xref: /openbsd/gnu/gcc/gcc/toplev.c (revision cec5ac9d)
1 /* Top level of GCC compilers (cc1, cc1plus, etc.)
2    Copyright (C) 1987, 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
4    Free Software Foundation, Inc.
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12 
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
21 02110-1301, USA.  */
22 
23 /* This is the top level of cc1/c++.
24    It parses command args, opens files, invokes the various passes
25    in the proper order, and counts the time used by each.
26    Error messages and low-level interface to malloc also handled here.  */
27 
28 #include "config.h"
29 #undef FLOAT /* This is for hpux. They should change hpux.  */
30 #undef FFS  /* Some systems define this in param.h.  */
31 #include "system.h"
32 #include "coretypes.h"
33 #include "tm.h"
34 #include <signal.h>
35 
36 #ifdef HAVE_SYS_RESOURCE_H
37 # include <sys/resource.h>
38 #endif
39 
40 #ifdef HAVE_SYS_TIMES_H
41 # include <sys/times.h>
42 #endif
43 
44 #include "line-map.h"
45 #include "input.h"
46 #include "tree.h"
47 #include "version.h"
48 #include "rtl.h"
49 #include "tm_p.h"
50 #include "flags.h"
51 #include "insn-attr.h"
52 #include "insn-config.h"
53 #include "insn-flags.h"
54 #include "hard-reg-set.h"
55 #include "recog.h"
56 #include "output.h"
57 #include "except.h"
58 #include "function.h"
59 #include "toplev.h"
60 #include "expr.h"
61 #include "basic-block.h"
62 #include "intl.h"
63 #include "ggc.h"
64 #include "graph.h"
65 #include "regs.h"
66 #include "timevar.h"
67 #include "diagnostic.h"
68 #include "params.h"
69 #include "reload.h"
70 #include "dwarf2asm.h"
71 #include "integrate.h"
72 #include "real.h"
73 #include "debug.h"
74 #include "target.h"
75 #include "langhooks.h"
76 #include "cfglayout.h"
77 #include "cfgloop.h"
78 #include "hosthooks.h"
79 #include "cgraph.h"
80 #include "opts.h"
81 #include "coverage.h"
82 #include "value-prof.h"
83 #include "alloc-pool.h"
84 #include "tree-mudflap.h"
85 
86 #if defined (DWARF2_UNWIND_INFO) || defined (DWARF2_DEBUGGING_INFO)
87 #include "dwarf2out.h"
88 #endif
89 
90 #if defined(DBX_DEBUGGING_INFO) || defined(XCOFF_DEBUGGING_INFO)
91 #include "dbxout.h"
92 #endif
93 
94 #ifdef SDB_DEBUGGING_INFO
95 #include "sdbout.h"
96 #endif
97 
98 #ifdef XCOFF_DEBUGGING_INFO
99 #include "xcoffout.h"		/* Needed for external data
100 				   declarations for e.g. AIX 4.x.  */
101 #endif
102 
103 static void general_init (const char *);
104 static void do_compile (void);
105 static void process_options (void);
106 static void backend_init (void);
107 static int lang_dependent_init (const char *);
108 static void init_asm_output (const char *);
109 static void finalize (void);
110 
111 static void crash_signal (int) ATTRIBUTE_NORETURN;
112 static void setup_core_dumping (void);
113 static void compile_file (void);
114 
115 static int print_single_switch (FILE *, int, int, const char *,
116 				const char *, const char *,
117 				const char *, const char *);
118 static void print_switch_values (FILE *, int, int, const char *,
119 				 const char *, const char *);
120 
121 /* Nonzero to dump debug info whilst parsing (-dy option).  */
122 static int set_yydebug;
123 
124 /* True if we don't need a backend (e.g. preprocessing only).  */
125 static bool no_backend;
126 
127 /* Length of line when printing switch values.  */
128 #define MAX_LINE 75
129 
130 /* Name of program invoked, sans directories.  */
131 
132 const char *progname;
133 
134 /* Copy of argument vector to toplev_main.  */
135 static const char **save_argv;
136 
137 /* Name of top-level original source file (what was input to cpp).
138    This comes from the #-command at the beginning of the actual input.
139    If there isn't any there, then this is the cc1 input file name.  */
140 
141 const char *main_input_filename;
142 
143 #ifndef USE_MAPPED_LOCATION
144 location_t unknown_location = { NULL, 0 };
145 #endif
146 
147 /* Used to enable -fvar-tracking, -fweb and -frename-registers according
148    to optimize and default_debug_hooks in process_options ().  */
149 #define AUTODETECT_VALUE 2
150 
151 /* Current position in real source file.  */
152 
153 location_t input_location;
154 
155 struct line_maps line_table;
156 
157 /* Nonzero if it is unsafe to create any new pseudo registers.  */
158 int no_new_pseudos;
159 
160 /* Stack of currently pending input files.  */
161 
162 struct file_stack *input_file_stack;
163 
164 /* Incremented on each change to input_file_stack.  */
165 int input_file_stack_tick;
166 
167 /* Record of input_file_stack at each tick.  */
168 typedef struct file_stack *fs_p;
169 DEF_VEC_P(fs_p);
170 DEF_VEC_ALLOC_P(fs_p,heap);
171 static VEC(fs_p,heap) *input_file_stack_history;
172 
173 /* Whether input_file_stack has been restored to a previous state (in
174    which case there should be no more pushing).  */
175 static bool input_file_stack_restored;
176 
177 /* Name to use as base of names for dump output files.  */
178 
179 const char *dump_base_name;
180 
181 /* Name to use as a base for auxiliary output files.  */
182 
183 const char *aux_base_name;
184 
185 /* Bit flags that specify the machine subtype we are compiling for.
186    Bits are tested using macros TARGET_... defined in the tm.h file
187    and set by `-m...' switches.  Must be defined in rtlanal.c.  */
188 
189 extern int target_flags;
190 
191 /* A mask of target_flags that includes bit X if X was set or cleared
192    on the command line.  */
193 
194 int target_flags_explicit;
195 
196 /* Debug hooks - dependent upon command line options.  */
197 
198 const struct gcc_debug_hooks *debug_hooks;
199 
200 /* Debug hooks - target default.  */
201 
202 static const struct gcc_debug_hooks *default_debug_hooks;
203 
204 /* Other flags saying which kinds of debugging dump have been requested.  */
205 
206 int rtl_dump_and_exit;
207 int flag_print_asm_name;
208 enum graph_dump_types graph_dump_format;
209 
210 /* Name for output file of assembly code, specified with -o.  */
211 
212 const char *asm_file_name;
213 
214 /* Nonzero means do optimizations.  -O.
215    Particular numeric values stand for particular amounts of optimization;
216    thus, -O2 stores 2 here.  However, the optimizations beyond the basic
217    ones are not controlled directly by this variable.  Instead, they are
218    controlled by individual `flag_...' variables that are defaulted
219    based on this variable.  */
220 
221 int optimize = 0;
222 
223 /* Nonzero means optimize for size.  -Os.
224    The only valid values are zero and nonzero. When optimize_size is
225    nonzero, optimize defaults to 2, but certain individual code
226    bloating optimizations are disabled.  */
227 
228 int optimize_size = 0;
229 
230 /* The FUNCTION_DECL for the function currently being compiled,
231    or 0 if between functions.  */
232 tree current_function_decl;
233 
234 /* Set to the FUNC_BEGIN label of the current function, or NULL
235    if none.  */
236 const char * current_function_func_begin_label;
237 
238 /* Temporarily suppress certain warnings.
239    This is set while reading code from a system header file.  */
240 
241 int in_system_header = 0;
242 
243 /* Nonzero means to collect statistics which might be expensive
244    and to print them when we are done.  */
245 int flag_detailed_statistics = 0;
246 
247 /* A random sequence of characters, unless overridden by user.  */
248 const char *flag_random_seed;
249 
250 /* A local time stamp derived from the time of compilation. It will be
251    zero if the system cannot provide a time.  It will be -1u, if the
252    user has specified a particular random seed.  */
253 unsigned local_tick;
254 
255 /* -f flags.  */
256 
257 /* Nonzero means `char' should be signed.  */
258 
259 int flag_signed_char;
260 
261 /* Nonzero means give an enum type only as many bytes as it needs.  A value
262    of 2 means it has not yet been initialized.  */
263 
264 int flag_short_enums;
265 
266 /* Nonzero if structures and unions should be returned in memory.
267 
268    This should only be defined if compatibility with another compiler or
269    with an ABI is needed, because it results in slower code.  */
270 
271 #ifndef DEFAULT_PCC_STRUCT_RETURN
272 #define DEFAULT_PCC_STRUCT_RETURN 1
273 #endif
274 
275 /* Nonzero for -fpcc-struct-return: return values the same way PCC does.  */
276 
277 int flag_pcc_struct_return = DEFAULT_PCC_STRUCT_RETURN;
278 
279 /* 0 means straightforward implementation of complex divide acceptable.
280    1 means wide ranges of inputs must work for complex divide.
281    2 means C99-like requirements for complex multiply and divide.  */
282 
283 int flag_complex_method = 1;
284 
285 /* Nonzero means that we don't want inlining by virtue of -fno-inline,
286    not just because the tree inliner turned us off.  */
287 
288 int flag_really_no_inline = 2;
289 
290 /* Nonzero means we should be saving declaration info into a .X file.  */
291 
292 int flag_gen_aux_info = 0;
293 
294 /* Specified name of aux-info file.  */
295 
296 const char *aux_info_file_name;
297 
298 /* Nonzero if we are compiling code for a shared library, zero for
299    executable.  */
300 
301 int flag_shlib;
302 
303 /* Generate code for GNU or NeXT Objective-C runtime environment.  */
304 
305 #ifdef NEXT_OBJC_RUNTIME
306 int flag_next_runtime = 1;
307 #else
308 int flag_next_runtime = 0;
309 #endif
310 
311 /* Set to the default thread-local storage (tls) model to use.  */
312 
313 enum tls_model flag_tls_default = TLS_MODEL_GLOBAL_DYNAMIC;
314 
315 /* Nonzero means change certain warnings into errors.
316    Usually these are warnings about failure to conform to some standard.  */
317 
318 int flag_pedantic_errors = 0;
319 
320 /* -dA causes debug commentary information to be produced in
321    the generated assembly code (to make it more readable).  This option
322    is generally only of use to those who actually need to read the
323    generated assembly code (perhaps while debugging the compiler itself).
324    Currently, this switch is only used by dwarfout.c; however, it is intended
325    to be a catchall for printing debug information in the assembler file.  */
326 
327 int flag_debug_asm = 0;
328 
329 /* -dP causes the rtl to be emitted as a comment in assembly.  */
330 
331 int flag_dump_rtl_in_asm = 0;
332 
333 /* When non-NULL, indicates that whenever space is allocated on the
334    stack, the resulting stack pointer must not pass this
335    address---that is, for stacks that grow downward, the stack pointer
336    must always be greater than or equal to this address; for stacks
337    that grow upward, the stack pointer must be less than this address.
338    At present, the rtx may be either a REG or a SYMBOL_REF, although
339    the support provided depends on the backend.  */
340 rtx stack_limit_rtx;
341 
342 /* If one, renumber instruction UIDs to reduce the number of
343    unused UIDs if there are a lot of instructions.  If greater than
344    one, unconditionally renumber instruction UIDs.  */
345 int flag_renumber_insns = 1;
346 
347 /* Nonzero if we should track variables.  When
348    flag_var_tracking == AUTODETECT_VALUE it will be set according
349    to optimize, debug_info_level and debug_hooks in process_options ().  */
350 int flag_var_tracking = AUTODETECT_VALUE;
351 
352 /* True if the user has tagged the function with the 'section'
353    attribute.  */
354 
355 bool user_defined_section_attribute = false;
356 
357 /* Values of the -falign-* flags: how much to align labels in code.
358    0 means `use default', 1 means `don't align'.
359    For each variable, there is an _log variant which is the power
360    of two not less than the variable, for .align output.  */
361 
362 int align_loops_log;
363 int align_loops_max_skip;
364 int align_jumps_log;
365 int align_jumps_max_skip;
366 int align_labels_log;
367 int align_labels_max_skip;
368 int align_functions_log;
369 
370 /* Like align_functions_log above, but used by front-ends to force the
371    minimum function alignment.  Zero means no alignment is forced.  */
372 int force_align_functions_log;
373 
374 typedef struct
375 {
376   const char *const string;
377   int *const variable;
378   const int on_value;
379 }
380 lang_independent_options;
381 
382 /* Nonzero if subexpressions must be evaluated from left-to-right.  */
383 int flag_evaluation_order = 0;
384 
385 /* The user symbol prefix after having resolved same.  */
386 const char *user_label_prefix;
387 
388 static const param_info lang_independent_params[] = {
389 #define DEFPARAM(ENUM, OPTION, HELP, DEFAULT, MIN, MAX) \
390   { OPTION, DEFAULT, MIN, MAX, HELP },
391 #include "params.def"
392 #undef DEFPARAM
393   { NULL, 0, 0, 0, NULL }
394 };
395 
396 /* Output files for assembler code (real compiler output)
397    and debugging dumps.  */
398 
399 FILE *asm_out_file;
400 FILE *aux_info_file;
401 FILE *dump_file = NULL;
402 const char *dump_file_name;
403 
404 /* The current working directory of a translation.  It's generally the
405    directory from which compilation was initiated, but a preprocessed
406    file may specify the original directory in which it was
407    created.  */
408 
409 static const char *src_pwd;
410 
411 /* Initialize src_pwd with the given string, and return true.  If it
412    was already initialized, return false.  As a special case, it may
413    be called with a NULL argument to test whether src_pwd has NOT been
414    initialized yet.  */
415 
416 bool
set_src_pwd(const char * pwd)417 set_src_pwd (const char *pwd)
418 {
419   if (src_pwd)
420     {
421       if (strcmp (src_pwd, pwd) == 0)
422 	return true;
423       else
424 	return false;
425     }
426 
427   src_pwd = xstrdup (pwd);
428   return true;
429 }
430 
431 /* Return the directory from which the translation unit was initiated,
432    in case set_src_pwd() was not called before to assign it a
433    different value.  */
434 
435 const char *
get_src_pwd(void)436 get_src_pwd (void)
437 {
438   if (! src_pwd)
439     {
440       src_pwd = getpwd ();
441       if (!src_pwd)
442 	src_pwd = ".";
443     }
444 
445    return src_pwd;
446 }
447 
448 /* Called when the start of a function definition is parsed,
449    this function prints on stderr the name of the function.  */
450 void
announce_function(tree decl)451 announce_function (tree decl)
452 {
453   if (!quiet_flag)
454     {
455       if (rtl_dump_and_exit)
456 	fprintf (stderr, "%s ", IDENTIFIER_POINTER (DECL_NAME (decl)));
457       else
458 	fprintf (stderr, " %s", lang_hooks.decl_printable_name (decl, 2));
459       fflush (stderr);
460       pp_needs_newline (global_dc->printer) = true;
461       diagnostic_set_last_function (global_dc);
462     }
463 }
464 
465 /* Set up a default flag_random_seed and local_tick, unless the user
466    already specified one.  */
467 
468 static void
randomize(void)469 randomize (void)
470 {
471   if (!flag_random_seed)
472     {
473       unsigned HOST_WIDE_INT value;
474       static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
475 
476       /* Get some more or less random data.  */
477 #ifdef HAVE_GETTIMEOFDAY
478       {
479  	struct timeval tv;
480 
481  	gettimeofday (&tv, NULL);
482 	local_tick = tv.tv_sec * 1000 + tv.tv_usec / 1000;
483       }
484 #else
485       {
486 	time_t now = time (NULL);
487 
488 	if (now != (time_t)-1)
489 	  local_tick = (unsigned) now;
490       }
491 #endif
492       value = local_tick ^ getpid ();
493 
494       sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
495       flag_random_seed = random_seed;
496     }
497   else if (!local_tick)
498     local_tick = -1;
499 }
500 
501 
502 /* Decode the string P as an integral parameter.
503    If the string is indeed an integer return its numeric value else
504    issue an Invalid Option error for the option PNAME and return DEFVAL.
505    If PNAME is zero just return DEFVAL, do not call error.  */
506 
507 int
read_integral_parameter(const char * p,const char * pname,const int defval)508 read_integral_parameter (const char *p, const char *pname, const int  defval)
509 {
510   const char *endp = p;
511 
512   while (*endp)
513     {
514       if (ISDIGIT (*endp))
515 	endp++;
516       else
517 	break;
518     }
519 
520   if (*endp != 0)
521     {
522       if (pname != 0)
523 	error ("invalid option argument %qs", pname);
524       return defval;
525     }
526 
527   return atoi (p);
528 }
529 
530 /* When compiling with a recent enough GCC, we use the GNU C "extern inline"
531    for floor_log2 and exact_log2; see toplev.h.  That construct, however,
532    conflicts with the ISO C++ One Definition Rule.   */
533 
534 #if GCC_VERSION < 3004 || !defined (__cplusplus)
535 
536 /* Given X, an unsigned number, return the largest int Y such that 2**Y <= X.
537    If X is 0, return -1.  */
538 
539 int
floor_log2(unsigned HOST_WIDE_INT x)540 floor_log2 (unsigned HOST_WIDE_INT x)
541 {
542   int t = 0;
543 
544   if (x == 0)
545     return -1;
546 
547 #ifdef CLZ_HWI
548   t = HOST_BITS_PER_WIDE_INT - 1 - (int) CLZ_HWI (x);
549 #else
550   if (HOST_BITS_PER_WIDE_INT > 64)
551     if (x >= (unsigned HOST_WIDE_INT) 1 << (t + 64))
552       t += 64;
553   if (HOST_BITS_PER_WIDE_INT > 32)
554     if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 32))
555       t += 32;
556   if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 16))
557     t += 16;
558   if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 8))
559     t += 8;
560   if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 4))
561     t += 4;
562   if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 2))
563     t += 2;
564   if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 1))
565     t += 1;
566 #endif
567 
568   return t;
569 }
570 
571 /* Return the logarithm of X, base 2, considering X unsigned,
572    if X is a power of 2.  Otherwise, returns -1.  */
573 
574 int
exact_log2(unsigned HOST_WIDE_INT x)575 exact_log2 (unsigned HOST_WIDE_INT x)
576 {
577   if (x != (x & -x))
578     return -1;
579 #ifdef CTZ_HWI
580   return x ? CTZ_HWI (x) : -1;
581 #else
582   return floor_log2 (x);
583 #endif
584 }
585 
586 #endif /*  GCC_VERSION < 3004 || !defined (__cplusplus)  */
587 
588 /* Handler for fatal signals, such as SIGSEGV.  These are transformed
589    into ICE messages, which is much more user friendly.  In case the
590    error printer crashes, reset the signal to prevent infinite recursion.  */
591 
592 static void
crash_signal(int signo)593 crash_signal (int signo)
594 {
595   signal (signo, SIG_DFL);
596 
597   /* If we crashed while processing an ASM statement, then be a little more
598      graceful.  It's most likely the user's fault.  */
599   if (this_is_asm_operands)
600     {
601       output_operand_lossage ("unrecoverable error");
602       exit (FATAL_EXIT_CODE);
603     }
604 
605   internal_error ("%s", strsignal (signo));
606 }
607 
608 /* Arrange to dump core on error.  (The regular error message is still
609    printed first, except in the case of abort().)  */
610 
611 static void
setup_core_dumping(void)612 setup_core_dumping (void)
613 {
614 #ifdef SIGABRT
615   signal (SIGABRT, SIG_DFL);
616 #endif
617 #if defined(HAVE_SETRLIMIT)
618   {
619     struct rlimit rlim;
620     if (getrlimit (RLIMIT_CORE, &rlim) != 0)
621       fatal_error ("getting core file size maximum limit: %m");
622     rlim.rlim_cur = rlim.rlim_max;
623     if (setrlimit (RLIMIT_CORE, &rlim) != 0)
624       fatal_error ("setting core file size limit to maximum: %m");
625   }
626 #endif
627   diagnostic_abort_on_error (global_dc);
628 }
629 
630 
631 /* Strip off a legitimate source ending from the input string NAME of
632    length LEN.  Rather than having to know the names used by all of
633    our front ends, we strip off an ending of a period followed by
634    up to five characters.  (Java uses ".class".)  */
635 
636 void
strip_off_ending(char * name,int len)637 strip_off_ending (char *name, int len)
638 {
639   int i;
640   for (i = 2; i < 6 && len > i; i++)
641     {
642       if (name[len - i] == '.')
643 	{
644 	  name[len - i] = '\0';
645 	  break;
646 	}
647     }
648 }
649 
650 /* Output a quoted string.  */
651 
652 void
output_quoted_string(FILE * asm_file,const char * string)653 output_quoted_string (FILE *asm_file, const char *string)
654 {
655 #ifdef OUTPUT_QUOTED_STRING
656   OUTPUT_QUOTED_STRING (asm_file, string);
657 #else
658   char c;
659 
660   putc ('\"', asm_file);
661   while ((c = *string++) != 0)
662     {
663       if (ISPRINT (c))
664 	{
665 	  if (c == '\"' || c == '\\')
666 	    putc ('\\', asm_file);
667 	  putc (c, asm_file);
668 	}
669       else
670 	fprintf (asm_file, "\\%03o", (unsigned char) c);
671     }
672   putc ('\"', asm_file);
673 #endif
674 }
675 
676 /* Output a file name in the form wanted by System V.  */
677 
678 void
output_file_directive(FILE * asm_file,const char * input_name)679 output_file_directive (FILE *asm_file, const char *input_name)
680 {
681   int len;
682   const char *na;
683 
684   if (input_name == NULL)
685     input_name = "<stdin>";
686 
687   len = strlen (input_name);
688   na = input_name + len;
689 
690   /* NA gets INPUT_NAME sans directory names.  */
691   while (na > input_name)
692     {
693       if (IS_DIR_SEPARATOR (na[-1]))
694 	break;
695       na--;
696     }
697 
698 #ifdef ASM_OUTPUT_SOURCE_FILENAME
699   ASM_OUTPUT_SOURCE_FILENAME (asm_file, na);
700 #else
701   fprintf (asm_file, "\t.file\t");
702   output_quoted_string (asm_file, na);
703   fputc ('\n', asm_file);
704 #endif
705 }
706 
707 /* A subroutine of wrapup_global_declarations.  We've come to the end of
708    the compilation unit.  All deferred variables should be undeferred,
709    and all incomplete decls should be finalized.  */
710 
711 void
wrapup_global_declaration_1(tree decl)712 wrapup_global_declaration_1 (tree decl)
713 {
714   /* We're not deferring this any longer.  Assignment is conditional to
715      avoid needlessly dirtying PCH pages.  */
716   if (CODE_CONTAINS_STRUCT (TREE_CODE (decl), TS_DECL_WITH_VIS)
717       && DECL_DEFER_OUTPUT (decl) != 0)
718     DECL_DEFER_OUTPUT (decl) = 0;
719 
720   if (TREE_CODE (decl) == VAR_DECL && DECL_SIZE (decl) == 0)
721     lang_hooks.finish_incomplete_decl (decl);
722 }
723 
724 /* A subroutine of wrapup_global_declarations.  Decide whether or not DECL
725    needs to be output.  Return true if it is output.  */
726 
727 bool
wrapup_global_declaration_2(tree decl)728 wrapup_global_declaration_2 (tree decl)
729 {
730   if (TREE_ASM_WRITTEN (decl) || DECL_EXTERNAL (decl))
731     return false;
732 
733   /* Don't write out static consts, unless we still need them.
734 
735      We also keep static consts if not optimizing (for debugging),
736      unless the user specified -fno-keep-static-consts.
737      ??? They might be better written into the debug information.
738      This is possible when using DWARF.
739 
740      A language processor that wants static constants to be always
741      written out (even if it is not used) is responsible for
742      calling rest_of_decl_compilation itself.  E.g. the C front-end
743      calls rest_of_decl_compilation from finish_decl.
744      One motivation for this is that is conventional in some
745      environments to write things like:
746      static const char rcsid[] = "... version string ...";
747      intending to force the string to be in the executable.
748 
749      A language processor that would prefer to have unneeded
750      static constants "optimized away" would just defer writing
751      them out until here.  E.g. C++ does this, because static
752      constants are often defined in header files.
753 
754      ??? A tempting alternative (for both C and C++) would be
755      to force a constant to be written if and only if it is
756      defined in a main file, as opposed to an include file.  */
757 
758   if (TREE_CODE (decl) == VAR_DECL && TREE_STATIC (decl))
759     {
760       struct cgraph_varpool_node *node;
761       bool needed = true;
762       node = cgraph_varpool_node (decl);
763 
764       if (node->finalized)
765 	needed = false;
766       else if (node->alias)
767 	needed = false;
768       else if (!cgraph_global_info_ready
769 	       && (TREE_USED (decl)
770 		   || TREE_USED (DECL_ASSEMBLER_NAME (decl))))
771 	/* needed */;
772       else if (node->needed)
773 	/* needed */;
774       else if (DECL_COMDAT (decl))
775 	needed = false;
776       else if (TREE_READONLY (decl) && !TREE_PUBLIC (decl)
777 	       && (optimize || !flag_keep_static_consts
778 		   || DECL_ARTIFICIAL (decl)))
779 	needed = false;
780 
781       if (needed)
782 	{
783 	  rest_of_decl_compilation (decl, 1, 1);
784 	  return true;
785 	}
786     }
787 
788   return false;
789 }
790 
791 /* Do any final processing required for the declarations in VEC, of
792    which there are LEN.  We write out inline functions and variables
793    that have been deferred until this point, but which are required.
794    Returns nonzero if anything was put out.  */
795 
796 bool
wrapup_global_declarations(tree * vec,int len)797 wrapup_global_declarations (tree *vec, int len)
798 {
799   bool reconsider, output_something = false;
800   int i;
801 
802   for (i = 0; i < len; i++)
803     wrapup_global_declaration_1 (vec[i]);
804 
805   /* Now emit any global variables or functions that we have been
806      putting off.  We need to loop in case one of the things emitted
807      here references another one which comes earlier in the list.  */
808   do
809     {
810       reconsider = false;
811       for (i = 0; i < len; i++)
812 	reconsider |= wrapup_global_declaration_2 (vec[i]);
813       if (reconsider)
814 	output_something = true;
815     }
816   while (reconsider);
817 
818   return output_something;
819 }
820 
821 /* A subroutine of check_global_declarations.  Issue appropriate warnings
822    for the global declaration DECL.  */
823 
824 void
check_global_declaration_1(tree decl)825 check_global_declaration_1 (tree decl)
826 {
827   /* Warn about any function declared static but not defined.  We don't
828      warn about variables, because many programs have static variables
829      that exist only to get some text into the object file.  */
830   if (TREE_CODE (decl) == FUNCTION_DECL
831       && DECL_INITIAL (decl) == 0
832       && DECL_EXTERNAL (decl)
833       && ! DECL_ARTIFICIAL (decl)
834       && ! TREE_NO_WARNING (decl)
835       && ! TREE_PUBLIC (decl)
836       && (warn_unused_function
837 	  || TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl))))
838     {
839       if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
840 	pedwarn ("%q+F used but never defined", decl);
841       else
842 	warning (0, "%q+F declared %<static%> but never defined", decl);
843       /* This symbol is effectively an "extern" declaration now.  */
844       TREE_PUBLIC (decl) = 1;
845       assemble_external (decl);
846     }
847 
848   /* Warn about static fns or vars defined but not used.  */
849   if (((warn_unused_function && TREE_CODE (decl) == FUNCTION_DECL)
850        /* We don't warn about "static const" variables because the
851 	  "rcs_id" idiom uses that construction.  */
852        || (warn_unused_variable
853 	   && TREE_CODE (decl) == VAR_DECL && ! TREE_READONLY (decl)))
854       && ! DECL_IN_SYSTEM_HEADER (decl)
855       && ! TREE_USED (decl)
856       /* The TREE_USED bit for file-scope decls is kept in the identifier,
857 	 to handle multiple external decls in different scopes.  */
858       && ! (DECL_NAME (decl) && TREE_USED (DECL_NAME (decl)))
859       && ! DECL_EXTERNAL (decl)
860       && ! TREE_PUBLIC (decl)
861       /* A volatile variable might be used in some non-obvious way.  */
862       && ! TREE_THIS_VOLATILE (decl)
863       /* Global register variables must be declared to reserve them.  */
864       && ! (TREE_CODE (decl) == VAR_DECL && DECL_REGISTER (decl))
865       /* Otherwise, ask the language.  */
866       && lang_hooks.decls.warn_unused_global (decl))
867     warning (0, "%q+D defined but not used", decl);
868 }
869 
870 /* Issue appropriate warnings for the global declarations in VEC (of
871    which there are LEN).  */
872 
873 void
check_global_declarations(tree * vec,int len)874 check_global_declarations (tree *vec, int len)
875 {
876   int i;
877 
878   for (i = 0; i < len; i++)
879     check_global_declaration_1 (vec[i]);
880 }
881 
882 /* Emit debugging information for all global declarations in VEC.  */
883 
884 void
emit_debug_global_declarations(tree * vec,int len)885 emit_debug_global_declarations (tree *vec, int len)
886 {
887   int i;
888 
889   /* Avoid confusing the debug information machinery when there are errors.  */
890   if (errorcount != 0 || sorrycount != 0)
891     return;
892 
893   timevar_push (TV_SYMOUT);
894   for (i = 0; i < len; i++)
895     debug_hooks->global_decl (vec[i]);
896   timevar_pop (TV_SYMOUT);
897 }
898 
899 /* Warn about a use of an identifier which was marked deprecated.  */
900 void
warn_deprecated_use(tree node)901 warn_deprecated_use (tree node)
902 {
903   if (node == 0 || !warn_deprecated_decl)
904     return;
905 
906   if (DECL_P (node))
907     {
908       expanded_location xloc = expand_location (DECL_SOURCE_LOCATION (node));
909       warning (OPT_Wdeprecated_declarations,
910 	       "%qs is deprecated (declared at %s:%d)",
911 	       IDENTIFIER_POINTER (DECL_NAME (node)),
912 	       xloc.file, xloc.line);
913     }
914   else if (TYPE_P (node))
915     {
916       const char *what = NULL;
917       tree decl = TYPE_STUB_DECL (node);
918 
919       if (TYPE_NAME (node))
920 	{
921 	  if (TREE_CODE (TYPE_NAME (node)) == IDENTIFIER_NODE)
922 	    what = IDENTIFIER_POINTER (TYPE_NAME (node));
923 	  else if (TREE_CODE (TYPE_NAME (node)) == TYPE_DECL
924 		   && DECL_NAME (TYPE_NAME (node)))
925 	    what = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (node)));
926 	}
927 
928       if (decl)
929 	{
930 	  expanded_location xloc
931 	    = expand_location (DECL_SOURCE_LOCATION (decl));
932 	  if (what)
933 	    warning (OPT_Wdeprecated_declarations,
934 		     "%qs is deprecated (declared at %s:%d)", what,
935 		     xloc.file, xloc.line);
936 	  else
937 	    warning (OPT_Wdeprecated_declarations,
938 		     "type is deprecated (declared at %s:%d)",
939 		     xloc.file, xloc.line);
940 	}
941       else
942 	{
943 	  if (what)
944 	    warning (OPT_Wdeprecated_declarations, "%qs is deprecated", what);
945 	  else
946 	    warning (OPT_Wdeprecated_declarations, "type is deprecated");
947 	}
948     }
949 }
950 
951 /* Save the current INPUT_LOCATION on the top entry in the
952    INPUT_FILE_STACK.  Push a new entry for FILE and LINE, and set the
953    INPUT_LOCATION accordingly.  */
954 
955 void
956 #ifdef USE_MAPPED_LOCATION
push_srcloc(location_t fline)957 push_srcloc (location_t fline)
958 #else
959 push_srcloc (const char *file, int line)
960 #endif
961 {
962   struct file_stack *fs;
963 
964   gcc_assert (!input_file_stack_restored);
965   if (input_file_stack_tick == (int) ((1U << INPUT_FILE_STACK_BITS) - 1))
966     sorry ("GCC supports only %d input file changes", input_file_stack_tick);
967 
968   fs = XNEW (struct file_stack);
969   fs->location = input_location;
970   fs->next = input_file_stack;
971 #ifdef USE_MAPPED_LOCATION
972   input_location = fline;
973 #else
974   input_filename = file;
975   input_line = line;
976 #endif
977   input_file_stack = fs;
978   input_file_stack_tick++;
979   VEC_safe_push (fs_p, heap, input_file_stack_history, input_file_stack);
980 }
981 
982 /* Pop the top entry off the stack of presently open source files.
983    Restore the INPUT_LOCATION from the new topmost entry on the
984    stack.  */
985 
986 void
pop_srcloc(void)987 pop_srcloc (void)
988 {
989   struct file_stack *fs;
990 
991   gcc_assert (!input_file_stack_restored);
992   if (input_file_stack_tick == (int) ((1U << INPUT_FILE_STACK_BITS) - 1))
993     sorry ("GCC supports only %d input file changes", input_file_stack_tick);
994 
995   fs = input_file_stack;
996   input_location = fs->location;
997   input_file_stack = fs->next;
998   input_file_stack_tick++;
999   VEC_safe_push (fs_p, heap, input_file_stack_history, input_file_stack);
1000 }
1001 
1002 /* Restore the input file stack to its state as of TICK, for the sake
1003    of diagnostics after processing the whole input.  Once this has
1004    been called, push_srcloc and pop_srcloc may no longer be
1005    called.  */
1006 void
restore_input_file_stack(int tick)1007 restore_input_file_stack (int tick)
1008 {
1009   if (tick == 0)
1010     input_file_stack = NULL;
1011   else
1012     input_file_stack = VEC_index (fs_p, input_file_stack_history, tick - 1);
1013   input_file_stack_tick = tick;
1014   input_file_stack_restored = true;
1015 }
1016 
1017 /* Compile an entire translation unit.  Write a file of assembly
1018    output and various debugging dumps.  */
1019 
1020 static void
compile_file(void)1021 compile_file (void)
1022 {
1023   /* Initialize yet another pass.  */
1024 
1025   init_cgraph ();
1026   init_final (main_input_filename);
1027   coverage_init (aux_base_name);
1028 
1029   timevar_push (TV_PARSE);
1030 
1031   /* Call the parser, which parses the entire file (calling
1032      rest_of_compilation for each function).  */
1033   lang_hooks.parse_file (set_yydebug);
1034 
1035   /* In case there were missing block closers,
1036      get us back to the global binding level.  */
1037   lang_hooks.clear_binding_stack ();
1038 
1039   /* Compilation is now finished except for writing
1040      what's left of the symbol table output.  */
1041   timevar_pop (TV_PARSE);
1042 
1043   if (flag_syntax_only || errorcount || sorrycount)
1044     return;
1045 
1046   lang_hooks.decls.final_write_globals ();
1047   cgraph_varpool_assemble_pending_decls ();
1048   finish_aliases_2 ();
1049 
1050   /* This must occur after the loop to output deferred functions.
1051      Else the coverage initializer would not be emitted if all the
1052      functions in this compilation unit were deferred.  */
1053   coverage_finish ();
1054 
1055   /* Likewise for mudflap static object registrations.  */
1056   if (flag_mudflap)
1057     mudflap_finish_file ();
1058 
1059   output_shared_constant_pool ();
1060   output_object_blocks ();
1061 
1062   /* Write out any pending weak symbol declarations.  */
1063 
1064   weak_finish ();
1065 
1066   /* Do dbx symbols.  */
1067   timevar_push (TV_SYMOUT);
1068 
1069 #if defined DWARF2_DEBUGGING_INFO || defined DWARF2_UNWIND_INFO
1070   if (dwarf2out_do_frame ())
1071     dwarf2out_frame_finish ();
1072 #endif
1073 
1074   (*debug_hooks->finish) (main_input_filename);
1075   timevar_pop (TV_SYMOUT);
1076 
1077   /* Output some stuff at end of file if nec.  */
1078 
1079   dw2_output_indirect_constants ();
1080 
1081   /* Flush any pending external directives.  */
1082   process_pending_assemble_externals ();
1083 
1084   /* Attach a special .ident directive to the end of the file to identify
1085      the version of GCC which compiled this code.  The format of the .ident
1086      string is patterned after the ones produced by native SVR4 compilers.  */
1087 #ifdef IDENT_ASM_OP
1088   if (!flag_no_ident)
1089     fprintf (asm_out_file, "%s\"GCC: (GNU) %s\"\n",
1090 	     IDENT_ASM_OP, version_string);
1091 #endif
1092 
1093   /* This must be at the end.  Some target ports emit end of file directives
1094      into the assembly file here, and hence we can not output anything to the
1095      assembly file after this point.  */
1096   targetm.asm_out.file_end ();
1097 }
1098 
1099 /* Parse a -d... command line switch.  */
1100 
1101 void
decode_d_option(const char * arg)1102 decode_d_option (const char *arg)
1103 {
1104   int c;
1105 
1106   while (*arg)
1107     switch (c = *arg++)
1108       {
1109       case 'A':
1110 	flag_debug_asm = 1;
1111 	break;
1112       case 'p':
1113 	flag_print_asm_name = 1;
1114 	break;
1115       case 'P':
1116 	flag_dump_rtl_in_asm = 1;
1117 	flag_print_asm_name = 1;
1118 	break;
1119       case 'v':
1120 	graph_dump_format = vcg;
1121 	break;
1122       case 'x':
1123 	rtl_dump_and_exit = 1;
1124 	break;
1125       case 'y':
1126 	set_yydebug = 1;
1127 	break;
1128       case 'D':	/* These are handled by the preprocessor.  */
1129       case 'I':
1130 	break;
1131       case 'H':
1132 	setup_core_dumping();
1133 	break;
1134 
1135       case 'a':
1136       default:
1137 	if (!enable_rtl_dump_file (c))
1138 	  warning (0, "unrecognized gcc debugging option: %c", c);
1139 	break;
1140       }
1141 }
1142 
1143 /* Indexed by enum debug_info_type.  */
1144 const char *const debug_type_names[] =
1145 {
1146   "none", "stabs", "coff", "dwarf-2", "xcoff", "vms"
1147 };
1148 
1149 /* Print version information to FILE.
1150    Each line begins with INDENT (for the case where FILE is the
1151    assembler output file).  */
1152 
1153 void
print_version(FILE * file,const char * indent)1154 print_version (FILE *file, const char *indent)
1155 {
1156   static const char fmt1[] =
1157 #ifdef __GNUC__
1158     N_("%s%s%s version %s (%s)\n%s\tcompiled by GNU C version %s.\n")
1159 #else
1160     N_("%s%s%s version %s (%s) compiled by CC.\n")
1161 #endif
1162     ;
1163   static const char fmt2[] =
1164     N_("%s%sGGC heuristics: --param ggc-min-expand=%d --param ggc-min-heapsize=%d\n");
1165 #ifndef __VERSION__
1166 #define __VERSION__ "[?]"
1167 #endif
1168   fprintf (file,
1169 	   file == stderr ? _(fmt1) : fmt1,
1170 	   indent, *indent != 0 ? " " : "",
1171 	   lang_hooks.name, version_string, TARGET_NAME,
1172 	   indent, __VERSION__);
1173   fprintf (file,
1174 	   file == stderr ? _(fmt2) : fmt2,
1175 	   indent, *indent != 0 ? " " : "",
1176 	   PARAM_VALUE (GGC_MIN_EXPAND), PARAM_VALUE (GGC_MIN_HEAPSIZE));
1177 }
1178 
1179 /* Print an option value and return the adjusted position in the line.
1180    ??? We don't handle error returns from fprintf (disk full); presumably
1181    other code will catch a disk full though.  */
1182 
1183 static int
print_single_switch(FILE * file,int pos,int max,const char * indent,const char * sep,const char * term,const char * type,const char * name)1184 print_single_switch (FILE *file, int pos, int max,
1185 		     const char *indent, const char *sep, const char *term,
1186 		     const char *type, const char *name)
1187 {
1188   /* The ultrix fprintf returns 0 on success, so compute the result we want
1189      here since we need it for the following test.  */
1190   int len = strlen (sep) + strlen (type) + strlen (name);
1191 
1192   if (pos != 0
1193       && pos + len > max)
1194     {
1195       fprintf (file, "%s", term);
1196       pos = 0;
1197     }
1198   if (pos == 0)
1199     {
1200       fprintf (file, "%s", indent);
1201       pos = strlen (indent);
1202     }
1203   fprintf (file, "%s%s%s", sep, type, name);
1204   pos += len;
1205   return pos;
1206 }
1207 
1208 /* Print active target switches to FILE.
1209    POS is the current cursor position and MAX is the size of a "line".
1210    Each line begins with INDENT and ends with TERM.
1211    Each switch is separated from the next by SEP.  */
1212 
1213 static void
print_switch_values(FILE * file,int pos,int max,const char * indent,const char * sep,const char * term)1214 print_switch_values (FILE *file, int pos, int max,
1215 		     const char *indent, const char *sep, const char *term)
1216 {
1217   size_t j;
1218   const char **p;
1219 
1220   /* Fill in the -frandom-seed option, if the user didn't pass it, so
1221      that it can be printed below.  This helps reproducibility.  */
1222   randomize ();
1223 
1224   /* Print the options as passed.  */
1225   pos = print_single_switch (file, pos, max, indent, *indent ? " " : "", term,
1226 			     _("options passed: "), "");
1227 
1228   for (p = &save_argv[1]; *p != NULL; p++)
1229     if (**p == '-')
1230       {
1231 	/* Ignore these.  */
1232 	if (strcmp (*p, "-o") == 0)
1233 	  {
1234 	    if (p[1] != NULL)
1235 	      p++;
1236 	    continue;
1237 	  }
1238 	if (strcmp (*p, "-quiet") == 0)
1239 	  continue;
1240 	if (strcmp (*p, "-version") == 0)
1241 	  continue;
1242 	if ((*p)[1] == 'd')
1243 	  continue;
1244 
1245 	pos = print_single_switch (file, pos, max, indent, sep, term, *p, "");
1246       }
1247   if (pos > 0)
1248     fprintf (file, "%s", term);
1249 
1250   /* Print the -f and -m options that have been enabled.
1251      We don't handle language specific options but printing argv
1252      should suffice.  */
1253 
1254   pos = print_single_switch (file, 0, max, indent, *indent ? " " : "", term,
1255 			     _("options enabled: "), "");
1256 
1257   for (j = 0; j < cl_options_count; j++)
1258     if ((cl_options[j].flags & CL_REPORT)
1259 	&& option_enabled (j) > 0)
1260       pos = print_single_switch (file, pos, max, indent, sep, term,
1261 				 "", cl_options[j].opt_text);
1262 
1263   fprintf (file, "%s", term);
1264 }
1265 
1266 /* Open assembly code output file.  Do this even if -fsyntax-only is
1267    on, because then the driver will have provided the name of a
1268    temporary file or bit bucket for us.  NAME is the file specified on
1269    the command line, possibly NULL.  */
1270 static void
init_asm_output(const char * name)1271 init_asm_output (const char *name)
1272 {
1273   if (name == NULL && asm_file_name == 0)
1274     asm_out_file = stdout;
1275   else
1276     {
1277       if (asm_file_name == 0)
1278 	{
1279 	  int len = strlen (dump_base_name);
1280 	  char *dumpname = XNEWVEC (char, len + 6);
1281 	  memcpy (dumpname, dump_base_name, len + 1);
1282 	  strip_off_ending (dumpname, len);
1283 	  strcat (dumpname, ".s");
1284 	  asm_file_name = dumpname;
1285 	}
1286       if (!strcmp (asm_file_name, "-"))
1287 	asm_out_file = stdout;
1288       else
1289 	asm_out_file = fopen (asm_file_name, "w+b");
1290       if (asm_out_file == 0)
1291 	fatal_error ("can%'t open %s for writing: %m", asm_file_name);
1292     }
1293 
1294   if (!flag_syntax_only)
1295     {
1296       targetm.asm_out.file_start ();
1297 
1298 #ifdef ASM_COMMENT_START
1299       if (flag_verbose_asm)
1300 	{
1301 	  /* Print the list of options in effect.  */
1302 	  print_version (asm_out_file, ASM_COMMENT_START);
1303 	  print_switch_values (asm_out_file, 0, MAX_LINE,
1304 			       ASM_COMMENT_START, " ", "\n");
1305 	  /* Add a blank line here so it appears in assembler output but not
1306 	     screen output.  */
1307 	  fprintf (asm_out_file, "\n");
1308 	}
1309 #endif
1310     }
1311 }
1312 
1313 /* Return true if the state of option OPTION should be stored in PCH files
1314    and checked by default_pch_valid_p.  Store the option's current state
1315    in STATE if so.  */
1316 
1317 static inline bool
option_affects_pch_p(int option,struct cl_option_state * state)1318 option_affects_pch_p (int option, struct cl_option_state *state)
1319 {
1320   if ((cl_options[option].flags & CL_TARGET) == 0)
1321     return false;
1322   if (cl_options[option].flag_var == &target_flags)
1323     if (targetm.check_pch_target_flags)
1324       return false;
1325   return get_option_state (option, state);
1326 }
1327 
1328 /* Default version of get_pch_validity.
1329    By default, every flag difference is fatal; that will be mostly right for
1330    most targets, but completely right for very few.  */
1331 
1332 void *
default_get_pch_validity(size_t * len)1333 default_get_pch_validity (size_t *len)
1334 {
1335   struct cl_option_state state;
1336   size_t i;
1337   char *result, *r;
1338 
1339   *len = 2;
1340   if (targetm.check_pch_target_flags)
1341     *len += sizeof (target_flags);
1342   for (i = 0; i < cl_options_count; i++)
1343     if (option_affects_pch_p (i, &state))
1344       *len += state.size;
1345 
1346   result = r = XNEWVEC (char, *len);
1347   r[0] = flag_pic;
1348   r[1] = flag_pie;
1349   r += 2;
1350   if (targetm.check_pch_target_flags)
1351     {
1352       memcpy (r, &target_flags, sizeof (target_flags));
1353       r += sizeof (target_flags);
1354     }
1355 
1356   for (i = 0; i < cl_options_count; i++)
1357     if (option_affects_pch_p (i, &state))
1358       {
1359 	memcpy (r, state.data, state.size);
1360 	r += state.size;
1361       }
1362 
1363   return result;
1364 }
1365 
1366 /* Return a message which says that a PCH file was created with a different
1367    setting of OPTION.  */
1368 
1369 static const char *
pch_option_mismatch(const char * option)1370 pch_option_mismatch (const char *option)
1371 {
1372   char *r;
1373 
1374   asprintf (&r, _("created and used with differing settings of '%s'"), option);
1375   if (r == NULL)
1376     return _("out of memory");
1377   return r;
1378 }
1379 
1380 /* Default version of pch_valid_p.  */
1381 
1382 const char *
default_pch_valid_p(const void * data_p,size_t len)1383 default_pch_valid_p (const void *data_p, size_t len)
1384 {
1385   struct cl_option_state state;
1386   const char *data = (const char *)data_p;
1387   size_t i;
1388 
1389   /* -fpic and -fpie also usually make a PCH invalid.  */
1390   if (data[0] != flag_pic)
1391     return _("created and used with different settings of -fpic");
1392   if (data[1] != flag_pie)
1393     return _("created and used with different settings of -fpie");
1394   data += 2;
1395 
1396   /* Check target_flags.  */
1397   if (targetm.check_pch_target_flags)
1398     {
1399       int tf;
1400       const char *r;
1401 
1402       memcpy (&tf, data, sizeof (target_flags));
1403       data += sizeof (target_flags);
1404       len -= sizeof (target_flags);
1405       r = targetm.check_pch_target_flags (tf);
1406       if (r != NULL)
1407 	return r;
1408     }
1409 
1410   for (i = 0; i < cl_options_count; i++)
1411     if (option_affects_pch_p (i, &state))
1412       {
1413 	if (memcmp (data, state.data, state.size) != 0)
1414 	  return pch_option_mismatch (cl_options[i].opt_text);
1415 	data += state.size;
1416 	len -= state.size;
1417       }
1418 
1419   return NULL;
1420 }
1421 
1422 /* Default tree printer.   Handles declarations only.  */
1423 static bool
default_tree_printer(pretty_printer * pp,text_info * text,const char * spec,int precision,bool wide,bool set_locus,bool hash)1424 default_tree_printer (pretty_printer * pp, text_info *text, const char *spec,
1425 		      int precision, bool wide, bool set_locus, bool hash)
1426 {
1427   tree t;
1428 
1429   /* FUTURE: %+x should set the locus.  */
1430   if (precision != 0 || wide || hash)
1431     return false;
1432 
1433   switch (*spec)
1434     {
1435     case 'D':
1436       t = va_arg (*text->args_ptr, tree);
1437       if (DECL_DEBUG_EXPR_IS_FROM (t) && DECL_DEBUG_EXPR (t))
1438 	t = DECL_DEBUG_EXPR (t);
1439       break;
1440 
1441     case 'F':
1442     case 'T':
1443       t = va_arg (*text->args_ptr, tree);
1444       break;
1445 
1446     default:
1447       return false;
1448     }
1449 
1450   if (set_locus && text->locus)
1451     *text->locus = DECL_SOURCE_LOCATION (t);
1452 
1453   if (DECL_P (t))
1454     {
1455       const char *n = DECL_NAME (t)
1456         ? lang_hooks.decl_printable_name (t, 2)
1457         : "<anonymous>";
1458       pp_string (pp, n);
1459     }
1460   else
1461     dump_generic_node (pp, t, 0, 0, 0);
1462 
1463   return true;
1464 }
1465 
1466 /* Initialization of the front end environment, before command line
1467    options are parsed.  Signal handlers, internationalization etc.
1468    ARGV0 is main's argv[0].  */
1469 static void
general_init(const char * argv0)1470 general_init (const char *argv0)
1471 {
1472   const char *p;
1473 
1474   p = argv0 + strlen (argv0);
1475   while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
1476     --p;
1477   progname = p;
1478 
1479   xmalloc_set_program_name (progname);
1480 
1481   hex_init ();
1482 
1483   /* Unlock the stdio streams.  */
1484   unlock_std_streams ();
1485 
1486   gcc_init_libintl ();
1487 
1488   /* Initialize the diagnostics reporting machinery, so option parsing
1489      can give warnings and errors.  */
1490   diagnostic_initialize (global_dc);
1491   /* Set a default printer.  Language specific initializations will
1492      override it later.  */
1493   pp_format_decoder (global_dc->printer) = &default_tree_printer;
1494 
1495   /* Trap fatal signals, e.g. SIGSEGV, and convert them to ICE messages.  */
1496 #ifdef SIGSEGV
1497   signal (SIGSEGV, crash_signal);
1498 #endif
1499 #ifdef SIGILL
1500   signal (SIGILL, crash_signal);
1501 #endif
1502 #ifdef SIGBUS
1503   signal (SIGBUS, crash_signal);
1504 #endif
1505 #ifdef SIGABRT
1506   signal (SIGABRT, crash_signal);
1507 #endif
1508 #if defined SIGIOT && (!defined SIGABRT || SIGABRT != SIGIOT)
1509   signal (SIGIOT, crash_signal);
1510 #endif
1511 #ifdef SIGFPE
1512   signal (SIGFPE, crash_signal);
1513 #endif
1514 
1515   /* Other host-specific signal setup.  */
1516   (*host_hooks.extra_signals)();
1517 
1518   /* Initialize the garbage-collector, string pools and tree type hash
1519      table.  */
1520   init_ggc ();
1521   init_stringpool ();
1522   linemap_init (&line_table);
1523   init_ttree ();
1524 
1525   /* Initialize register usage now so switches may override.  */
1526   init_reg_sets ();
1527 
1528   /* Register the language-independent parameters.  */
1529   add_params (lang_independent_params, LAST_PARAM);
1530 
1531   /* This must be done after add_params but before argument processing.  */
1532   init_ggc_heuristics();
1533   init_optimization_passes ();
1534 }
1535 
1536 /* Return true if the current target supports -fsection-anchors.  */
1537 
1538 static bool
target_supports_section_anchors_p(void)1539 target_supports_section_anchors_p (void)
1540 {
1541   if (targetm.min_anchor_offset == 0 && targetm.max_anchor_offset == 0)
1542     return false;
1543 
1544   if (targetm.asm_out.output_anchor == NULL)
1545     return false;
1546 
1547   return true;
1548 }
1549 
1550 /* Process the options that have been parsed.  */
1551 static void
process_options(void)1552 process_options (void)
1553 {
1554   /* Just in case lang_hooks.post_options ends up calling a debug_hook.
1555      This can happen with incorrect pre-processed input. */
1556   debug_hooks = &do_nothing_debug_hooks;
1557 
1558   /* Allow the front end to perform consistency checks and do further
1559      initialization based on the command line options.  This hook also
1560      sets the original filename if appropriate (e.g. foo.i -> foo.c)
1561      so we can correctly initialize debug output.  */
1562   no_backend = lang_hooks.post_options (&main_input_filename);
1563 #ifndef USE_MAPPED_LOCATION
1564   input_filename = main_input_filename;
1565 #endif
1566 
1567 #ifdef OVERRIDE_OPTIONS
1568   /* Some machines may reject certain combinations of options.  */
1569   OVERRIDE_OPTIONS;
1570 #endif
1571 
1572   if (flag_section_anchors && !target_supports_section_anchors_p ())
1573     {
1574       warning (OPT_fsection_anchors,
1575 	       "this target does not support %qs", "-fsection-anchors");
1576       flag_section_anchors = 0;
1577     }
1578 
1579   if (flag_short_enums == 2)
1580     flag_short_enums = targetm.default_short_enums ();
1581 
1582   /* Set aux_base_name if not already set.  */
1583   if (aux_base_name)
1584     ;
1585   else if (main_input_filename)
1586     {
1587       char *name = xstrdup (lbasename (main_input_filename));
1588 
1589       strip_off_ending (name, strlen (name));
1590       aux_base_name = name;
1591     }
1592   else
1593     aux_base_name = "gccaux";
1594 
1595   /* Set up the align_*_log variables, defaulting them to 1 if they
1596      were still unset.  */
1597   if (align_loops <= 0) align_loops = 1;
1598   if (align_loops_max_skip > align_loops || !align_loops)
1599     align_loops_max_skip = align_loops - 1;
1600   align_loops_log = floor_log2 (align_loops * 2 - 1);
1601   if (align_jumps <= 0) align_jumps = 1;
1602   if (align_jumps_max_skip > align_jumps || !align_jumps)
1603     align_jumps_max_skip = align_jumps - 1;
1604   align_jumps_log = floor_log2 (align_jumps * 2 - 1);
1605   if (align_labels <= 0) align_labels = 1;
1606   align_labels_log = floor_log2 (align_labels * 2 - 1);
1607   if (align_labels_max_skip > align_labels || !align_labels)
1608     align_labels_max_skip = align_labels - 1;
1609   if (align_functions <= 0) align_functions = 1;
1610   align_functions_log = floor_log2 (align_functions * 2 - 1);
1611 
1612   /* Unrolling all loops implies that standard loop unrolling must also
1613      be done.  */
1614   if (flag_unroll_all_loops)
1615     flag_unroll_loops = 1;
1616 
1617   /* The loop unrolling code assumes that cse will be run after loop.
1618      web and rename-registers also help when run after loop unrolling.  */
1619 
1620   if (flag_rerun_cse_after_loop == AUTODETECT_VALUE)
1621     flag_rerun_cse_after_loop = flag_unroll_loops || flag_peel_loops;
1622   if (flag_web == AUTODETECT_VALUE)
1623     flag_web = flag_unroll_loops || flag_peel_loops;
1624   if (flag_rename_registers == AUTODETECT_VALUE)
1625     flag_rename_registers = flag_unroll_loops || flag_peel_loops;
1626 
1627   if (flag_non_call_exceptions)
1628     flag_asynchronous_unwind_tables = 1;
1629   if (flag_asynchronous_unwind_tables)
1630     flag_unwind_tables = 1;
1631 
1632   /* Disable unit-at-a-time mode for frontends not supporting callgraph
1633      interface.  */
1634   if (flag_unit_at_a_time && ! lang_hooks.callgraph.expand_function)
1635     flag_unit_at_a_time = 0;
1636 
1637   if (!flag_unit_at_a_time)
1638     flag_section_anchors = 0;
1639 
1640   if (flag_value_profile_transformations)
1641     flag_profile_values = 1;
1642 
1643   /* Warn about options that are not supported on this machine.  */
1644 #ifndef INSN_SCHEDULING
1645   if (flag_schedule_insns || flag_schedule_insns_after_reload)
1646     warning (0, "instruction scheduling not supported on this target machine");
1647 #endif
1648 #ifndef DELAY_SLOTS
1649   if (flag_delayed_branch)
1650     warning (0, "this target machine does not have delayed branches");
1651 #endif
1652 
1653   user_label_prefix = USER_LABEL_PREFIX;
1654   if (flag_leading_underscore != -1)
1655     {
1656       /* If the default prefix is more complicated than "" or "_",
1657 	 issue a warning and ignore this option.  */
1658       if (user_label_prefix[0] == 0 ||
1659 	  (user_label_prefix[0] == '_' && user_label_prefix[1] == 0))
1660 	{
1661 	  user_label_prefix = flag_leading_underscore ? "_" : "";
1662 	}
1663       else
1664 	warning (0, "-f%sleading-underscore not supported on this target machine",
1665 		 flag_leading_underscore ? "" : "no-");
1666     }
1667 
1668   /* If we are in verbose mode, write out the version and maybe all the
1669      option flags in use.  */
1670   if (version_flag)
1671     {
1672       print_version (stderr, "");
1673       if (! quiet_flag)
1674 	print_switch_values (stderr, 0, MAX_LINE, "", " ", "\n");
1675     }
1676 
1677   if (flag_syntax_only)
1678     {
1679       write_symbols = NO_DEBUG;
1680       profile_flag = 0;
1681     }
1682 
1683   /* A lot of code assumes write_symbols == NO_DEBUG if the debugging
1684      level is 0.  */
1685   if (debug_info_level == DINFO_LEVEL_NONE)
1686     write_symbols = NO_DEBUG;
1687 
1688   /* Now we know write_symbols, set up the debug hooks based on it.
1689      By default we do nothing for debug output.  */
1690   if (PREFERRED_DEBUGGING_TYPE == NO_DEBUG)
1691     default_debug_hooks = &do_nothing_debug_hooks;
1692 #if defined(DBX_DEBUGGING_INFO)
1693   else if (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG)
1694     default_debug_hooks = &dbx_debug_hooks;
1695 #endif
1696 #if defined(XCOFF_DEBUGGING_INFO)
1697   else if (PREFERRED_DEBUGGING_TYPE == XCOFF_DEBUG)
1698     default_debug_hooks = &xcoff_debug_hooks;
1699 #endif
1700 #ifdef SDB_DEBUGGING_INFO
1701   else if (PREFERRED_DEBUGGING_TYPE == SDB_DEBUG)
1702     default_debug_hooks = &sdb_debug_hooks;
1703 #endif
1704 #ifdef DWARF2_DEBUGGING_INFO
1705   else if (PREFERRED_DEBUGGING_TYPE == DWARF2_DEBUG)
1706     default_debug_hooks = &dwarf2_debug_hooks;
1707 #endif
1708 #ifdef VMS_DEBUGGING_INFO
1709   else if (PREFERRED_DEBUGGING_TYPE == VMS_DEBUG
1710 	   || PREFERRED_DEBUGGING_TYPE == VMS_AND_DWARF2_DEBUG)
1711     default_debug_hooks = &vmsdbg_debug_hooks;
1712 #endif
1713 
1714   if (write_symbols == NO_DEBUG)
1715     ;
1716 #if defined(DBX_DEBUGGING_INFO)
1717   else if (write_symbols == DBX_DEBUG)
1718     debug_hooks = &dbx_debug_hooks;
1719 #endif
1720 #if defined(XCOFF_DEBUGGING_INFO)
1721   else if (write_symbols == XCOFF_DEBUG)
1722     debug_hooks = &xcoff_debug_hooks;
1723 #endif
1724 #ifdef SDB_DEBUGGING_INFO
1725   else if (write_symbols == SDB_DEBUG)
1726     debug_hooks = &sdb_debug_hooks;
1727 #endif
1728 #ifdef DWARF2_DEBUGGING_INFO
1729   else if (write_symbols == DWARF2_DEBUG)
1730     debug_hooks = &dwarf2_debug_hooks;
1731 #endif
1732 #ifdef VMS_DEBUGGING_INFO
1733   else if (write_symbols == VMS_DEBUG || write_symbols == VMS_AND_DWARF2_DEBUG)
1734     debug_hooks = &vmsdbg_debug_hooks;
1735 #endif
1736   else
1737     error ("target system does not support the \"%s\" debug format",
1738 	   debug_type_names[write_symbols]);
1739 
1740   /* Now we know which debug output will be used so we can set
1741      flag_var_tracking, flag_rename_registers if the user has
1742      not specified them.  */
1743   if (debug_info_level < DINFO_LEVEL_NORMAL
1744       || debug_hooks->var_location == do_nothing_debug_hooks.var_location)
1745     {
1746       if (flag_var_tracking == 1)
1747         {
1748 	  if (debug_info_level < DINFO_LEVEL_NORMAL)
1749 	    warning (0, "variable tracking requested, but useless unless "
1750 		     "producing debug info");
1751 	  else
1752 	    warning (0, "variable tracking requested, but not supported "
1753 		     "by this debug format");
1754 	}
1755       flag_var_tracking = 0;
1756     }
1757 
1758   if (flag_rename_registers == AUTODETECT_VALUE)
1759     flag_rename_registers = default_debug_hooks->var_location
1760 	    		    != do_nothing_debug_hooks.var_location;
1761 
1762   if (flag_var_tracking == AUTODETECT_VALUE)
1763     flag_var_tracking = optimize >= 1;
1764 
1765   /* If auxiliary info generation is desired, open the output file.
1766      This goes in the same directory as the source file--unlike
1767      all the other output files.  */
1768   if (flag_gen_aux_info)
1769     {
1770       aux_info_file = fopen (aux_info_file_name, "w");
1771       if (aux_info_file == 0)
1772 	fatal_error ("can%'t open %s: %m", aux_info_file_name);
1773     }
1774 
1775   if (! targetm.have_named_sections)
1776     {
1777       if (flag_function_sections)
1778 	{
1779 	  warning (0, "-ffunction-sections not supported for this target");
1780 	  flag_function_sections = 0;
1781 	}
1782       if (flag_data_sections)
1783 	{
1784 	  warning (0, "-fdata-sections not supported for this target");
1785 	  flag_data_sections = 0;
1786 	}
1787     }
1788 
1789   if (flag_function_sections && profile_flag)
1790     {
1791       warning (0, "-ffunction-sections disabled; it makes profiling impossible");
1792       flag_function_sections = 0;
1793     }
1794 
1795 #ifndef HAVE_prefetch
1796   if (flag_prefetch_loop_arrays)
1797     {
1798       warning (0, "-fprefetch-loop-arrays not supported for this target");
1799       flag_prefetch_loop_arrays = 0;
1800     }
1801 #else
1802   if (flag_prefetch_loop_arrays && !HAVE_prefetch)
1803     {
1804       warning (0, "-fprefetch-loop-arrays not supported for this target (try -march switches)");
1805       flag_prefetch_loop_arrays = 0;
1806     }
1807 #endif
1808 
1809   /* This combination of options isn't handled for i386 targets and doesn't
1810      make much sense anyway, so don't allow it.  */
1811   if (flag_prefetch_loop_arrays && optimize_size)
1812     {
1813       warning (0, "-fprefetch-loop-arrays is not supported with -Os");
1814       flag_prefetch_loop_arrays = 0;
1815     }
1816 
1817 #ifndef OBJECT_FORMAT_ELF
1818 #ifndef OBJECT_FORMAT_MACHO
1819   if (flag_function_sections && write_symbols != NO_DEBUG)
1820     warning (0, "-ffunction-sections may affect debugging on some targets");
1821 #endif
1822 #endif
1823 
1824   /* The presence of IEEE signaling NaNs, implies all math can trap.  */
1825   if (flag_signaling_nans)
1826     flag_trapping_math = 1;
1827 
1828   /* With -fcx-limited-range, we do cheap and quick complex arithmetic.  */
1829   if (flag_cx_limited_range)
1830     flag_complex_method = 0;
1831 
1832   /* Targets must be able to place spill slots at lower addresses.  If the
1833      target already uses a soft frame pointer, the transition is trivial.  */
1834   if (flag_stack_protect == -1)
1835 #ifdef __arm__
1836     flag_stack_protect = FRAME_GROWS_DOWNWARD ? 1 : 0;
1837 #else
1838     flag_stack_protect = FRAME_GROWS_DOWNWARD ? 3 : 0;
1839 #endif
1840   if (!FRAME_GROWS_DOWNWARD && flag_stack_protect)
1841     {
1842       warning (0, "-fstack-protector not supported for this target");
1843       flag_stack_protect = 0;
1844     }
1845   if (!flag_stack_protect)
1846     warn_stack_protect = 0;
1847 
1848   /* ??? Unwind info is not correct around the CFG unless either a frame
1849      pointer is present or A_O_A is set.  Fixing this requires rewriting
1850      unwind info generation to be aware of the CFG and propagating states
1851      around edges.  */
1852   if (flag_unwind_tables && !ACCUMULATE_OUTGOING_ARGS
1853       && flag_omit_frame_pointer)
1854     {
1855       warning (0, "unwind tables currently requires a frame pointer "
1856 	       "for correctness");
1857       flag_omit_frame_pointer = 0;
1858     }
1859 }
1860 
1861 /* Initialize the compiler back end.  */
1862 static void
backend_init(void)1863 backend_init (void)
1864 {
1865   init_emit_once (debug_info_level == DINFO_LEVEL_NORMAL
1866 		  || debug_info_level == DINFO_LEVEL_VERBOSE
1867 #ifdef VMS_DEBUGGING_INFO
1868 		    /* Enable line number info for traceback.  */
1869 		    || debug_info_level > DINFO_LEVEL_NONE
1870 #endif
1871 		    || flag_test_coverage);
1872 
1873   init_rtlanal ();
1874   init_regs ();
1875   init_fake_stack_mems ();
1876   init_alias_once ();
1877   init_reload ();
1878   init_varasm_once ();
1879 
1880   /* The following initialization functions need to generate rtl, so
1881      provide a dummy function context for them.  */
1882   init_dummy_function_start ();
1883   init_expmed ();
1884   if (flag_caller_saves)
1885     init_caller_save ();
1886   expand_dummy_function_end ();
1887 }
1888 
1889 /* Language-dependent initialization.  Returns nonzero on success.  */
1890 static int
lang_dependent_init(const char * name)1891 lang_dependent_init (const char *name)
1892 {
1893   location_t save_loc = input_location;
1894   if (dump_base_name == 0)
1895     dump_base_name = name && name[0] ? name : "gccdump";
1896 
1897   /* Other front-end initialization.  */
1898 #ifdef USE_MAPPED_LOCATION
1899   input_location = BUILTINS_LOCATION;
1900 #else
1901   input_filename = "<built-in>";
1902   input_line = 0;
1903 #endif
1904   if (lang_hooks.init () == 0)
1905     return 0;
1906   input_location = save_loc;
1907 
1908   init_asm_output (name);
1909 
1910   /* These create various _DECL nodes, so need to be called after the
1911      front end is initialized.  */
1912   init_eh ();
1913   init_optabs ();
1914 
1915   /* The following initialization functions need to generate rtl, so
1916      provide a dummy function context for them.  */
1917   init_dummy_function_start ();
1918   init_expr_once ();
1919   expand_dummy_function_end ();
1920 
1921   /* If dbx symbol table desired, initialize writing it and output the
1922      predefined types.  */
1923   timevar_push (TV_SYMOUT);
1924 
1925 #if defined DWARF2_DEBUGGING_INFO || defined DWARF2_UNWIND_INFO
1926   if (dwarf2out_do_frame ())
1927     dwarf2out_frame_init ();
1928 #endif
1929 
1930   /* Now we have the correct original filename, we can initialize
1931      debug output.  */
1932   (*debug_hooks->init) (name);
1933 
1934   timevar_pop (TV_SYMOUT);
1935 
1936   return 1;
1937 }
1938 
1939 /* Clean up: close opened files, etc.  */
1940 
1941 static void
finalize(void)1942 finalize (void)
1943 {
1944   /* Close the dump files.  */
1945   if (flag_gen_aux_info)
1946     {
1947       fclose (aux_info_file);
1948       if (errorcount)
1949 	unlink (aux_info_file_name);
1950     }
1951 
1952   /* Close non-debugging input and output files.  Take special care to note
1953      whether fclose returns an error, since the pages might still be on the
1954      buffer chain while the file is open.  */
1955 
1956   if (asm_out_file)
1957     {
1958       if (ferror (asm_out_file) != 0)
1959 	fatal_error ("error writing to %s: %m", asm_file_name);
1960       if (fclose (asm_out_file) != 0)
1961 	fatal_error ("error closing %s: %m", asm_file_name);
1962     }
1963 
1964   finish_optimization_passes ();
1965 
1966   if (mem_report)
1967     {
1968       ggc_print_statistics ();
1969       stringpool_statistics ();
1970       dump_tree_statistics ();
1971       dump_rtx_statistics ();
1972       dump_varray_statistics ();
1973       dump_alloc_pool_statistics ();
1974       dump_ggc_loc_statistics ();
1975     }
1976 
1977   /* Free up memory for the benefit of leak detectors.  */
1978   free_reg_info ();
1979 
1980   /* Language-specific end of compilation actions.  */
1981   lang_hooks.finish ();
1982 }
1983 
1984 /* Initialize the compiler, and compile the input file.  */
1985 static void
do_compile(void)1986 do_compile (void)
1987 {
1988   /* Initialize timing first.  The C front ends read the main file in
1989      the post_options hook, and C++ does file timings.  */
1990   if (time_report || !quiet_flag  || flag_detailed_statistics)
1991     timevar_init ();
1992   timevar_start (TV_TOTAL);
1993 
1994   process_options ();
1995 
1996   /* Don't do any more if an error has already occurred.  */
1997   if (!errorcount)
1998     {
1999       /* This must be run always, because it is needed to compute the FP
2000 	 predefined macros, such as __LDBL_MAX__, for targets using non
2001 	 default FP formats.  */
2002       init_adjust_machine_modes ();
2003 
2004       /* Set up the back-end if requested.  */
2005       if (!no_backend)
2006 	backend_init ();
2007 
2008       /* Language-dependent initialization.  Returns true on success.  */
2009       if (lang_dependent_init (main_input_filename))
2010 	compile_file ();
2011 
2012       finalize ();
2013     }
2014 
2015   /* Stop timing and print the times.  */
2016   timevar_stop (TV_TOTAL);
2017   timevar_print (stderr);
2018 }
2019 
2020 /* Entry point of cc1, cc1plus, jc1, f771, etc.
2021    Exit code is FATAL_EXIT_CODE if can't open files or if there were
2022    any errors, or SUCCESS_EXIT_CODE if compilation succeeded.
2023 
2024    It is not safe to call this function more than once.  */
2025 
2026 int
toplev_main(unsigned int argc,const char ** argv)2027 toplev_main (unsigned int argc, const char **argv)
2028 {
2029   save_argv = argv;
2030 
2031   /* Initialization of GCC's environment, and diagnostics.  */
2032   general_init (argv[0]);
2033 
2034   if (pledge ("stdio rpath wpath cpath", NULL) == -1)
2035 	fatal_error ("can't pledge");
2036 
2037   /* Parse the options and do minimal processing; basically just
2038      enough to default flags appropriately.  */
2039   decode_options (argc, argv);
2040 
2041   randomize ();
2042 
2043   /* Exit early if we can (e.g. -help).  */
2044   if (!exit_after_options)
2045     do_compile ();
2046 
2047   if (errorcount || sorrycount)
2048   {
2049     late_options_error ();
2050     return (FATAL_EXIT_CODE);
2051   }
2052 
2053   return (SUCCESS_EXIT_CODE);
2054 }
2055