OSDN Git Service

f691245a3a0bba686982d665a1c5e3f63e5c7563
[pf3gnuchains/gcc-fork.git] / gcc / profile.c
1 /* Calculate branch probabilities, and basic block execution counts. 
2    Copyright (C) 1990, 91-94, 96-98, 1999 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
7 This file is part of GNU CC.
8
9 GNU CC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GNU CC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GNU CC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 /* ??? Really should not put insns inside of LIBCALL sequences, when putting
25    insns after a call, should look for the insn setting the retval, and
26    insert the insns after that one.  */
27
28 /* ??? Register allocation should use basic block execution counts to
29    give preference to the most commonly executed blocks.  */
30
31 /* ??? The .da files are not safe.  Changing the program after creating .da
32    files or using different options when compiling with -fbranch-probabilities
33    can result the arc data not matching the program.  Maybe add instrumented
34    arc count to .bbg file?  Maybe check whether PFG matches the .bbg file?  */
35
36 /* ??? Should calculate branch probabilities before instrumenting code, since
37    then we can use arc counts to help decide which arcs to instrument.  */
38
39 /* ??? Rearrange code so that the most frequently executed arcs become from
40    one block to the next block (i.e. a fall through), move seldom executed
41    code outside of loops even at the expense of adding a few branches to
42    achieve this, see Dain Sample's UC Berkeley thesis.  */
43
44 #include "config.h"
45 #include "system.h"
46 #include "rtl.h"
47 #include "tree.h"
48 #include "flags.h"
49 #include "insn-flags.h"
50 #include "insn-config.h"
51 #include "output.h"
52 #include "regs.h"
53 #include "function.h"
54 #include "output.h"
55 #include "gcov-io.h"
56 #include "toplev.h"
57 #include "ggc.h"
58
59 /* One of these is dynamically created whenever we identify an arc in the
60    function.  */
61
62 struct adj_list
63 {
64   int source;
65   int target;
66   int arc_count;
67   unsigned int count_valid : 1;
68   unsigned int on_tree : 1;
69   unsigned int fake : 1;
70   unsigned int fall_through : 1;
71   rtx branch_insn;
72   struct adj_list *pred_next;
73   struct adj_list *succ_next;
74 };
75
76 #define ARC_TARGET(ARCPTR) (ARCPTR->target)
77 #define ARC_SOURCE(ARCPTR) (ARCPTR->source)
78 #define ARC_COUNT(ARCPTR)  (ARCPTR->arc_count)
79
80 /* Count the number of basic blocks, and create an array of these structures,
81    one for each bb in the function.  */
82
83 struct bb_info
84 {
85   struct adj_list *succ;
86   struct adj_list *pred;
87   int succ_count;
88   int pred_count;
89   int exec_count;
90   unsigned int count_valid : 1;
91   unsigned int on_tree : 1;
92   rtx first_insn;
93 };
94
95 /* Indexed by label number, gives the basic block number containing that
96    label.  */
97
98 static int *label_to_bb;
99
100 /* Number of valid entries in the label_to_bb array.  */
101
102 static int label_to_bb_size;
103
104 /* Indexed by block index, holds the basic block graph.  */
105
106 static struct bb_info *bb_graph;
107
108 /* Name and file pointer of the output file for the basic block graph.  */
109
110 static char *bbg_file_name;
111 static FILE *bbg_file;
112
113 /* Name and file pointer of the input file for the arc count data.  */
114
115 static char *da_file_name;
116 static FILE *da_file;
117
118 /* Pointer of the output file for the basic block/line number map. */
119 static FILE *bb_file;
120
121 /* Last source file name written to bb_file. */
122
123 static char *last_bb_file_name;
124
125 /* Indicates whether the next line number note should be output to
126    bb_file or not.  Used to eliminate a redundant note after an
127    expanded inline function call.  */
128
129 static int ignore_next_note;
130
131 /* Used by final, for allocating the proper amount of storage for the
132    instrumented arc execution counts.  */
133
134 int count_instrumented_arcs;
135
136 /* Number of executions for the return label.  */
137
138 int return_label_execution_count;
139
140 /* Collect statistics on the performance of this pass for the entire source
141    file.  */
142
143 static int total_num_blocks;
144 static int total_num_arcs;
145 static int total_num_arcs_instrumented;
146 static int total_num_blocks_created;
147 static int total_num_passes;
148 static int total_num_times_called;
149 static int total_hist_br_prob[20];
150 static int total_num_never_executed;
151 static int total_num_branches;
152
153 /* Forward declarations.  */
154 static void init_arc PROTO((struct adj_list *, int, int, rtx));
155 static void find_spanning_tree PROTO((int));
156 static void expand_spanning_tree PROTO((int));
157 static void fill_spanning_tree PROTO((int));
158 static void init_arc_profiler PROTO((void));
159 static void output_arc_profiler PROTO((int, rtx));
160 static void instrument_arcs PROTO((rtx, int, FILE *));
161 static void output_gcov_string PROTO((const char *, long));
162 static int tablejump_entry_p PROTO((rtx, rtx));
163
164 #ifndef LONG_TYPE_SIZE
165 #define LONG_TYPE_SIZE BITS_PER_WORD
166 #endif
167
168 /* If non-zero, we need to output a constructor to set up the
169    per-object-file data. */
170 static int need_func_profiler = 0;
171
172 \f
173 /* Add arc instrumentation code to the entire insn chain.
174
175    F is the first insn of the chain.
176    NUM_BLOCKS is the number of basic blocks found in F.
177    DUMP_FILE, if nonzero, is an rtl dump file we can write to.  */
178
179 static void
180 instrument_arcs (f, num_blocks, dump_file)
181      rtx f;
182      int num_blocks;
183      FILE *dump_file;
184 {
185   register int i;
186   register struct adj_list *arcptr, *backptr;
187   int num_arcs = 0;
188   int num_instr_arcs = 0;
189   rtx insn;
190
191   /* Instrument the program start.  */
192   /* Handle block 0 specially, since it will always be instrumented,
193      but it doesn't have a valid first_insn or branch_insn.  We must
194      put the instructions before the NOTE_INSN_FUNCTION_BEG note, so
195      that they don't clobber any of the parameters of the current
196      function.  */
197   for (insn = f; insn; insn = NEXT_INSN (insn))
198     if (GET_CODE (insn) == NOTE
199         && NOTE_LINE_NUMBER (insn) == NOTE_INSN_FUNCTION_BEG)
200       break;
201   insn = PREV_INSN (insn);
202   need_func_profiler = 1;
203   output_arc_profiler (total_num_arcs_instrumented + num_instr_arcs++, insn);
204
205   for (i = 1; i < num_blocks; i++)
206     for (arcptr = bb_graph[i].succ; arcptr; arcptr = arcptr->succ_next)
207       if (! arcptr->on_tree)
208         {
209           if (dump_file)
210             fprintf (dump_file, "Arc %d to %d instrumented\n", i,
211                      ARC_TARGET (arcptr));
212
213           /* Check to see if this arc is the only exit from its source block,
214              or the only entrance to its target block.  In either case,
215              we don't need to create a new block to instrument the arc.  */
216           
217           if (bb_graph[i].succ == arcptr && arcptr->succ_next == 0)
218             {
219               /* Instrument the source block.  */
220               output_arc_profiler (total_num_arcs_instrumented
221                                    + num_instr_arcs++,
222                                    PREV_INSN (bb_graph[i].first_insn));
223             }
224           else if (arcptr == bb_graph[ARC_TARGET (arcptr)].pred
225                    && arcptr->pred_next == 0)
226             {
227               /* Instrument the target block.  */
228               output_arc_profiler (total_num_arcs_instrumented
229                                    + num_instr_arcs++, 
230                                    PREV_INSN (bb_graph[ARC_TARGET (arcptr)].first_insn));
231             }
232           else if (arcptr->fall_through)
233             {
234               /* This is a fall-through; put the instrumentation code after
235                  the branch that ends this block.  */
236               
237               for (backptr = bb_graph[i].succ; backptr;
238                    backptr = backptr->succ_next)
239                 if (backptr != arcptr)
240                   break;
241               
242               output_arc_profiler (total_num_arcs_instrumented
243                                    + num_instr_arcs++,
244                                    backptr->branch_insn);
245             }
246           else
247             {
248               /* Must emit a new basic block to hold the arc counting code.  */
249               enum rtx_code code = GET_CODE (PATTERN (arcptr->branch_insn));
250
251               if (code == SET)
252                 {
253                   /* Create the new basic block right after the branch.
254                      Invert the branch so that it jumps past the end of the new
255                      block.  The new block will consist of the instrumentation
256                      code, and a jump to the target of this arc.  */
257                   int this_is_simplejump = simplejump_p (arcptr->branch_insn);
258                   rtx new_label = gen_label_rtx ();
259                   rtx old_label, set_src;
260                   rtx after = arcptr->branch_insn;
261                   
262                   /* Simplejumps can't reach here.  */
263                   if (this_is_simplejump)
264                     abort ();
265
266                   /* We can't use JUMP_LABEL, because it won't be set if we
267                      are compiling without optimization.  */
268
269                   set_src = SET_SRC (single_set (arcptr->branch_insn));
270                   if (GET_CODE (set_src) == LABEL_REF)
271                     old_label = set_src;
272                   else if (GET_CODE (set_src) != IF_THEN_ELSE)
273                     abort ();
274                   else if (XEXP (set_src, 1) == pc_rtx)
275                     old_label = XEXP (XEXP (set_src, 2), 0);
276                   else
277                     old_label = XEXP (XEXP (set_src, 1), 0);
278
279                   /* Set the JUMP_LABEL so that redirect_jump will work.  */
280                   JUMP_LABEL (arcptr->branch_insn) = old_label;
281
282                   /* Add a use for OLD_LABEL that will be needed when we emit
283                      the JUMP_INSN below.  If we don't do this here,
284                      `invert_jump' might delete it for us.  We must add two
285                      when not optimizing, because the NUSES is zero now,
286                      but must be at least two to prevent the label from being
287                      deleted.  */
288                   LABEL_NUSES (old_label) += 2;
289                   
290                   /* Emit the insns for the new block in reverse order,
291                      since that is most convenient.  */
292
293                   if (this_is_simplejump)
294                     {
295                       after = NEXT_INSN (arcptr->branch_insn);
296                       if (! redirect_jump (arcptr->branch_insn, new_label))
297                         /* Don't know what to do if this branch won't
298                            redirect.  */
299                         abort ();
300                     }
301                   else
302                     {
303                       if (! invert_jump (arcptr->branch_insn, new_label))
304                         /* Don't know what to do if this branch won't invert.  */
305                         abort ();
306
307                       emit_label_after (new_label, after);
308                       LABEL_NUSES (new_label)++;
309                     }
310                   emit_barrier_after (after);
311                   emit_jump_insn_after (gen_jump (old_label), after);
312                   JUMP_LABEL (NEXT_INSN (after)) = old_label;
313                   
314                   /* Instrument the source arc.  */
315                   output_arc_profiler (total_num_arcs_instrumented
316                                        + num_instr_arcs++,
317                                        after);
318                   if (this_is_simplejump)
319                     {
320                       emit_label_after (new_label, after);
321                       LABEL_NUSES (new_label)++;
322                     }
323                 }
324               else if (code == ADDR_VEC || code == ADDR_DIFF_VEC)
325                 {
326                   /* A table jump.  Create a new basic block immediately
327                      after the table, by emitting a barrier, a label, a
328                      counting note, and a jump to the old label.  Put the
329                      new label in the table.  */
330                   
331                   rtx new_label = gen_label_rtx ();
332                   rtx old_lref, new_lref;
333                   int index;
334                   
335                   /* Must determine the old_label reference, do this
336                      by counting the arcs after this one, which will
337                      give the index of our label in the table.  */
338                   
339                   index = 0;
340                   for (backptr = arcptr->succ_next; backptr;
341                        backptr = backptr->succ_next)
342                     index++;
343                   
344                   old_lref = XVECEXP (PATTERN (arcptr->branch_insn),
345                                       (code == ADDR_DIFF_VEC), index);
346                   
347                   /* Emit the insns for the new block in reverse order,
348                      since that is most convenient.  */
349                   emit_jump_insn_after (gen_jump (XEXP (old_lref, 0)),
350                                         arcptr->branch_insn);
351                   JUMP_LABEL (NEXT_INSN (arcptr->branch_insn))
352                     = XEXP (old_lref, 0);
353
354                   /* Instrument the source arc.  */
355                   output_arc_profiler (total_num_arcs_instrumented
356                                        + num_instr_arcs++,
357                                        arcptr->branch_insn);
358
359                   emit_label_after (new_label, arcptr->branch_insn);
360                   LABEL_NUSES (NEXT_INSN (arcptr->branch_insn))++;
361                   emit_barrier_after (arcptr->branch_insn);
362                   
363                   /* Fix up the table jump.  */
364                   new_lref = gen_rtx_LABEL_REF (Pmode, new_label);
365                   XVECEXP (PATTERN (arcptr->branch_insn),
366                            (code == ADDR_DIFF_VEC), index) = new_lref;
367                 }
368               else
369                 abort ();
370
371               num_arcs += 1;
372               if (dump_file)
373                 fprintf (dump_file,
374                          "Arc %d to %d needed new basic block\n", i,
375                          ARC_TARGET (arcptr));
376             }
377         }
378   
379   total_num_arcs_instrumented += num_instr_arcs;
380   count_instrumented_arcs = total_num_arcs_instrumented;
381
382   total_num_blocks_created += num_arcs;
383   if (dump_file)
384     {
385       fprintf (dump_file, "%d arcs instrumented\n", num_instr_arcs);
386       fprintf (dump_file, "%d extra basic blocks created\n", num_arcs);
387     }
388 }
389
390 /* Output STRING to bb_file, surrounded by DELIMITER.  */
391
392 static void
393 output_gcov_string (string, delimiter)
394      const char *string;
395      long delimiter;
396 {
397   long temp;
398                         
399   /* Write a delimiter to indicate that a file name follows.  */
400   __write_long (delimiter, bb_file, 4);
401
402   /* Write the string.  */
403   temp = strlen (string) + 1;
404   fwrite (string, temp, 1, bb_file);
405
406   /* Append a few zeros, to align the output to a 4 byte boundary.  */
407   temp = temp & 0x3;
408   if (temp)
409     {
410       char c[4];
411
412       c[0] = c[1] = c[2] = c[3] = 0;
413       fwrite (c, sizeof (char), 4 - temp, bb_file);
414     }
415
416   /* Store another delimiter in the .bb file, just to make it easy to find the
417      end of the file name.  */
418   __write_long (delimiter, bb_file, 4);
419 }
420 \f
421 /* Return TRUE if this insn must be a tablejump entry insn.  This works for
422    the MIPS port, but may give false negatives for some targets.  */
423
424 static int
425 tablejump_entry_p (insn, label)
426      rtx insn, label;
427 {
428   rtx next = next_active_insn (insn);
429   enum rtx_code code = GET_CODE (PATTERN (next));
430
431   if (code != ADDR_DIFF_VEC && code != ADDR_VEC)
432     return 0;
433
434   if (PREV_INSN (next) == XEXP (label, 0))
435     return 1;
436
437   return 0;
438 }
439
440 /* Instrument and/or analyze program behavior based on program flow graph.
441    In either case, this function builds a flow graph for the function being
442    compiled.  The flow graph is stored in BB_GRAPH.
443
444    When FLAG_PROFILE_ARCS is nonzero, this function instruments the arcs in
445    the flow graph that are needed to reconstruct the dynamic behavior of the
446    flow graph.
447
448    When FLAG_BRANCH_PROBABILITIES is nonzero, this function reads auxiliary
449    information from a data file containing arc count information from previous
450    executions of the function being compiled.  In this case, the flow graph is
451    annotated with actual execution counts, which are later propagated into the
452    rtl for optimization purposes.
453
454    Main entry point of this file.  */
455
456 void
457 branch_prob (f, dump_file)
458      rtx f;
459      FILE *dump_file;
460 {
461   int i, num_blocks;
462   struct adj_list *arcptr;
463   int num_arcs, changes, passes;
464   int total, prob;
465   int hist_br_prob[20], num_never_executed, num_branches;
466   /* Set to non-zero if we got bad count information.  */
467   int bad_counts = 0;
468
469   /* start of a function.  */
470   if (flag_test_coverage)
471     output_gcov_string (current_function_name, (long) -2);
472
473   /* Execute this only if doing arc profiling or branch probabilities.  */
474   if (! profile_arc_flag && ! flag_branch_probabilities
475       && ! flag_test_coverage)
476     abort ();
477
478   total_num_times_called++;
479
480   /* Create an array label_to_bb of ints of size max_label_num.  */
481   label_to_bb_size = max_label_num ();
482   label_to_bb = (int *) oballoc (label_to_bb_size * sizeof (int));
483   bzero ((char *) label_to_bb, label_to_bb_size * sizeof (int));
484
485   /* Scan the insns in the function, count the number of basic blocks
486      present.  When a code label is passed, set label_to_bb[label] = bb
487      number.  */
488
489   /* The first block found will be block 1, so that function entry can be
490      block 0.  */
491
492   {
493     register RTX_CODE prev_code = JUMP_INSN;
494     register RTX_CODE code;
495     register rtx insn;
496     register int i;
497     int block_separator_emitted = 0;
498
499     ignore_next_note = 0;
500
501     for (insn = NEXT_INSN (f), i = 0; insn; insn = NEXT_INSN (insn))
502       {
503         code = GET_CODE (insn);
504
505         if (code == BARRIER)
506           ;
507         else if (code == CODE_LABEL)
508           /* This label is part of the next block, but we can't increment
509              block number yet since there might be multiple labels.  */
510           label_to_bb[CODE_LABEL_NUMBER (insn)] = i + 1;
511         /* We make NOTE_INSN_SETJMP notes into a block of their own, so that
512            they can be the target of the fake arc for the setjmp call.
513            This avoids creating cycles of fake arcs, which would happen if
514            the block after the setjmp call contained a call insn.  */
515         else if ((prev_code == JUMP_INSN || prev_code == CALL_INSN
516                   || prev_code == CODE_LABEL || prev_code == BARRIER)
517                  && (GET_RTX_CLASS (code) == 'i'
518                      || (code == NOTE
519                          && NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP)))
520           {
521             i += 1;
522
523             /* Emit the block separator if it hasn't already been emitted.  */
524             if (flag_test_coverage && ! block_separator_emitted)
525               {
526                 /* Output a zero to the .bb file to indicate that a new
527                    block list is starting.  */
528                 __write_long (0, bb_file, 4);
529               }
530             block_separator_emitted = 0;
531           }
532         /* If flag_test_coverage is true, then we must add an entry to the
533            .bb file for every note.  */
534         else if (code == NOTE && flag_test_coverage)
535           {
536             /* Must ignore the line number notes that immediately follow the
537                end of an inline function to avoid counting it twice.  There
538                is a note before the call, and one after the call.  */
539             if (NOTE_LINE_NUMBER (insn) == NOTE_REPEATED_LINE_NUMBER)
540               ignore_next_note = 1;
541             else if (NOTE_LINE_NUMBER (insn) > 0)
542               {
543                 if (ignore_next_note)
544                   ignore_next_note = 0;
545                 else
546                   {
547                     /* Emit a block separator here to ensure that a NOTE
548                        immediately following a JUMP_INSN or CALL_INSN will end
549                        up in the right basic block list.  */
550                     if ((prev_code == JUMP_INSN || prev_code == CALL_INSN
551                          || prev_code == CODE_LABEL || prev_code == BARRIER)
552                         && ! block_separator_emitted)
553                       {
554                         /* Output a zero to the .bb file to indicate that
555                            a new block list is starting.  */
556                         __write_long (0, bb_file, 4);
557
558                         block_separator_emitted = 1;
559                       }
560                     
561                     /* If this is a new source file, then output the file's
562                        name to the .bb file.  */
563                     if (! last_bb_file_name
564                         || strcmp (NOTE_SOURCE_FILE (insn),
565                                    last_bb_file_name))
566                       {
567                         if (last_bb_file_name)
568                           free (last_bb_file_name);
569                         last_bb_file_name = xstrdup (NOTE_SOURCE_FILE (insn));
570                         output_gcov_string (NOTE_SOURCE_FILE (insn), (long)-1);
571                       }
572
573                     /* Output the line number to the .bb file.  Must be done
574                        after the output_bb_profile_data() call, and after the
575                        file name is written, to ensure that it is correctly
576                        handled by gcov.  */
577                     __write_long (NOTE_LINE_NUMBER (insn), bb_file, 4);
578                   }
579               }
580           }
581
582         if (code != NOTE)
583           prev_code = code;
584         else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP)
585           prev_code = CALL_INSN;
586       }
587
588     /* Allocate last `normal' entry for bb_graph.  */
589
590     /* The last insn was a jump, call, or label.  In that case we have
591        a block at the end of the function with no insns.  */
592     if (prev_code == JUMP_INSN || prev_code == CALL_INSN
593         || prev_code == CODE_LABEL || prev_code == BARRIER)
594       {
595         i++;
596
597         /* Emit the block separator if it hasn't already been emitted.  */
598         if (flag_test_coverage && ! block_separator_emitted)
599           {
600             /* Output a zero to the .bb file to indicate that a new
601                block list is starting.  */
602             __write_long (0, bb_file, 4);
603           }
604       }
605
606     /* Create another block to stand for EXIT, and make all return insns, and
607        the last basic block point here.  Add one more to account for block
608        zero.  */
609     num_blocks = i + 2;
610   }
611
612   total_num_blocks += num_blocks;
613   if (dump_file)
614     fprintf (dump_file, "%d basic blocks\n", num_blocks);
615
616   /* If we are only doing test coverage here, then return now.  */
617   if (! profile_arc_flag && ! flag_branch_probabilities)
618     return;
619
620   /* Create and initialize the arrays that will hold bb_graph
621      and execution count info.  */
622
623   bb_graph = (struct bb_info *) alloca (num_blocks * sizeof (struct bb_info));
624   bzero ((char *) bb_graph, (sizeof (struct bb_info) * num_blocks));
625
626   {
627     /* Scan the insns again:
628        - at the entry to each basic block, increment the predecessor count
629        (and successor of previous block) if it is a fall through entry,
630        create adj_list entries for this and the previous block
631        - at each jump insn, increment predecessor/successor counts for
632        target/source basic blocks, add this insn to pred/succ lists.
633
634        This also cannot be broken out as a separate subroutine
635        because it uses `alloca'.  */
636
637     register RTX_CODE prev_code = JUMP_INSN;
638     register RTX_CODE code;
639     register rtx insn;
640     register int i;
641     int fall_through = 0;
642     struct adj_list *arcptr;
643     int dest = 0;
644
645     /* Block 0 always falls through to block 1.  */
646     num_arcs = 0;
647     arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
648     init_arc (arcptr, 0, 1, 0);
649     arcptr->fall_through = 1;
650     num_arcs++;
651
652     /* Add a fake fall through arc from the last block to block 0, to make the
653        graph complete.  */
654     arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
655     init_arc (arcptr, num_blocks - 1, 0, 0);
656     arcptr->fake = 1;
657     num_arcs++;
658
659     /* Exit must be one node of the graph, and all exits from the function
660        must point there.  When see a return branch, must point the arc to the
661        exit node.  */
662
663     /* Must start scan with second insn in function as above.  */
664     for (insn = NEXT_INSN (f), i = 0; insn; insn = NEXT_INSN (insn))
665       {
666         code = GET_CODE (insn);
667
668         if (code == BARRIER)
669           fall_through = 0;
670         else if (code == CODE_LABEL)
671           ;
672         /* We make NOTE_INSN_SETJMP notes into a block of their own, so that
673            they can be the target of the fake arc for the setjmp call.
674            This avoids creating cycles of fake arcs, which would happen if
675            the block after the setjmp call ended with a call.  */
676         else if ((prev_code == JUMP_INSN || prev_code == CALL_INSN
677                   || prev_code == CODE_LABEL || prev_code == BARRIER)
678                  && (GET_RTX_CLASS (code) == 'i'
679                      || (code == NOTE
680                          && NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP)))
681           {
682             /* This is the first insn of the block.  */
683             i += 1;
684             if (fall_through)
685               {
686                 arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
687                 init_arc (arcptr, i - 1, i, 0);
688                 arcptr->fall_through = 1;
689
690                 num_arcs++;
691               }
692             fall_through = 1;
693             bb_graph[i].first_insn = insn;
694           }
695         else if (code == NOTE)
696           {;}
697
698         if (code == CALL_INSN)
699           {
700             /* In the normal case, the call returns, and this is just like
701                a branch fall through.  */
702             fall_through = 1;
703
704             /* Setjmp may return more times than called, so to make the graph
705                solvable, add a fake arc from the function entrance to the
706                next block.
707
708                All other functions may return fewer times than called (if
709                a descendent call longjmp or exit), so to make the graph
710                solvable, add a fake arc to the function exit from the
711                current block.
712
713                Distinguish the cases by checking for a SETJUMP note.
714                A call_insn can be the last ins of a function, so must check
715                to see if next insn actually exists.  */
716             arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
717             if (NEXT_INSN (insn)
718                 && GET_CODE (NEXT_INSN (insn)) == NOTE
719                 && NOTE_LINE_NUMBER (NEXT_INSN (insn)) == NOTE_INSN_SETJMP)
720               init_arc (arcptr, 0, i+1, insn);
721             else
722               init_arc (arcptr, i, num_blocks-1, insn);
723             arcptr->fake = 1;
724             num_arcs++;
725           }
726         else if (code == JUMP_INSN)
727           {
728             rtx tem, pattern = PATTERN (insn);
729             rtx tablejump = 0;
730
731             /* If running without optimization, then jump label won't be valid,
732                so we must search for the destination label in that case.
733                We have to handle tablejumps and returns specially anyways, so
734                we don't check the JUMP_LABEL at all here.  */
735
736             /* ??? This code should be rewritten.  We need a more elegant way
737                to find the LABEL_REF.  We need a more elegant way to
738                differentiate tablejump entries from computed gotos.
739                We should perhaps reuse code from flow to compute the CFG
740                instead of trying to compute it here.
741
742                We can't use current_function_has_computed_jump, because that
743                is calculated later by flow.  We can't use computed_jump_p,
744                because that returns true for tablejump entry insns for some
745                targets, e.g. HPPA and MIPS.  */
746
747             if (GET_CODE (pattern) == PARALLEL)
748               {
749                 /* This assumes that PARALLEL jumps with a USE are
750                    tablejump entry jumps.  The same assumption can be found
751                    in computed_jump_p.  */
752                 /* Make an arc from this jump to the label of the
753                    jump table.  This will instrument the number of
754                    times the switch statement is executed.  */
755                 if (GET_CODE (XVECEXP (pattern, 0, 1)) == USE)
756                   {
757                     tem = XEXP (XVECEXP (pattern, 0, 1), 0);
758                     if (GET_CODE (tem) != LABEL_REF)
759                       abort ();
760                     dest = label_to_bb[CODE_LABEL_NUMBER (XEXP (tem, 0))];
761                   }
762                 else if (GET_CODE (XVECEXP (pattern, 0, 0)) == SET
763                          && SET_DEST (XVECEXP (pattern, 0, 0)) == pc_rtx)
764                   {
765                     tem = SET_SRC (XVECEXP (pattern, 0, 0));
766                     if (GET_CODE (tem) == PLUS
767                         && GET_CODE (XEXP (tem, 1)) == LABEL_REF)
768                       {
769                         tem = XEXP (tem, 1);
770                         dest = label_to_bb [CODE_LABEL_NUMBER (XEXP (tem, 0))];
771                       }
772                   }
773                 else
774                   abort ();
775               }
776             else if (GET_CODE (pattern) == ADDR_VEC
777                      || GET_CODE (pattern) == ADDR_DIFF_VEC)
778               tablejump = pattern;
779             else if (GET_CODE (pattern) == RETURN)
780               dest = num_blocks - 1;
781             else if (GET_CODE (pattern) != SET)
782               abort ();
783             else if ((tem = SET_SRC (pattern))
784                      && GET_CODE (tem) == LABEL_REF)
785               dest = label_to_bb[CODE_LABEL_NUMBER (XEXP (tem, 0))];
786             /* Recognize HPPA table jump entry.  This code is similar to
787                the code above in the PARALLEL case.  */
788             else if (GET_CODE (tem) == PLUS
789                      && GET_CODE (XEXP (tem, 0)) == MEM
790                      && GET_CODE (XEXP (XEXP (tem, 0), 0)) == PLUS
791                      && GET_CODE (XEXP (XEXP (XEXP (tem, 0), 0), 0)) == PC
792                      && GET_CODE (XEXP (tem, 1)) == LABEL_REF
793                      && tablejump_entry_p (insn, XEXP (tem, 1)))
794               dest = label_to_bb[CODE_LABEL_NUMBER (XEXP (XEXP (tem, 1), 0))];
795             /* Recognize the MIPS table jump entry.  */
796             else if (GET_CODE (tem) == PLUS
797                      && GET_CODE (XEXP (tem, 0)) == REG
798                      && GET_CODE (XEXP (tem, 1)) == LABEL_REF
799                      && tablejump_entry_p (insn, XEXP (tem, 1)))
800               dest = label_to_bb[CODE_LABEL_NUMBER (XEXP (XEXP (tem, 1), 0))];
801             else
802               {
803                 rtx label_ref;
804
805                 /* Must be an IF_THEN_ELSE branch.  If it isn't, assume it
806                    is a computed goto, which aren't supported yet.  */
807                 if (GET_CODE (tem) != IF_THEN_ELSE)
808                   fatal ("-fprofile-arcs does not support computed gotos");
809                 if (XEXP (tem, 1) != pc_rtx)
810                   label_ref = XEXP (tem, 1);
811                 else
812                   label_ref = XEXP (tem, 2);
813                 dest = label_to_bb[CODE_LABEL_NUMBER (XEXP (label_ref, 0))];
814               }
815
816             if (tablejump)
817               {
818                 int diff_vec_p = GET_CODE (tablejump) == ADDR_DIFF_VEC;
819                 int len = XVECLEN (tablejump, diff_vec_p);
820                 int k;
821
822                 for (k = 0; k < len; k++)
823                   {
824                     rtx tem = XEXP (XVECEXP (tablejump, diff_vec_p, k), 0);
825                     dest = label_to_bb[CODE_LABEL_NUMBER (tem)];
826
827                     arcptr = (struct adj_list *) alloca (sizeof(struct adj_list));
828                     init_arc (arcptr, i, dest, insn);
829
830                     num_arcs++;
831                   }
832               }
833             else
834               {
835                 arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
836                 init_arc (arcptr, i, dest, insn);
837
838                 num_arcs++;
839               }
840
841             /* Determine whether or not this jump will fall through.
842                Unconditional jumps and returns are not always followed by
843                barriers.  */
844             pattern = PATTERN (insn);
845             if (GET_CODE (pattern) == PARALLEL
846                 || GET_CODE (pattern) == RETURN)
847               fall_through = 0;
848             else if (GET_CODE (pattern) == ADDR_VEC
849                      || GET_CODE (pattern) == ADDR_DIFF_VEC)
850               /* These aren't actually jump insns, but they never fall
851                  through, so...  */
852               fall_through = 0;
853             else
854               {
855                 if (GET_CODE (pattern) != SET || SET_DEST (pattern) != pc_rtx)
856                   abort ();
857                 if (GET_CODE (SET_SRC (pattern)) != IF_THEN_ELSE)
858                   fall_through = 0;
859               }
860           }
861
862         if (code != NOTE)
863           prev_code = code;
864         else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_SETJMP)
865           {
866             /* Make a fake insn to tag our notes on.  */
867             bb_graph[i].first_insn = insn
868               = emit_insn_after (gen_rtx_USE (VOIDmode, stack_pointer_rtx),
869                                  insn);
870             prev_code = CALL_INSN;
871           }
872       }
873
874     /* If the code at the end of the function would give a new block, then
875        do the following.  */
876
877     if (prev_code == JUMP_INSN || prev_code == CALL_INSN
878         || prev_code == CODE_LABEL || prev_code == BARRIER)
879       {
880         if (fall_through)
881           {
882             arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
883             init_arc (arcptr, i, i + 1, 0);
884             arcptr->fall_through = 1;
885
886             num_arcs++;
887           }
888           
889         /* This may not be a real insn, but that should not cause a problem.  */
890         bb_graph[i+1].first_insn = get_last_insn ();
891       }
892
893     /* There is always a fake arc from the last block of the function
894        to the function exit block.  */
895     arcptr = (struct adj_list *) alloca (sizeof (struct adj_list));
896     init_arc (arcptr, num_blocks-2, num_blocks-1, 0);
897     arcptr->fake = 1;
898     num_arcs++;
899   }
900
901   total_num_arcs += num_arcs;
902   if (dump_file)
903     fprintf (dump_file, "%d arcs\n", num_arcs);
904
905   /* Create spanning tree from basic block graph, mark each arc that is
906      on the spanning tree.  */
907
908   /* To reduce the instrumentation cost, make two passes over the tree.
909      First, put as many must-split (crowded and fake) arcs on the tree as
910      possible, then on the second pass fill in the rest of the tree.
911      Note that the spanning tree is considered undirected, so that as many
912      must-split arcs as possible can be put on it.
913
914      Fallthrough arcs which are crowded should not be chosen on the first
915      pass, since they do not require creating a new basic block.  These
916      arcs will have fall_through set.  */
917
918   find_spanning_tree (num_blocks);
919
920   /* Create a .bbg file from which gcov can reconstruct the basic block
921      graph.  First output the number of basic blocks, and then for every
922      arc output the source and target basic block numbers.
923      NOTE: The format of this file must be compatible with gcov.  */
924
925   if (flag_test_coverage)
926     {
927       int flag_bits;
928
929       __write_long (num_blocks, bbg_file, 4);
930       __write_long (num_arcs, bbg_file, 4);
931
932       for (i = 0; i < num_blocks; i++)
933         {
934           long count = 0;
935           for (arcptr = bb_graph[i].succ; arcptr; arcptr = arcptr->succ_next)
936             count++;
937           __write_long (count, bbg_file, 4);
938
939           for (arcptr = bb_graph[i].succ; arcptr; arcptr = arcptr->succ_next)
940             {
941               flag_bits = 0;
942               if (arcptr->on_tree)
943                 flag_bits |= 0x1;
944               if (arcptr->fake)
945                 flag_bits |= 0x2;
946               if (arcptr->fall_through)
947                 flag_bits |= 0x4;
948
949               __write_long (ARC_TARGET (arcptr), bbg_file, 4);
950               __write_long (flag_bits, bbg_file, 4);
951             }
952         }
953
954       /* Emit a -1 to separate the list of all arcs from the list of
955          loop back edges that follows.  */
956       __write_long (-1, bbg_file, 4);
957     }
958
959   /* For each arc not on the spanning tree, add counting code as rtl.  */
960
961   if (profile_arc_flag)
962     {
963       instrument_arcs (f, num_blocks, dump_file);
964       allocate_reg_info (max_reg_num (), FALSE, FALSE);
965     }
966
967   /* Execute the rest only if doing branch probabilities.  */
968   if (! flag_branch_probabilities)
969     return;
970
971   /* For each arc not on the spanning tree, set its execution count from
972      the .da file.  */
973
974   /* The first count in the .da file is the number of times that the function
975      was entered.  This is the exec_count for block zero.  */
976
977   num_arcs = 0;
978   for (i = 0; i < num_blocks; i++)
979     for (arcptr = bb_graph[i].succ; arcptr; arcptr = arcptr->succ_next)
980       if (! arcptr->on_tree)
981         {
982           num_arcs++;
983           if (da_file)
984             {
985               long value;
986               __read_long (&value, da_file, 8);
987               ARC_COUNT (arcptr) = value;
988             }
989           else
990             ARC_COUNT (arcptr) = 0;
991           arcptr->count_valid = 1;
992           bb_graph[i].succ_count--;
993           bb_graph[ARC_TARGET (arcptr)].pred_count--;
994         }
995
996   if (dump_file)
997     fprintf (dump_file, "%d arc counts read\n", num_arcs);
998
999   /* For every block in the file,
1000      - if every exit/entrance arc has a known count, then set the block count
1001      - if the block count is known, and every exit/entrance arc but one has
1002        a known execution count, then set the count of the remaining arc
1003
1004      As arc counts are set, decrement the succ/pred count, but don't delete
1005      the arc, that way we can easily tell when all arcs are known, or only
1006      one arc is unknown.  */
1007
1008   /* The order that the basic blocks are iterated through is important.
1009      Since the code that finds spanning trees starts with block 0, low numbered
1010      arcs are put on the spanning tree in preference to high numbered arcs.
1011      Hence, most instrumented arcs are at the end.  Graph solving works much
1012      faster if we propagate numbers from the end to the start.
1013      
1014      This takes an average of slightly more than 3 passes.  */
1015
1016   changes = 1;
1017   passes = 0;
1018   while (changes)
1019     {
1020       passes++;
1021       changes = 0;
1022
1023       for (i = num_blocks - 1; i >= 0; i--)
1024         {
1025           struct bb_info *binfo = &bb_graph[i];
1026           if (! binfo->count_valid)
1027             {
1028               if (binfo->succ_count == 0)
1029                 {
1030                   total = 0;
1031                   for (arcptr = binfo->succ; arcptr;
1032                        arcptr = arcptr->succ_next)
1033                     total += ARC_COUNT (arcptr);
1034                   binfo->exec_count = total;
1035                   binfo->count_valid = 1;
1036                   changes = 1;
1037                 }
1038               else if (binfo->pred_count == 0)
1039                 {
1040                   total = 0;
1041                   for (arcptr = binfo->pred; arcptr;
1042                        arcptr = arcptr->pred_next)
1043                     total += ARC_COUNT (arcptr);
1044                   binfo->exec_count = total;
1045                   binfo->count_valid = 1;
1046                   changes = 1;
1047                 }
1048             }
1049           if (binfo->count_valid)
1050             {
1051               if (binfo->succ_count == 1)
1052                 {
1053                   total = 0;
1054                   /* One of the counts will be invalid, but it is zero,
1055                      so adding it in also doesn't hurt.  */
1056                   for (arcptr = binfo->succ; arcptr;
1057                        arcptr = arcptr->succ_next)
1058                     total += ARC_COUNT (arcptr);
1059                   /* Calculate count for remaining arc by conservation.  */
1060                   total = binfo->exec_count - total;
1061                   /* Search for the invalid arc, and set its count.  */
1062                   for (arcptr = binfo->succ; arcptr;
1063                        arcptr = arcptr->succ_next)
1064                     if (! arcptr->count_valid)
1065                       break;
1066                   if (! arcptr)
1067                     abort ();
1068                   arcptr->count_valid = 1;
1069                   ARC_COUNT (arcptr) = total;
1070                   binfo->succ_count--;
1071                   
1072                   bb_graph[ARC_TARGET (arcptr)].pred_count--;
1073                   changes = 1;
1074                 }
1075               if (binfo->pred_count == 1)
1076                 {
1077                   total = 0;
1078                   /* One of the counts will be invalid, but it is zero,
1079                      so adding it in also doesn't hurt.  */
1080                   for (arcptr = binfo->pred; arcptr;
1081                        arcptr = arcptr->pred_next)
1082                     total += ARC_COUNT (arcptr);
1083                   /* Calculate count for remaining arc by conservation.  */
1084                   total = binfo->exec_count - total;
1085                   /* Search for the invalid arc, and set its count.  */
1086                   for (arcptr = binfo->pred; arcptr;
1087                        arcptr = arcptr->pred_next)
1088                     if (! arcptr->count_valid)
1089                       break;
1090                   if (! arcptr)
1091                     abort ();
1092                   arcptr->count_valid = 1;
1093                   ARC_COUNT (arcptr) = total;
1094                   binfo->pred_count--;
1095                   
1096                   bb_graph[ARC_SOURCE (arcptr)].succ_count--;
1097                   changes = 1;
1098                 }
1099             }
1100         }
1101     }
1102
1103   total_num_passes += passes;
1104   if (dump_file)
1105     fprintf (dump_file, "Graph solving took %d passes.\n\n", passes);
1106
1107   /* If the graph has been correctly solved, every block will have a
1108      succ and pred count of zero.  */
1109   for (i = 0; i < num_blocks; i++)
1110     {
1111       struct bb_info *binfo = &bb_graph[i];
1112       if (binfo->succ_count || binfo->pred_count)
1113         abort ();
1114     }
1115
1116   /* For every arc, calculate its branch probability and add a reg_note
1117      to the branch insn to indicate this.  */
1118
1119   for (i = 0; i < 20; i++)
1120     hist_br_prob[i] = 0;
1121   num_never_executed = 0;
1122   num_branches = 0;
1123
1124   for (i = 0; i < num_blocks; i++)
1125     {
1126       struct bb_info *binfo = &bb_graph[i];
1127
1128       total = binfo->exec_count;
1129       for (arcptr = binfo->succ; arcptr; arcptr = arcptr->succ_next)
1130         {
1131           if (arcptr->branch_insn)
1132             {
1133               /* This calculates the branch probability as an integer between
1134                  0 and REG_BR_PROB_BASE, properly rounded to the nearest
1135                  integer.  Perform the arithmetic in double to avoid
1136                  overflowing the range of ints.  */
1137
1138               if (total == 0)
1139                 prob = -1;
1140               else
1141                 {
1142                   rtx pat = PATTERN (arcptr->branch_insn);
1143                   
1144                   prob = (((double)ARC_COUNT (arcptr) * REG_BR_PROB_BASE)
1145                           + (total >> 1)) / total;
1146                   if (prob < 0 || prob > REG_BR_PROB_BASE)
1147                     {
1148                       if (dump_file)
1149                         fprintf (dump_file, "bad count: prob for %d-%d thought to be %d (forcibly normalized)\n",
1150                                  ARC_SOURCE (arcptr), ARC_TARGET (arcptr),
1151                                  prob);
1152
1153                       bad_counts = 1;
1154                       prob = REG_BR_PROB_BASE / 2;
1155                     }
1156                   
1157                   /* Match up probability with JUMP pattern.  */
1158
1159                   if (GET_CODE (pat) == SET
1160                       && GET_CODE (SET_SRC (pat)) == IF_THEN_ELSE)
1161                     {
1162                       if (ARC_TARGET (arcptr) == ARC_SOURCE (arcptr) + 1)
1163                         {
1164                           /* A fall through arc should never have a
1165                              branch insn.  */
1166                           abort ();
1167                         }
1168                       else
1169                         {
1170                           /* This is the arc for the taken branch.  */
1171                           if (GET_CODE (XEXP (SET_SRC (pat), 2)) != PC)
1172                             prob = REG_BR_PROB_BASE - prob;
1173                         }
1174                     }
1175                 }
1176               
1177               if (prob == -1)
1178                 num_never_executed++;
1179               else
1180                 {
1181                   int index = prob * 20 / REG_BR_PROB_BASE;
1182                   if (index == 20)
1183                     index = 19;
1184                   hist_br_prob[index]++;
1185                 }
1186               num_branches++;
1187               
1188               REG_NOTES (arcptr->branch_insn)
1189                 = gen_rtx_EXPR_LIST (REG_BR_PROB, GEN_INT (prob),
1190                                      REG_NOTES (arcptr->branch_insn));
1191             }
1192         }
1193
1194       /* Add a REG_EXEC_COUNT note to the first instruction of this block.  */
1195       if (! binfo->first_insn 
1196           || GET_RTX_CLASS (GET_CODE (binfo->first_insn)) != 'i')
1197         {
1198           /* Block 0 is a fake block representing function entry, and does
1199              not have a real first insn.  The second last block might not
1200              begin with a real insn.  */
1201           if (i == num_blocks - 1)
1202             return_label_execution_count = total;
1203           else if (i != 0 && i != num_blocks - 2)
1204             abort ();
1205         }
1206       else
1207         {
1208           REG_NOTES (binfo->first_insn)
1209             = gen_rtx_EXPR_LIST (REG_EXEC_COUNT, GEN_INT (total),
1210                                  REG_NOTES (binfo->first_insn));
1211           if (i == num_blocks - 1)
1212             return_label_execution_count = total;
1213         }
1214     }
1215   
1216   /* This should never happen.  */
1217   if (bad_counts)
1218     warning ("Arc profiling: some arc counts were bad.");
1219
1220   if (dump_file)
1221     {
1222       fprintf (dump_file, "%d branches\n", num_branches);
1223       fprintf (dump_file, "%d branches never executed\n",
1224                num_never_executed);
1225       if (num_branches)
1226         for (i = 0; i < 10; i++)
1227           fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1228                    (hist_br_prob[i]+hist_br_prob[19-i])*100/num_branches,
1229                    5*i, 5*i+5);
1230
1231       total_num_branches += num_branches;
1232       total_num_never_executed += num_never_executed;
1233       for (i = 0; i < 20; i++)
1234         total_hist_br_prob[i] += hist_br_prob[i];
1235     }
1236
1237 }
1238 \f
1239 /* Initialize a new arc.
1240    ARCPTR is the empty adj_list this function fills in.
1241    SOURCE is the block number of the source block.
1242    TARGET is the block number of the target block.
1243    INSN is the insn which transfers control from SOURCE to TARGET,
1244    or zero if the transfer is implicit.  */
1245
1246 static void
1247 init_arc (arcptr, source, target, insn)
1248      struct adj_list *arcptr;
1249      int source, target;
1250      rtx insn;
1251 {
1252   ARC_TARGET (arcptr) = target;
1253   ARC_SOURCE (arcptr) = source;
1254
1255   ARC_COUNT (arcptr) = 0;
1256   arcptr->count_valid = 0;
1257   arcptr->on_tree = 0;
1258   arcptr->fake = 0;
1259   arcptr->fall_through = 0;
1260   arcptr->branch_insn = insn;
1261
1262   arcptr->succ_next = bb_graph[source].succ;
1263   bb_graph[source].succ = arcptr;
1264   bb_graph[source].succ_count++;
1265
1266   arcptr->pred_next = bb_graph[target].pred;
1267   bb_graph[target].pred = arcptr;
1268   bb_graph[target].pred_count++;
1269 }
1270
1271 /* This function searches all of the arcs in the program flow graph, and puts
1272    as many bad arcs as possible onto the spanning tree.  Bad arcs include
1273    fake arcs (needed for setjmp(), longjmp(), exit()) which MUST be on the
1274    spanning tree as they can't be instrumented.  Also, arcs which must be
1275    split when instrumented should be part of the spanning tree if possible.  */
1276
1277 static void
1278 find_spanning_tree (num_blocks)
1279      int num_blocks;
1280 {
1281   int i;
1282   struct adj_list *arcptr;
1283   struct bb_info *binfo = &bb_graph[0];
1284
1285   /* Fake arcs must be part of the spanning tree, and are always safe to put
1286      on the spanning tree.  Fake arcs will either be a successor of node 0,
1287      a predecessor of the last node, or from the last node to node 0.  */
1288
1289   for (arcptr = bb_graph[0].succ; arcptr; arcptr = arcptr->succ_next)
1290     if (arcptr->fake)
1291       {
1292         /* Adding this arc should never cause a cycle.  This is a fatal 
1293            error if it would.  */
1294         if (bb_graph[ARC_TARGET (arcptr)].on_tree && binfo->on_tree)
1295           abort();
1296         else
1297           {
1298             arcptr->on_tree = 1;
1299             bb_graph[ARC_TARGET (arcptr)].on_tree = 1;
1300             binfo->on_tree = 1;
1301           }
1302       }
1303
1304   binfo = &bb_graph[num_blocks-1];
1305   for (arcptr = binfo->pred; arcptr; arcptr = arcptr->pred_next)
1306     if (arcptr->fake)
1307       {
1308         /* Adding this arc should never cause a cycle.  This is a fatal 
1309            error if it would.  */
1310         if (bb_graph[ARC_SOURCE (arcptr)].on_tree && binfo->on_tree)
1311           abort();
1312         else
1313           {
1314             arcptr->on_tree = 1;
1315             bb_graph[ARC_SOURCE (arcptr)].on_tree = 1;
1316             binfo->on_tree = 1;
1317           }
1318       }
1319   /* The only entrace to node zero is a fake arc.  */
1320   bb_graph[0].pred->on_tree = 1;
1321   
1322   /* Arcs which are crowded at both the source and target should be put on
1323      the spanning tree if possible, except for fall_throuch arcs which never
1324      require adding a new block even if crowded, add arcs with the same source
1325      and dest which must always be instrumented.  */
1326   for (i = 0; i < num_blocks; i++)
1327     {
1328       binfo = &bb_graph[i];
1329
1330       for (arcptr = binfo->succ; arcptr; arcptr = arcptr->succ_next)
1331         if (! ((binfo->succ == arcptr && arcptr->succ_next == 0)
1332                || (bb_graph[ARC_TARGET (arcptr)].pred
1333                    && arcptr->pred_next == 0))
1334             && ! arcptr->fall_through
1335             && ARC_TARGET (arcptr) != i)
1336           {
1337             /* This is a crowded arc at both source and target.  Try to put
1338                in on the spanning tree.  Can do this if either the source or
1339                target block is not yet on the tree.  */
1340             if (! bb_graph[ARC_TARGET (arcptr)].on_tree || ! binfo->on_tree)
1341               {
1342                 arcptr->on_tree = 1;
1343                 bb_graph[ARC_TARGET (arcptr)].on_tree = 1;
1344                 binfo->on_tree = 1;
1345               }
1346           }
1347     }
1348
1349   /* Clear all of the basic block on_tree bits, so that we can use them to
1350      create the spanning tree.  */
1351   for (i = 0; i < num_blocks; i++)
1352     bb_graph[i].on_tree = 0;
1353
1354   /* Now fill in the spanning tree until every basic block is on it.
1355      Don't put the 0 to 1 fall through arc on the tree, since it is 
1356      always cheap to instrument, so start filling the tree from node 1.  */
1357
1358   for (i = 1; i < num_blocks; i++)
1359     for (arcptr = bb_graph[i].succ; arcptr; arcptr = arcptr->succ_next)
1360       if (! arcptr->on_tree
1361           && ! bb_graph[ARC_TARGET (arcptr)].on_tree)
1362         {
1363           fill_spanning_tree (i);
1364           break;
1365         }
1366 }
1367
1368 /* Add arcs reached from BLOCK to the spanning tree if they are needed and
1369    not already there.  */
1370
1371 static void
1372 fill_spanning_tree (block)
1373      int block;
1374 {
1375   struct adj_list *arcptr;
1376   
1377   expand_spanning_tree (block);
1378
1379   for (arcptr = bb_graph[block].succ; arcptr; arcptr = arcptr->succ_next)
1380     if (! arcptr->on_tree
1381         && ! bb_graph[ARC_TARGET (arcptr)].on_tree)
1382       {
1383         arcptr->on_tree = 1;
1384         fill_spanning_tree (ARC_TARGET (arcptr));
1385       }
1386 }
1387
1388 /* When first visit a block, must add all blocks that are already connected
1389    to this block via tree arcs to the spanning tree.  */
1390
1391 static void
1392 expand_spanning_tree (block)
1393      int block;
1394 {
1395   struct adj_list *arcptr;
1396
1397   bb_graph[block].on_tree = 1;
1398
1399   for (arcptr = bb_graph[block].succ; arcptr; arcptr = arcptr->succ_next)
1400     if (arcptr->on_tree && ! bb_graph[ARC_TARGET (arcptr)].on_tree)
1401       expand_spanning_tree (ARC_TARGET (arcptr));
1402     
1403   for (arcptr = bb_graph[block].pred;
1404        arcptr; arcptr = arcptr->pred_next)
1405     if (arcptr->on_tree && ! bb_graph[ARC_SOURCE (arcptr)].on_tree)
1406       expand_spanning_tree (ARC_SOURCE (arcptr));
1407 }
1408 \f
1409 /* Perform file-level initialization for branch-prob processing.  */
1410
1411 void
1412 init_branch_prob (filename)
1413   const char *filename;
1414 {
1415   long len;
1416   int i;
1417
1418   if (flag_test_coverage)
1419     {
1420       /* Open an output file for the basic block/line number map.  */
1421       int len = strlen (filename);
1422       char *data_file = (char *) alloca (len + 4);
1423       strcpy (data_file, filename);
1424       strip_off_ending (data_file, len);
1425       strcat (data_file, ".bb");
1426       if ((bb_file = fopen (data_file, "wb")) == 0)
1427         pfatal_with_name (data_file);
1428
1429       /* Open an output file for the program flow graph.  */
1430       len = strlen (filename);
1431       bbg_file_name = (char *) alloca (len + 5);
1432       strcpy (bbg_file_name, filename);
1433       strip_off_ending (bbg_file_name, len);
1434       strcat (bbg_file_name, ".bbg");
1435       if ((bbg_file = fopen (bbg_file_name, "wb")) == 0)
1436         pfatal_with_name (bbg_file_name);
1437
1438       /* Initialize to zero, to ensure that the first file name will be
1439          written to the .bb file.  */
1440       last_bb_file_name = 0;
1441     }
1442
1443   if (flag_branch_probabilities)
1444     {
1445       len = strlen (filename);
1446       da_file_name = (char *) alloca (len + 4);
1447       strcpy (da_file_name, filename);
1448       strip_off_ending (da_file_name, len);
1449       strcat (da_file_name, ".da");
1450       if ((da_file = fopen (da_file_name, "rb")) == 0)
1451         warning ("file %s not found, execution counts assumed to be zero.",
1452                  da_file_name);
1453
1454       /* The first word in the .da file gives the number of instrumented arcs,
1455          which is not needed for our purposes.  */
1456
1457       if (da_file)
1458         __read_long (&len, da_file, 8);
1459     }
1460
1461   if (profile_arc_flag)
1462     init_arc_profiler ();
1463
1464   total_num_blocks = 0;
1465   total_num_arcs = 0;
1466   total_num_arcs_instrumented = 0;
1467   total_num_blocks_created = 0;
1468   total_num_passes = 0;
1469   total_num_times_called = 0;
1470   total_num_branches = 0;
1471   total_num_never_executed = 0;
1472   for (i = 0; i < 20; i++)
1473     total_hist_br_prob[i] = 0;
1474 }
1475
1476 /* Performs file-level cleanup after branch-prob processing
1477    is completed.  */
1478
1479 void
1480 end_branch_prob (dump_file)
1481      FILE *dump_file;
1482 {
1483   if (flag_test_coverage)
1484     {
1485       fclose (bb_file);
1486       fclose (bbg_file);
1487     }
1488
1489   if (flag_branch_probabilities)
1490     {
1491       if (da_file)
1492         {
1493           long temp;
1494           /* This seems slightly dangerous, as it presumes the EOF
1495              flag will not be set until an attempt is made to read
1496              past the end of the file. */
1497           if (feof (da_file))
1498             warning (".da file contents exhausted too early\n");
1499           /* Should be at end of file now.  */
1500           if (__read_long (&temp, da_file, 8) == 0)
1501             warning (".da file contents not exhausted\n");
1502           fclose (da_file);
1503         }
1504     }
1505
1506   if (dump_file)
1507     {
1508       fprintf (dump_file, "\n");
1509       fprintf (dump_file, "Total number of blocks: %d\n", total_num_blocks);
1510       fprintf (dump_file, "Total number of arcs: %d\n", total_num_arcs);
1511       fprintf (dump_file, "Total number of instrumented arcs: %d\n",
1512                total_num_arcs_instrumented);
1513       fprintf (dump_file, "Total number of blocks created: %d\n",
1514                total_num_blocks_created);
1515       fprintf (dump_file, "Total number of graph solution passes: %d\n",
1516                total_num_passes);
1517       if (total_num_times_called != 0)
1518         fprintf (dump_file, "Average number of graph solution passes: %d\n",
1519                  (total_num_passes + (total_num_times_called  >> 1))
1520                  / total_num_times_called);
1521       fprintf (dump_file, "Total number of branches: %d\n", total_num_branches);
1522       fprintf (dump_file, "Total number of branches never executed: %d\n",
1523                total_num_never_executed);
1524       if (total_num_branches)
1525         {
1526           int i;
1527
1528           for (i = 0; i < 10; i++)
1529             fprintf (dump_file, "%d%% branches in range %d-%d%%\n",
1530                      (total_hist_br_prob[i] + total_hist_br_prob[19-i]) * 100
1531                      / total_num_branches, 5*i, 5*i+5);
1532         }
1533     }
1534 }
1535 \f
1536 /* The label used by the arc profiling code.  */
1537
1538 static rtx profiler_label;
1539
1540 /* Initialize the profiler_label.  */
1541
1542 static void
1543 init_arc_profiler ()
1544 {
1545   /* Generate and save a copy of this so it can be shared.  */
1546   char *name = ggc_alloc_string (NULL, 20);
1547   ASM_GENERATE_INTERNAL_LABEL (name, "LPBX", 2);
1548   profiler_label = gen_rtx_SYMBOL_REF (Pmode, name);
1549   ggc_add_rtx_root (&profiler_label, 1);
1550 }
1551
1552 /* Output instructions as RTL to increment the arc execution count.  */
1553
1554 static void
1555 output_arc_profiler (arcno, insert_after)
1556      int arcno;
1557      rtx insert_after;
1558 {
1559   rtx profiler_target_addr
1560     = (arcno ? plus_constant (profiler_label,
1561                               LONG_TYPE_SIZE / BITS_PER_UNIT * arcno)
1562        : profiler_label);
1563   enum machine_mode mode = mode_for_size (LONG_TYPE_SIZE, MODE_INT, 0);
1564   rtx profiler_reg = gen_reg_rtx (mode);
1565   rtx address_reg = gen_reg_rtx (Pmode);
1566   rtx mem_ref, add_ref;
1567   rtx sequence;
1568
1569   /* In this case, reload can use explicitly mentioned hard registers for
1570      reloads.  It is not safe to output profiling code between a call
1571      and the instruction that copies the result to a pseudo-reg.  This
1572      is because reload may allocate one of the profiling code pseudo-regs
1573      to the return value reg, thus clobbering the return value.  So we
1574      must check for calls here, and emit the profiling code after the
1575      instruction that uses the return value, if any.
1576
1577      ??? The code here performs the same tests that reload does so hopefully
1578      all the bases are covered.  */
1579
1580   if (SMALL_REGISTER_CLASSES
1581       && GET_CODE (insert_after) == CALL_INSN
1582       && (GET_CODE (PATTERN (insert_after)) == SET
1583           || (GET_CODE (PATTERN (insert_after)) == PARALLEL
1584               && GET_CODE (XVECEXP (PATTERN (insert_after), 0, 0)) == SET)))
1585     {
1586       rtx return_reg;
1587       rtx next_insert_after = next_nonnote_insn (insert_after);
1588
1589       /* The first insn after the call may be a stack pop, skip it.  */
1590       if (next_insert_after
1591           && GET_CODE (next_insert_after) == INSN
1592           && GET_CODE (PATTERN (next_insert_after)) == SET
1593           && SET_DEST (PATTERN (next_insert_after)) == stack_pointer_rtx)
1594         next_insert_after = next_nonnote_insn (next_insert_after);
1595
1596       if (next_insert_after
1597           && GET_CODE (next_insert_after) == INSN)
1598         {
1599           if (GET_CODE (PATTERN (insert_after)) == SET)
1600             return_reg = SET_DEST (PATTERN (insert_after));
1601           else
1602             return_reg = SET_DEST (XVECEXP (PATTERN (insert_after), 0, 0));
1603
1604           /* Now, NEXT_INSERT_AFTER may be an instruction that uses the
1605              return value.  However, it could also be something else,
1606              like a CODE_LABEL, so check that the code is INSN.  */
1607           if (next_insert_after != 0
1608               && GET_RTX_CLASS (GET_CODE (next_insert_after)) == 'i'
1609               && reg_referenced_p (return_reg, PATTERN (next_insert_after)))
1610             insert_after = next_insert_after;
1611         }
1612     }
1613
1614   start_sequence ();
1615
1616   emit_move_insn (address_reg, profiler_target_addr);
1617   mem_ref = gen_rtx_MEM (mode, address_reg);
1618   emit_move_insn (profiler_reg, mem_ref);
1619
1620   add_ref = gen_rtx_PLUS (mode, profiler_reg, GEN_INT (1));
1621   emit_move_insn (profiler_reg, add_ref);
1622
1623   /* This is the same rtx as above, but it is not legal to share this rtx.  */
1624   mem_ref = gen_rtx_MEM (mode, address_reg);
1625   emit_move_insn (mem_ref, profiler_reg);
1626
1627   sequence = gen_sequence ();
1628   end_sequence ();
1629   emit_insn_after (sequence, insert_after);
1630 }
1631
1632 /* Output code for a constructor that will invoke __bb_init_func, if
1633    this has not already been done. */
1634
1635 void
1636 output_func_start_profiler ()
1637 {
1638   tree fnname, fndecl;
1639   char *name, *cfnname;
1640   rtx table_address;
1641   enum machine_mode mode = mode_for_size (LONG_TYPE_SIZE, MODE_INT, 0);
1642   int save_flag_inline_functions = flag_inline_functions;
1643
1644   /* It's either already been output, or we don't need it because we're
1645      not doing profile-arcs. */
1646   if (! need_func_profiler)
1647     return;
1648
1649   need_func_profiler = 0;
1650
1651   /* Synthesize a constructor function to invoke __bb_init_func with a
1652      pointer to this object file's profile block. */
1653
1654   /* Try and make a unique name given the "file function name".
1655
1656      And no, I don't like this either. */
1657
1658   fnname = get_file_function_name ('I');
1659   cfnname = IDENTIFIER_POINTER (fnname);
1660   name = xmalloc (strlen (cfnname) + 5);
1661   sprintf (name, "%sGCOV",cfnname);
1662   fnname = get_identifier (name);
1663   free (name);
1664
1665   fndecl = build_decl (FUNCTION_DECL, fnname,
1666                        build_function_type (void_type_node, NULL_TREE));
1667   DECL_EXTERNAL (fndecl) = 0;
1668   TREE_PUBLIC (fndecl) = 1;
1669   DECL_ASSEMBLER_NAME (fndecl) = fnname;
1670   DECL_RESULT (fndecl) = build_decl (RESULT_DECL, NULL_TREE, void_type_node);
1671
1672   fndecl = pushdecl (fndecl);
1673   rest_of_decl_compilation (fndecl, 0, 1, 0);
1674   announce_function (fndecl);
1675   current_function_decl = fndecl;
1676   DECL_INITIAL (fndecl) = error_mark_node;
1677   temporary_allocation ();
1678   make_function_rtl (fndecl);
1679   init_function_start (fndecl, input_filename, lineno);
1680   pushlevel (0);
1681   expand_function_start (fndecl, 0);
1682
1683   /* Actually generate the code to call __bb_init_func. */
1684   name = ggc_alloc_string (NULL, 20);
1685   ASM_GENERATE_INTERNAL_LABEL (name, "LPBX", 0);
1686   table_address = force_reg (Pmode, gen_rtx_SYMBOL_REF (Pmode, name));
1687   emit_library_call (gen_rtx_SYMBOL_REF 
1688                      (Pmode, ggc_alloc_string ("__bb_init_func", 14)), 0,
1689                      mode, 1, table_address, Pmode);
1690
1691   expand_function_end (input_filename, lineno, 0);
1692   poplevel (1, 0, 1);
1693
1694   /* Since fndecl isn't in the list of globals, it would never be emitted
1695      when it's considered to be 'safe' for inlining, so turn off
1696      flag_inline_functions.  */
1697   flag_inline_functions = 0;
1698
1699   rest_of_compilation (fndecl);
1700
1701   /* Reset flag_inline_functions to its original value.  */
1702   flag_inline_functions = save_flag_inline_functions;
1703
1704   if (! quiet_flag)
1705     fflush (asm_out_file);
1706   current_function_decl = NULL_TREE;
1707
1708   assemble_constructor (IDENTIFIER_POINTER (DECL_NAME (fndecl)));
1709 }