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