common.opt: Change faddress-sanitizer to fsanitize=address.
[platform/upstream/gcc.git] / gcc / toplev.c
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, 2007, 2008, 2009, 2010,
4    2011 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 3, 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 COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* This is the top level of cc1/c++.
23    It parses command args, opens files, invokes the various passes
24    in the proper order, and counts the time used by each.
25    Error messages and low-level interface to malloc also handled here.  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "line-map.h"
32 #include "input.h"
33 #include "tree.h"
34 #include "realmpfr.h"   /* For GMP/MPFR/MPC versions, in print_version.  */
35 #include "version.h"
36 #include "rtl.h"
37 #include "tm_p.h"
38 #include "flags.h"
39 #include "insn-attr.h"
40 #include "insn-config.h"
41 #include "insn-flags.h"
42 #include "hard-reg-set.h"
43 #include "recog.h"
44 #include "output.h"
45 #include "except.h"
46 #include "function.h"
47 #include "toplev.h"
48 #include "expr.h"
49 #include "basic-block.h"
50 #include "intl.h"
51 #include "ggc.h"
52 #include "graph.h"
53 #include "regs.h"
54 #include "timevar.h"
55 #include "diagnostic.h"
56 #include "tree-diagnostic.h"
57 #include "tree-pretty-print.h"
58 #include "params.h"
59 #include "reload.h"
60 #include "ira.h"
61 #include "dwarf2asm.h"
62 #include "debug.h"
63 #include "target.h"
64 #include "common/common-target.h"
65 #include "langhooks.h"
66 #include "cfgloop.h" /* for init_set_costs */
67 #include "hosthooks.h"
68 #include "cgraph.h"
69 #include "opts.h"
70 #include "opts-diagnostic.h"
71 #include "coverage.h"
72 #include "value-prof.h"
73 #include "alloc-pool.h"
74 #include "tree-mudflap.h"
75 #include "asan.h"
76 #include "gimple.h"
77 #include "tree-ssa-alias.h"
78 #include "plugin.h"
79
80 #if defined(DBX_DEBUGGING_INFO) || defined(XCOFF_DEBUGGING_INFO)
81 #include "dbxout.h"
82 #endif
83
84 #ifdef SDB_DEBUGGING_INFO
85 #include "sdbout.h"
86 #endif
87
88 #ifdef XCOFF_DEBUGGING_INFO
89 #include "xcoffout.h"           /* Needed for external data
90                                    declarations for e.g. AIX 4.x.  */
91 #endif
92
93 static void general_init (const char *);
94 static void do_compile (void);
95 static void process_options (void);
96 static void backend_init (void);
97 static int lang_dependent_init (const char *);
98 static void init_asm_output (const char *);
99 static void finalize (bool);
100
101 static void crash_signal (int) ATTRIBUTE_NORETURN;
102 static void compile_file (void);
103
104 /* True if we don't need a backend (e.g. preprocessing only).  */
105 static bool no_backend;
106
107 /* Length of line when printing switch values.  */
108 #define MAX_LINE 75
109
110 /* Decoded options, and number of such options.  */
111 struct cl_decoded_option *save_decoded_options;
112 unsigned int save_decoded_options_count;
113
114 /* Used to enable -fvar-tracking, -fweb and -frename-registers according
115    to optimize in process_options ().  */
116 #define AUTODETECT_VALUE 2
117
118 /* Debug hooks - dependent upon command line options.  */
119
120 const struct gcc_debug_hooks *debug_hooks;
121
122 /* The FUNCTION_DECL for the function currently being compiled,
123    or 0 if between functions.  */
124 tree current_function_decl;
125
126 /* Set to the FUNC_BEGIN label of the current function, or NULL
127    if none.  */
128 const char * current_function_func_begin_label;
129
130 /* A random sequence of characters, unless overridden by user.  */
131 static const char *flag_random_seed;
132
133 /* A local time stamp derived from the time of compilation. It will be
134    zero if the system cannot provide a time.  It will be -1u, if the
135    user has specified a particular random seed.  */
136 unsigned local_tick;
137
138 /* Random number for this compilation */
139 HOST_WIDE_INT random_seed;
140
141 /* -f flags.  */
142
143 /* When non-NULL, indicates that whenever space is allocated on the
144    stack, the resulting stack pointer must not pass this
145    address---that is, for stacks that grow downward, the stack pointer
146    must always be greater than or equal to this address; for stacks
147    that grow upward, the stack pointer must be less than this address.
148    At present, the rtx may be either a REG or a SYMBOL_REF, although
149    the support provided depends on the backend.  */
150 rtx stack_limit_rtx;
151
152 /* True if the user has tagged the function with the 'section'
153    attribute.  */
154
155 bool user_defined_section_attribute = false;
156
157 struct target_flag_state default_target_flag_state;
158 #if SWITCHABLE_TARGET
159 struct target_flag_state *this_target_flag_state = &default_target_flag_state;
160 #else
161 #define this_target_flag_state (&default_target_flag_state)
162 #endif
163
164 /* The user symbol prefix after having resolved same.  */
165 const char *user_label_prefix;
166
167 /* Output files for assembler code (real compiler output)
168    and debugging dumps.  */
169
170 FILE *asm_out_file;
171 FILE *aux_info_file;
172 FILE *stack_usage_file = NULL;
173
174 /* The current working directory of a translation.  It's generally the
175    directory from which compilation was initiated, but a preprocessed
176    file may specify the original directory in which it was
177    created.  */
178
179 static const char *src_pwd;
180
181 /* Initialize src_pwd with the given string, and return true.  If it
182    was already initialized, return false.  As a special case, it may
183    be called with a NULL argument to test whether src_pwd has NOT been
184    initialized yet.  */
185
186 bool
187 set_src_pwd (const char *pwd)
188 {
189   if (src_pwd)
190     {
191       if (strcmp (src_pwd, pwd) == 0)
192         return true;
193       else
194         return false;
195     }
196
197   src_pwd = xstrdup (pwd);
198   return true;
199 }
200
201 /* Return the directory from which the translation unit was initiated,
202    in case set_src_pwd() was not called before to assign it a
203    different value.  */
204
205 const char *
206 get_src_pwd (void)
207 {
208   if (! src_pwd)
209     {
210       src_pwd = getpwd ();
211       if (!src_pwd)
212         src_pwd = ".";
213     }
214
215    return src_pwd;
216 }
217
218 /* Called when the start of a function definition is parsed,
219    this function prints on stderr the name of the function.  */
220 void
221 announce_function (tree decl)
222 {
223   if (!quiet_flag)
224     {
225       if (rtl_dump_and_exit)
226         fprintf (stderr, "%s ",
227                  identifier_to_locale (IDENTIFIER_POINTER (DECL_NAME (decl))));
228       else
229         fprintf (stderr, " %s",
230                  identifier_to_locale (lang_hooks.decl_printable_name (decl, 2)));
231       fflush (stderr);
232       pp_needs_newline (global_dc->printer) = true;
233       diagnostic_set_last_function (global_dc, (diagnostic_info *) NULL);
234     }
235 }
236
237 /* Initialize local_tick with a random number or -1 if
238    flag_random_seed is set.  */
239
240 static void
241 init_local_tick (void)
242 {
243   if (!flag_random_seed)
244     {
245       /* Try urandom first. Time of day is too likely to collide. 
246          In case of any error we just use the local tick. */
247
248       int fd = open ("/dev/urandom", O_RDONLY);
249       if (fd >= 0)
250         {
251           read (fd, &random_seed, sizeof (random_seed));
252           close (fd);
253         }
254
255       /* Now get the tick anyways  */
256 #ifdef HAVE_GETTIMEOFDAY
257       {
258         struct timeval tv;
259
260         gettimeofday (&tv, NULL);
261         local_tick = tv.tv_sec * 1000 + tv.tv_usec / 1000;
262       }
263 #else
264       {
265         time_t now = time (NULL);
266
267         if (now != (time_t)-1)
268           local_tick = (unsigned) now;
269       }
270 #endif
271     }
272   else
273     local_tick = -1;
274 }
275
276 /* Set up a default flag_random_seed and local_tick, unless the user
277    already specified one.  Must be called after init_local_tick.  */
278
279 static void
280 init_random_seed (void)
281 {
282   if (flag_random_seed)
283     {
284       char *endp;
285
286       /* When the driver passed in a hex number don't crc it again */
287       random_seed = strtoul (flag_random_seed, &endp, 0);
288       if (!(endp > flag_random_seed && *endp == 0))
289         random_seed = crc32_string (0, flag_random_seed);
290     }
291   else if (!random_seed)
292     random_seed = local_tick ^ getpid ();  /* Old racey fallback method */
293 }
294
295 /* Obtain the random_seed.  Unless NOINIT, initialize it if
296    it's not provided in the command line.  */
297
298 HOST_WIDE_INT
299 get_random_seed (bool noinit)
300 {
301   if (!flag_random_seed && !noinit)
302     init_random_seed ();
303   return random_seed;
304 }
305
306 /* Modify the random_seed string to VAL.  Return its previous
307    value.  */
308
309 const char *
310 set_random_seed (const char *val)
311 {
312   const char *old = flag_random_seed;
313   flag_random_seed = val;
314   return old;
315 }
316
317 /* Handler for fatal signals, such as SIGSEGV.  These are transformed
318    into ICE messages, which is much more user friendly.  In case the
319    error printer crashes, reset the signal to prevent infinite recursion.  */
320
321 static void
322 crash_signal (int signo)
323 {
324   signal (signo, SIG_DFL);
325
326   /* If we crashed while processing an ASM statement, then be a little more
327      graceful.  It's most likely the user's fault.  */
328   if (this_is_asm_operands)
329     {
330       output_operand_lossage ("unrecoverable error");
331       exit (FATAL_EXIT_CODE);
332     }
333
334   internal_error ("%s", strsignal (signo));
335 }
336
337 /* A subroutine of wrapup_global_declarations.  We've come to the end of
338    the compilation unit.  All deferred variables should be undeferred,
339    and all incomplete decls should be finalized.  */
340
341 void
342 wrapup_global_declaration_1 (tree decl)
343 {
344   /* We're not deferring this any longer.  Assignment is conditional to
345      avoid needlessly dirtying PCH pages.  */
346   if (CODE_CONTAINS_STRUCT (TREE_CODE (decl), TS_DECL_WITH_VIS)
347       && DECL_DEFER_OUTPUT (decl) != 0)
348     DECL_DEFER_OUTPUT (decl) = 0;
349
350   if (TREE_CODE (decl) == VAR_DECL && DECL_SIZE (decl) == 0)
351     lang_hooks.finish_incomplete_decl (decl);
352 }
353
354 /* A subroutine of wrapup_global_declarations.  Decide whether or not DECL
355    needs to be output.  Return true if it is output.  */
356
357 bool
358 wrapup_global_declaration_2 (tree decl)
359 {
360   if (TREE_ASM_WRITTEN (decl) || DECL_EXTERNAL (decl)
361       || (TREE_CODE (decl) == VAR_DECL && DECL_HAS_VALUE_EXPR_P (decl)))
362     return false;
363
364   /* Don't write out static consts, unless we still need them.
365
366      We also keep static consts if not optimizing (for debugging),
367      unless the user specified -fno-keep-static-consts.
368      ??? They might be better written into the debug information.
369      This is possible when using DWARF.
370
371      A language processor that wants static constants to be always
372      written out (even if it is not used) is responsible for
373      calling rest_of_decl_compilation itself.  E.g. the C front-end
374      calls rest_of_decl_compilation from finish_decl.
375      One motivation for this is that is conventional in some
376      environments to write things like:
377      static const char rcsid[] = "... version string ...";
378      intending to force the string to be in the executable.
379
380      A language processor that would prefer to have unneeded
381      static constants "optimized away" would just defer writing
382      them out until here.  E.g. C++ does this, because static
383      constants are often defined in header files.
384
385      ??? A tempting alternative (for both C and C++) would be
386      to force a constant to be written if and only if it is
387      defined in a main file, as opposed to an include file.  */
388
389   if (TREE_CODE (decl) == VAR_DECL && TREE_STATIC (decl))
390     {
391       struct varpool_node *node;
392       bool needed = true;
393       node = varpool_get_node (decl);
394
395       if (!node && flag_ltrans)
396         needed = false;
397       else if (node && node->finalized)
398         needed = false;
399       else if (node && node->alias)
400         needed = false;
401       else if (!cgraph_global_info_ready
402                && (TREE_USED (decl)
403                    || TREE_USED (DECL_ASSEMBLER_NAME (decl))))
404         /* needed */;
405       else if (node && node->analyzed)
406         /* needed */;
407       else if (DECL_COMDAT (decl))
408         needed = false;
409       else if (TREE_READONLY (decl) && !TREE_PUBLIC (decl)
410                && (optimize || !flag_keep_static_consts
411                    || DECL_ARTIFICIAL (decl)))
412         needed = false;
413
414       if (needed)
415         {
416           rest_of_decl_compilation (decl, 1, 1);
417           return true;
418         }
419     }
420
421   return false;
422 }
423
424 /* Do any final processing required for the declarations in VEC, of
425    which there are LEN.  We write out inline functions and variables
426    that have been deferred until this point, but which are required.
427    Returns nonzero if anything was put out.  */
428
429 bool
430 wrapup_global_declarations (tree *vec, int len)
431 {
432   bool reconsider, output_something = false;
433   int i;
434
435   for (i = 0; i < len; i++)
436     wrapup_global_declaration_1 (vec[i]);
437
438   /* Now emit any global variables or functions that we have been
439      putting off.  We need to loop in case one of the things emitted
440      here references another one which comes earlier in the list.  */
441   do
442     {
443       reconsider = false;
444       for (i = 0; i < len; i++)
445         reconsider |= wrapup_global_declaration_2 (vec[i]);
446       if (reconsider)
447         output_something = true;
448     }
449   while (reconsider);
450
451   return output_something;
452 }
453
454 /* A subroutine of check_global_declarations.  Issue appropriate warnings
455    for the global declaration DECL.  */
456
457 void
458 check_global_declaration_1 (tree decl)
459 {
460   /* Warn about any function declared static but not defined.  We don't
461      warn about variables, because many programs have static variables
462      that exist only to get some text into the object file.  */
463   if (TREE_CODE (decl) == FUNCTION_DECL
464       && DECL_INITIAL (decl) == 0
465       && DECL_EXTERNAL (decl)
466       && ! DECL_ARTIFICIAL (decl)
467       && ! TREE_NO_WARNING (decl)
468       && ! TREE_PUBLIC (decl)
469       && (warn_unused_function
470           || TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl))))
471     {
472       if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
473         pedwarn (input_location, 0, "%q+F used but never defined", decl);
474       else
475         warning (OPT_Wunused_function, "%q+F declared %<static%> but never defined", decl);
476       /* This symbol is effectively an "extern" declaration now.  */
477       TREE_PUBLIC (decl) = 1;
478     }
479
480   /* Warn about static fns or vars defined but not used.  */
481   if (((warn_unused_function && TREE_CODE (decl) == FUNCTION_DECL)
482        /* We don't warn about "static const" variables because the
483           "rcs_id" idiom uses that construction.  */
484        || (warn_unused_variable
485            && TREE_CODE (decl) == VAR_DECL && ! TREE_READONLY (decl)))
486       && ! DECL_IN_SYSTEM_HEADER (decl)
487       && ! TREE_USED (decl)
488       /* The TREE_USED bit for file-scope decls is kept in the identifier,
489          to handle multiple external decls in different scopes.  */
490       && ! (DECL_NAME (decl) && TREE_USED (DECL_NAME (decl)))
491       && ! DECL_EXTERNAL (decl)
492       && ! TREE_PUBLIC (decl)
493       /* A volatile variable might be used in some non-obvious way.  */
494       && ! TREE_THIS_VOLATILE (decl)
495       /* Global register variables must be declared to reserve them.  */
496       && ! (TREE_CODE (decl) == VAR_DECL && DECL_REGISTER (decl))
497       /* Otherwise, ask the language.  */
498       && lang_hooks.decls.warn_unused_global (decl))
499     warning ((TREE_CODE (decl) == FUNCTION_DECL)
500              ? OPT_Wunused_function
501              : OPT_Wunused_variable,
502              "%q+D defined but not used", decl);
503 }
504
505 /* Issue appropriate warnings for the global declarations in V (of
506    which there are LEN).  */
507
508 void
509 check_global_declarations (tree *v, int len)
510 {
511   int i;
512
513   for (i = 0; i < len; i++)
514     check_global_declaration_1 (v[i]);
515 }
516
517 /* Emit debugging information for all global declarations in VEC.  */
518
519 void
520 emit_debug_global_declarations (tree *vec, int len)
521 {
522   int i;
523
524   /* Avoid confusing the debug information machinery when there are errors.  */
525   if (seen_error ())
526     return;
527
528   timevar_push (TV_SYMOUT);
529   for (i = 0; i < len; i++)
530     debug_hooks->global_decl (vec[i]);
531   timevar_pop (TV_SYMOUT);
532 }
533
534 /* Compile an entire translation unit.  Write a file of assembly
535    output and various debugging dumps.  */
536
537 static void
538 compile_file (void)
539 {
540   timevar_start (TV_PHASE_PARSING);
541   timevar_push (TV_PARSE_GLOBAL);
542
543   /* Call the parser, which parses the entire file (calling
544      rest_of_compilation for each function).  */
545   lang_hooks.parse_file ();
546
547   timevar_pop (TV_PARSE_GLOBAL);
548   timevar_stop (TV_PHASE_PARSING);
549
550   /* Compilation is now finished except for writing
551      what's left of the symbol table output.  */
552
553   if (flag_syntax_only || flag_wpa)
554     return;
555
556   ggc_protect_identifiers = false;
557
558   /* This must also call finalize_compilation_unit.  */
559   lang_hooks.decls.final_write_globals ();
560
561   if (seen_error ())
562     return;
563
564   timevar_start (TV_PHASE_LATE_ASM);
565
566   /* Compilation unit is finalized.  When producing non-fat LTO object, we are
567      basically finished.  */
568   if (in_lto_p || !flag_lto || flag_fat_lto_objects)
569     {
570       /* Likewise for mudflap static object registrations.  */
571       if (flag_mudflap)
572         mudflap_finish_file ();
573
574       /* File-scope initialization for AddressSanitizer.  */
575       if (flag_asan)
576         asan_finish_file ();
577
578       output_shared_constant_pool ();
579       output_object_blocks ();
580       finish_tm_clone_pairs ();
581
582       /* Write out any pending weak symbol declarations.  */
583       weak_finish ();
584
585       /* This must be at the end before unwind and debug info.
586          Some target ports emit PIC setup thunks here.  */
587       targetm.asm_out.code_end ();
588
589       /* Do dbx symbols.  */
590       timevar_push (TV_SYMOUT);
591
592     #if defined DWARF2_DEBUGGING_INFO || defined DWARF2_UNWIND_INFO
593       if (dwarf2out_do_frame ())
594         dwarf2out_frame_finish ();
595     #endif
596
597       (*debug_hooks->finish) (main_input_filename);
598       timevar_pop (TV_SYMOUT);
599
600       /* Output some stuff at end of file if nec.  */
601
602       dw2_output_indirect_constants ();
603
604       /* Flush any pending external directives.  */
605       process_pending_assemble_externals ();
606    }
607
608   /* Emit LTO marker if LTO info has been previously emitted.  This is
609      used by collect2 to determine whether an object file contains IL.
610      We used to emit an undefined reference here, but this produces
611      link errors if an object file with IL is stored into a shared
612      library without invoking lto1.  */
613   if (flag_generate_lto)
614     {
615 #if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
616       ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE,
617                                       "__gnu_lto_v1",
618                                       (unsigned HOST_WIDE_INT) 1, 8);
619 #elif defined ASM_OUTPUT_ALIGNED_COMMON
620       ASM_OUTPUT_ALIGNED_COMMON (asm_out_file, "__gnu_lto_v1",
621                                  (unsigned HOST_WIDE_INT) 1, 8);
622 #else
623       ASM_OUTPUT_COMMON (asm_out_file, "__gnu_lto_v1",
624                          (unsigned HOST_WIDE_INT) 1,
625                          (unsigned HOST_WIDE_INT) 1);
626 #endif
627       /* Let linker plugin know that this is a slim object and must be LTOed
628          even when user did not ask for it.  */
629       if (!flag_fat_lto_objects)
630         {
631 #if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
632           ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE,
633                                           "__gnu_lto_slim",
634                                           (unsigned HOST_WIDE_INT) 1, 8);
635 #elif defined ASM_OUTPUT_ALIGNED_COMMON
636           ASM_OUTPUT_ALIGNED_COMMON (asm_out_file, "__gnu_lto_slim",
637                                      (unsigned HOST_WIDE_INT) 1, 8);
638 #else
639           ASM_OUTPUT_COMMON (asm_out_file, "__gnu_lto_slim",
640                              (unsigned HOST_WIDE_INT) 1,
641                              (unsigned HOST_WIDE_INT) 1);
642 #endif
643         }
644     }
645
646   /* Attach a special .ident directive to the end of the file to identify
647      the version of GCC which compiled this code.  The format of the .ident
648      string is patterned after the ones produced by native SVR4 compilers.  */
649   if (!flag_no_ident)
650     {
651       const char *pkg_version = "(GNU) ";
652       char *ident_str;
653
654       if (strcmp ("(GCC) ", pkgversion_string))
655         pkg_version = pkgversion_string;
656
657       ident_str = ACONCAT (("GCC: ", pkg_version, version_string, NULL));
658       targetm.asm_out.output_ident (ident_str);
659     }
660
661   /* Invoke registered plugin callbacks.  */
662   invoke_plugin_callbacks (PLUGIN_FINISH_UNIT, NULL);
663
664   /* This must be at the end.  Some target ports emit end of file directives
665      into the assembly file here, and hence we can not output anything to the
666      assembly file after this point.  */
667   targetm.asm_out.file_end ();
668
669   timevar_stop (TV_PHASE_LATE_ASM);
670 }
671
672 /* Print version information to FILE.
673    Each line begins with INDENT (for the case where FILE is the
674    assembler output file).  */
675
676 void
677 print_version (FILE *file, const char *indent)
678 {
679   static const char fmt1[] =
680 #ifdef __GNUC__
681     N_("%s%s%s %sversion %s (%s)\n%s\tcompiled by GNU C version %s, ")
682 #else
683     N_("%s%s%s %sversion %s (%s) compiled by CC, ")
684 #endif
685     ;
686   static const char fmt2[] =
687     N_("GMP version %s, MPFR version %s, MPC version %s\n");
688   static const char fmt3[] =
689     N_("%s%swarning: %s header version %s differs from library version %s.\n");
690   static const char fmt4[] =
691     N_("%s%sGGC heuristics: --param ggc-min-expand=%d --param ggc-min-heapsize=%d\n");
692 #ifndef __VERSION__
693 #define __VERSION__ "[?]"
694 #endif
695   fprintf (file,
696            file == stderr ? _(fmt1) : fmt1,
697            indent, *indent != 0 ? " " : "",
698            lang_hooks.name, pkgversion_string, version_string, TARGET_NAME,
699            indent, __VERSION__);
700
701   /* We need to stringify the GMP macro values.  Ugh, gmp_version has
702      two string formats, "i.j.k" and "i.j" when k is zero.  As of
703      gmp-4.3.0, GMP always uses the 3 number format.  */
704 #define GCC_GMP_STRINGIFY_VERSION3(X) #X
705 #define GCC_GMP_STRINGIFY_VERSION2(X) GCC_GMP_STRINGIFY_VERSION3(X)
706 #define GCC_GMP_VERSION_NUM(X,Y,Z) (((X) << 16L) | ((Y) << 8) | (Z))
707 #define GCC_GMP_VERSION \
708   GCC_GMP_VERSION_NUM(__GNU_MP_VERSION, __GNU_MP_VERSION_MINOR, __GNU_MP_VERSION_PATCHLEVEL)
709 #if GCC_GMP_VERSION < GCC_GMP_VERSION_NUM(4,3,0) && __GNU_MP_VERSION_PATCHLEVEL == 0
710 #define GCC_GMP_STRINGIFY_VERSION GCC_GMP_STRINGIFY_VERSION2(__GNU_MP_VERSION) "." \
711   GCC_GMP_STRINGIFY_VERSION2(__GNU_MP_VERSION_MINOR)
712 #else
713 #define GCC_GMP_STRINGIFY_VERSION GCC_GMP_STRINGIFY_VERSION2(__GNU_MP_VERSION) "." \
714   GCC_GMP_STRINGIFY_VERSION2(__GNU_MP_VERSION_MINOR) "." \
715   GCC_GMP_STRINGIFY_VERSION2(__GNU_MP_VERSION_PATCHLEVEL)
716 #endif
717   fprintf (file,
718            file == stderr ? _(fmt2) : fmt2,
719            GCC_GMP_STRINGIFY_VERSION, MPFR_VERSION_STRING, MPC_VERSION_STRING);
720   if (strcmp (GCC_GMP_STRINGIFY_VERSION, gmp_version))
721     fprintf (file,
722              file == stderr ? _(fmt3) : fmt3,
723              indent, *indent != 0 ? " " : "",
724              "GMP", GCC_GMP_STRINGIFY_VERSION, gmp_version);
725   if (strcmp (MPFR_VERSION_STRING, mpfr_get_version ()))
726     fprintf (file,
727              file == stderr ? _(fmt3) : fmt3,
728              indent, *indent != 0 ? " " : "",
729              "MPFR", MPFR_VERSION_STRING, mpfr_get_version ());
730   if (strcmp (MPC_VERSION_STRING, mpc_get_version ()))
731     fprintf (file,
732              file == stderr ? _(fmt3) : fmt3,
733              indent, *indent != 0 ? " " : "",
734              "MPC", MPC_VERSION_STRING, mpc_get_version ());
735   fprintf (file,
736            file == stderr ? _(fmt4) : fmt4,
737            indent, *indent != 0 ? " " : "",
738            PARAM_VALUE (GGC_MIN_EXPAND), PARAM_VALUE (GGC_MIN_HEAPSIZE));
739
740   print_plugins_versions (file, indent);
741 }
742
743 static int
744 print_to_asm_out_file (print_switch_type type, const char * text)
745 {
746   bool prepend_sep = true;
747
748   switch (type)
749     {
750     case SWITCH_TYPE_LINE_END:
751       putc ('\n', asm_out_file);
752       return 1;
753
754     case SWITCH_TYPE_LINE_START:
755       fputs (ASM_COMMENT_START, asm_out_file);
756       return strlen (ASM_COMMENT_START);
757
758     case SWITCH_TYPE_DESCRIPTIVE:
759       if (ASM_COMMENT_START[0] == 0)
760         prepend_sep = false;
761       /* Drop through.  */
762     case SWITCH_TYPE_PASSED:
763     case SWITCH_TYPE_ENABLED:
764       if (prepend_sep)
765         fputc (' ', asm_out_file);
766       fputs (text, asm_out_file);
767       /* No need to return the length here as
768          print_single_switch has already done it.  */
769       return 0;
770
771     default:
772       return -1;
773     }
774 }
775
776 static int
777 print_to_stderr (print_switch_type type, const char * text)
778 {
779   switch (type)
780     {
781     case SWITCH_TYPE_LINE_END:
782       putc ('\n', stderr);
783       return 1;
784
785     case SWITCH_TYPE_LINE_START:
786       return 0;
787
788     case SWITCH_TYPE_PASSED:
789     case SWITCH_TYPE_ENABLED:
790       fputc (' ', stderr);
791       /* Drop through.  */
792
793     case SWITCH_TYPE_DESCRIPTIVE:
794       fputs (text, stderr);
795       /* No need to return the length here as
796          print_single_switch has already done it.  */
797       return 0;
798
799     default:
800       return -1;
801     }
802 }
803
804 /* Print an option value and return the adjusted position in the line.
805    ??? print_fn doesn't handle errors, eg disk full; presumably other
806    code will catch a disk full though.  */
807
808 static int
809 print_single_switch (print_switch_fn_type print_fn,
810                      int pos,
811                      print_switch_type type,
812                      const char * text)
813 {
814   /* The ultrix fprintf returns 0 on success, so compute the result
815      we want here since we need it for the following test.  The +1
816      is for the separator character that will probably be emitted.  */
817   int len = strlen (text) + 1;
818
819   if (pos != 0
820       && pos + len > MAX_LINE)
821     {
822       print_fn (SWITCH_TYPE_LINE_END, NULL);
823       pos = 0;
824     }
825
826   if (pos == 0)
827     pos += print_fn (SWITCH_TYPE_LINE_START, NULL);
828
829   print_fn (type, text);
830   return pos + len;
831 }
832
833 /* Print active target switches using PRINT_FN.
834    POS is the current cursor position and MAX is the size of a "line".
835    Each line begins with INDENT and ends with TERM.
836    Each switch is separated from the next by SEP.  */
837
838 static void
839 print_switch_values (print_switch_fn_type print_fn)
840 {
841   int pos = 0;
842   size_t j;
843
844   /* Fill in the -frandom-seed option, if the user didn't pass it, so
845      that it can be printed below.  This helps reproducibility.  */
846   if (!flag_random_seed)
847     init_random_seed ();
848
849   /* Print the options as passed.  */
850   pos = print_single_switch (print_fn, pos,
851                              SWITCH_TYPE_DESCRIPTIVE, _("options passed: "));
852
853   for (j = 1; j < save_decoded_options_count; j++)
854     {
855       switch (save_decoded_options[j].opt_index)
856         {
857         case OPT_o:
858         case OPT_d:
859         case OPT_dumpbase:
860         case OPT_dumpdir:
861         case OPT_auxbase:
862         case OPT_quiet:
863         case OPT_version:
864           /* Ignore these.  */
865           continue;
866         }
867
868       pos = print_single_switch (print_fn, pos, SWITCH_TYPE_PASSED,
869                                  save_decoded_options[j].orig_option_with_args_text);
870     }
871
872   if (pos > 0)
873     print_fn (SWITCH_TYPE_LINE_END, NULL);
874
875   /* Print the -f and -m options that have been enabled.
876      We don't handle language specific options but printing argv
877      should suffice.  */
878   pos = print_single_switch (print_fn, 0,
879                              SWITCH_TYPE_DESCRIPTIVE, _("options enabled: "));
880
881   for (j = 0; j < cl_options_count; j++)
882     if (cl_options[j].cl_report
883         && option_enabled (j, &global_options) > 0)
884       pos = print_single_switch (print_fn, pos,
885                                  SWITCH_TYPE_ENABLED, cl_options[j].opt_text);
886
887   print_fn (SWITCH_TYPE_LINE_END, NULL);
888 }
889
890 /* Open assembly code output file.  Do this even if -fsyntax-only is
891    on, because then the driver will have provided the name of a
892    temporary file or bit bucket for us.  NAME is the file specified on
893    the command line, possibly NULL.  */
894 static void
895 init_asm_output (const char *name)
896 {
897   if (name == NULL && asm_file_name == 0)
898     asm_out_file = stdout;
899   else
900     {
901       if (asm_file_name == 0)
902         {
903           int len = strlen (dump_base_name);
904           char *dumpname = XNEWVEC (char, len + 6);
905
906           memcpy (dumpname, dump_base_name, len + 1);
907           strip_off_ending (dumpname, len);
908           strcat (dumpname, ".s");
909           asm_file_name = dumpname;
910         }
911       if (!strcmp (asm_file_name, "-"))
912         asm_out_file = stdout;
913       else
914         asm_out_file = fopen (asm_file_name, "w");
915       if (asm_out_file == 0)
916         fatal_error ("can%'t open %s for writing: %m", asm_file_name);
917     }
918
919   if (!flag_syntax_only)
920     {
921       targetm.asm_out.file_start ();
922
923       if (flag_record_gcc_switches)
924         {
925           if (targetm.asm_out.record_gcc_switches)
926             {
927               /* Let the target know that we are about to start recording.  */
928               targetm.asm_out.record_gcc_switches (SWITCH_TYPE_DESCRIPTIVE,
929                                                    NULL);
930               /* Now record the switches.  */
931               print_switch_values (targetm.asm_out.record_gcc_switches);
932               /* Let the target know that the recording is over.  */
933               targetm.asm_out.record_gcc_switches (SWITCH_TYPE_DESCRIPTIVE,
934                                                    NULL);
935             }
936           else
937             inform (input_location, "-frecord-gcc-switches is not supported by the current target");
938         }
939
940       if (flag_verbose_asm)
941         {
942           /* Print the list of switches in effect
943              into the assembler file as comments.  */
944           print_version (asm_out_file, ASM_COMMENT_START);
945           print_switch_values (print_to_asm_out_file);
946           putc ('\n', asm_out_file);
947         }
948     }
949 }
950
951 /* A helper function; used as the reallocator function for cpp's line
952    table.  */
953 static void *
954 realloc_for_line_map (void *ptr, size_t len)
955 {
956   return GGC_RESIZEVAR (void, ptr, len);
957 }
958
959 /* A helper function: used as the allocator function for
960    identifier_to_locale.  */
961 static void *
962 alloc_for_identifier_to_locale (size_t len)
963 {
964   return ggc_alloc_atomic (len);
965 }
966
967 /* Output stack usage information.  */
968 void
969 output_stack_usage (void)
970 {
971   static bool warning_issued = false;
972   enum stack_usage_kind_type { STATIC = 0, DYNAMIC, DYNAMIC_BOUNDED };
973   const char *stack_usage_kind_str[] = {
974     "static",
975     "dynamic",
976     "dynamic,bounded"
977   };
978   HOST_WIDE_INT stack_usage = current_function_static_stack_size;
979   enum stack_usage_kind_type stack_usage_kind;
980
981   if (stack_usage < 0)
982     {
983       if (!warning_issued)
984         {
985           warning (0, "stack usage computation not supported for this target");
986           warning_issued = true;
987         }
988       return;
989     }
990
991   stack_usage_kind = STATIC;
992
993   /* Add the maximum amount of space pushed onto the stack.  */
994   if (current_function_pushed_stack_size > 0)
995     {
996       stack_usage += current_function_pushed_stack_size;
997       stack_usage_kind = DYNAMIC_BOUNDED;
998     }
999
1000   /* Now on to the tricky part: dynamic stack allocation.  */
1001   if (current_function_allocates_dynamic_stack_space)
1002     {
1003       if (current_function_has_unbounded_dynamic_stack_size)
1004         stack_usage_kind = DYNAMIC;
1005       else
1006         stack_usage_kind = DYNAMIC_BOUNDED;
1007
1008       /* Add the size even in the unbounded case, this can't hurt.  */
1009       stack_usage += current_function_dynamic_stack_size;
1010     }
1011
1012   if (flag_stack_usage)
1013     {
1014       expanded_location loc
1015         = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1016       const char *raw_id, *id;
1017
1018       /* Strip the scope prefix if any.  */
1019       raw_id = lang_hooks.decl_printable_name (current_function_decl, 2);
1020       id = strrchr (raw_id, '.');
1021       if (id)
1022         id++;
1023       else
1024         id = raw_id;
1025
1026       fprintf (stack_usage_file,
1027                "%s:%d:%d:%s\t"HOST_WIDE_INT_PRINT_DEC"\t%s\n",
1028                lbasename (loc.file),
1029                loc.line,
1030                loc.column,
1031                id,
1032                stack_usage,
1033                stack_usage_kind_str[stack_usage_kind]);
1034     }
1035
1036   if (warn_stack_usage >= 0)
1037     {
1038       if (stack_usage_kind == DYNAMIC)
1039         warning (OPT_Wstack_usage_, "stack usage might be unbounded");
1040       else if (stack_usage > warn_stack_usage)
1041         {
1042           if (stack_usage_kind == DYNAMIC_BOUNDED)
1043             warning (OPT_Wstack_usage_, "stack usage might be %wd bytes",
1044                      stack_usage);
1045           else
1046             warning (OPT_Wstack_usage_, "stack usage is %wd bytes",
1047                      stack_usage);
1048         }
1049     }
1050 }
1051
1052 /* Open an auxiliary output file.  */
1053 static FILE *
1054 open_auxiliary_file (const char *ext)
1055 {
1056   char *filename;
1057   FILE *file;
1058
1059   filename = concat (aux_base_name, ".", ext, NULL);
1060   file = fopen (filename, "w");
1061   if (!file)
1062     fatal_error ("can%'t open %s for writing: %m", filename);
1063   free (filename);
1064   return file;
1065 }
1066
1067 /* Initialization of the front end environment, before command line
1068    options are parsed.  Signal handlers, internationalization etc.
1069    ARGV0 is main's argv[0].  */
1070 static void
1071 general_init (const char *argv0)
1072 {
1073   const char *p;
1074
1075   p = argv0 + strlen (argv0);
1076   while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
1077     --p;
1078   progname = p;
1079
1080   xmalloc_set_program_name (progname);
1081
1082   hex_init ();
1083
1084   /* Unlock the stdio streams.  */
1085   unlock_std_streams ();
1086
1087   gcc_init_libintl ();
1088
1089   identifier_to_locale_alloc = alloc_for_identifier_to_locale;
1090   identifier_to_locale_free = ggc_free;
1091
1092   /* Initialize the diagnostics reporting machinery, so option parsing
1093      can give warnings and errors.  */
1094   diagnostic_initialize (global_dc, N_OPTS);
1095   /* Set a default printer.  Language specific initializations will
1096      override it later.  */
1097   tree_diagnostics_defaults (global_dc);
1098   /* FIXME: This should probably be moved to C-family
1099      language-specific initializations.  */
1100   /* By default print macro expansion contexts in the diagnostic
1101      finalizer -- for tokens resulting from macro expansion.  */
1102   diagnostic_finalizer (global_dc) = virt_loc_aware_diagnostic_finalizer;
1103
1104   global_dc->show_caret
1105     = global_options_init.x_flag_diagnostics_show_caret;
1106   global_dc->show_option_requested
1107     = global_options_init.x_flag_diagnostics_show_option;
1108   global_dc->show_column
1109     = global_options_init.x_flag_show_column;
1110   global_dc->internal_error = plugins_internal_error_function;
1111   global_dc->option_enabled = option_enabled;
1112   global_dc->option_state = &global_options;
1113   global_dc->option_name = option_name;
1114
1115   /* Trap fatal signals, e.g. SIGSEGV, and convert them to ICE messages.  */
1116 #ifdef SIGSEGV
1117   signal (SIGSEGV, crash_signal);
1118 #endif
1119 #ifdef SIGILL
1120   signal (SIGILL, crash_signal);
1121 #endif
1122 #ifdef SIGBUS
1123   signal (SIGBUS, crash_signal);
1124 #endif
1125 #ifdef SIGABRT
1126   signal (SIGABRT, crash_signal);
1127 #endif
1128 #if defined SIGIOT && (!defined SIGABRT || SIGABRT != SIGIOT)
1129   signal (SIGIOT, crash_signal);
1130 #endif
1131 #ifdef SIGFPE
1132   signal (SIGFPE, crash_signal);
1133 #endif
1134
1135   /* Other host-specific signal setup.  */
1136   (*host_hooks.extra_signals)();
1137
1138   /* Initialize the garbage-collector, string pools and tree type hash
1139      table.  */
1140   init_ggc ();
1141   init_stringpool ();
1142   line_table = ggc_alloc_line_maps ();
1143   linemap_init (line_table);
1144   line_table->reallocator = realloc_for_line_map;
1145   line_table->round_alloc_size = ggc_round_alloc_size;
1146   init_ttree ();
1147
1148   /* Initialize register usage now so switches may override.  */
1149   init_reg_sets ();
1150
1151   /* Register the language-independent parameters.  */
1152   global_init_params ();
1153
1154   /* This must be done after global_init_params but before argument
1155      processing.  */
1156   init_ggc_heuristics();
1157   init_optimization_passes ();
1158   statistics_early_init ();
1159   finish_params ();
1160 }
1161
1162 /* Return true if the current target supports -fsection-anchors.  */
1163
1164 static bool
1165 target_supports_section_anchors_p (void)
1166 {
1167   if (targetm.min_anchor_offset == 0 && targetm.max_anchor_offset == 0)
1168     return false;
1169
1170   if (targetm.asm_out.output_anchor == NULL)
1171     return false;
1172
1173   return true;
1174 }
1175
1176 /* Default the align_* variables to 1 if they're still unset, and
1177    set up the align_*_log variables.  */
1178 static void
1179 init_alignments (void)
1180 {
1181   if (align_loops <= 0)
1182     align_loops = 1;
1183   if (align_loops_max_skip > align_loops)
1184     align_loops_max_skip = align_loops - 1;
1185   align_loops_log = floor_log2 (align_loops * 2 - 1);
1186   if (align_jumps <= 0)
1187     align_jumps = 1;
1188   if (align_jumps_max_skip > align_jumps)
1189     align_jumps_max_skip = align_jumps - 1;
1190   align_jumps_log = floor_log2 (align_jumps * 2 - 1);
1191   if (align_labels <= 0)
1192     align_labels = 1;
1193   align_labels_log = floor_log2 (align_labels * 2 - 1);
1194   if (align_labels_max_skip > align_labels)
1195     align_labels_max_skip = align_labels - 1;
1196   if (align_functions <= 0)
1197     align_functions = 1;
1198   align_functions_log = floor_log2 (align_functions * 2 - 1);
1199 }
1200
1201 /* Process the options that have been parsed.  */
1202 static void
1203 process_options (void)
1204 {
1205   /* Just in case lang_hooks.post_options ends up calling a debug_hook.
1206      This can happen with incorrect pre-processed input. */
1207   debug_hooks = &do_nothing_debug_hooks;
1208
1209   maximum_field_alignment = initial_max_fld_align * BITS_PER_UNIT;
1210
1211   /* Allow the front end to perform consistency checks and do further
1212      initialization based on the command line options.  This hook also
1213      sets the original filename if appropriate (e.g. foo.i -> foo.c)
1214      so we can correctly initialize debug output.  */
1215   no_backend = lang_hooks.post_options (&main_input_filename);
1216
1217   /* Some machines may reject certain combinations of options.  */
1218   targetm.target_option.override ();
1219
1220   /* Avoid any informative notes in the second run of -fcompare-debug.  */
1221   if (flag_compare_debug) 
1222     diagnostic_inhibit_notes (global_dc);
1223
1224   if (flag_section_anchors && !target_supports_section_anchors_p ())
1225     {
1226       warning (OPT_fsection_anchors,
1227                "this target does not support %qs", "-fsection-anchors");
1228       flag_section_anchors = 0;
1229     }
1230
1231   if (flag_short_enums == 2)
1232     flag_short_enums = targetm.default_short_enums ();
1233
1234   /* Set aux_base_name if not already set.  */
1235   if (aux_base_name)
1236     ;
1237   else if (main_input_filename)
1238     {
1239       char *name = xstrdup (lbasename (main_input_filename));
1240
1241       strip_off_ending (name, strlen (name));
1242       aux_base_name = name;
1243     }
1244   else
1245     aux_base_name = "gccaux";
1246
1247 #ifndef HAVE_cloog
1248   if (flag_graphite
1249       || flag_graphite_identity
1250       || flag_loop_block
1251       || flag_loop_interchange
1252       || flag_loop_strip_mine
1253       || flag_loop_parallelize_all)
1254     sorry ("Graphite loop optimizations cannot be used (-fgraphite, "
1255            "-fgraphite-identity, -floop-block, "
1256            "-floop-interchange, -floop-strip-mine, -floop-parallelize-all, "
1257            "and -ftree-loop-linear)");
1258 #endif
1259
1260   if (flag_mudflap && flag_lto)
1261     sorry ("mudflap cannot be used together with link-time optimization");
1262
1263   /* One region RA really helps to decrease the code size.  */
1264   if (flag_ira_region == IRA_REGION_AUTODETECT)
1265     flag_ira_region
1266       = optimize_size || !optimize ? IRA_REGION_ONE : IRA_REGION_MIXED;
1267
1268   if (flag_strict_volatile_bitfields > 0 && !abi_version_at_least (2))
1269     {
1270       warning (0, "-fstrict-volatile-bitfields disabled; "
1271                "it is incompatible with ABI versions < 2");
1272       flag_strict_volatile_bitfields = 0;
1273     }
1274
1275   /* Unrolling all loops implies that standard loop unrolling must also
1276      be done.  */
1277   if (flag_unroll_all_loops)
1278     flag_unroll_loops = 1;
1279
1280   /* web and rename-registers help when run after loop unrolling.  */
1281   if (flag_web == AUTODETECT_VALUE)
1282     flag_web = flag_unroll_loops || flag_peel_loops;
1283
1284   if (flag_rename_registers == AUTODETECT_VALUE)
1285     flag_rename_registers = flag_unroll_loops || flag_peel_loops;
1286
1287   if (flag_non_call_exceptions)
1288     flag_asynchronous_unwind_tables = 1;
1289   if (flag_asynchronous_unwind_tables)
1290     flag_unwind_tables = 1;
1291
1292   if (flag_value_profile_transformations)
1293     flag_profile_values = 1;
1294
1295   /* Warn about options that are not supported on this machine.  */
1296 #ifndef INSN_SCHEDULING
1297   if (flag_schedule_insns || flag_schedule_insns_after_reload)
1298     warning (0, "instruction scheduling not supported on this target machine");
1299 #endif
1300 #ifndef DELAY_SLOTS
1301   if (flag_delayed_branch)
1302     warning (0, "this target machine does not have delayed branches");
1303 #endif
1304
1305   user_label_prefix = USER_LABEL_PREFIX;
1306   if (flag_leading_underscore != -1)
1307     {
1308       /* If the default prefix is more complicated than "" or "_",
1309          issue a warning and ignore this option.  */
1310       if (user_label_prefix[0] == 0 ||
1311           (user_label_prefix[0] == '_' && user_label_prefix[1] == 0))
1312         {
1313           user_label_prefix = flag_leading_underscore ? "_" : "";
1314         }
1315       else
1316         warning (0, "-f%sleading-underscore not supported on this target machine",
1317                  flag_leading_underscore ? "" : "no-");
1318     }
1319
1320   /* If we are in verbose mode, write out the version and maybe all the
1321      option flags in use.  */
1322   if (version_flag)
1323     {
1324       print_version (stderr, "");
1325       if (! quiet_flag)
1326         print_switch_values (print_to_stderr);
1327     }
1328
1329   if (flag_syntax_only)
1330     {
1331       write_symbols = NO_DEBUG;
1332       profile_flag = 0;
1333     }
1334
1335   if (flag_gtoggle)
1336     {
1337       if (debug_info_level == DINFO_LEVEL_NONE)
1338         {
1339           debug_info_level = DINFO_LEVEL_NORMAL;
1340
1341           if (write_symbols == NO_DEBUG)
1342             write_symbols = PREFERRED_DEBUGGING_TYPE;
1343         }
1344       else
1345         debug_info_level = DINFO_LEVEL_NONE;
1346     }
1347
1348   if (flag_dump_final_insns && !flag_syntax_only && !no_backend)
1349     {
1350       FILE *final_output = fopen (flag_dump_final_insns, "w");
1351       if (!final_output)
1352         {
1353           error ("could not open final insn dump file %qs: %m",
1354                  flag_dump_final_insns);
1355           flag_dump_final_insns = NULL;
1356         }
1357       else if (fclose (final_output))
1358         {
1359           error ("could not close zeroed insn dump file %qs: %m",
1360                  flag_dump_final_insns);
1361           flag_dump_final_insns = NULL;
1362         }
1363     }
1364
1365   /* A lot of code assumes write_symbols == NO_DEBUG if the debugging
1366      level is 0.  */
1367   if (debug_info_level == DINFO_LEVEL_NONE)
1368     write_symbols = NO_DEBUG;
1369
1370   if (write_symbols == NO_DEBUG)
1371     ;
1372 #if defined(DBX_DEBUGGING_INFO)
1373   else if (write_symbols == DBX_DEBUG)
1374     debug_hooks = &dbx_debug_hooks;
1375 #endif
1376 #if defined(XCOFF_DEBUGGING_INFO)
1377   else if (write_symbols == XCOFF_DEBUG)
1378     debug_hooks = &xcoff_debug_hooks;
1379 #endif
1380 #ifdef SDB_DEBUGGING_INFO
1381   else if (write_symbols == SDB_DEBUG)
1382     debug_hooks = &sdb_debug_hooks;
1383 #endif
1384 #ifdef DWARF2_DEBUGGING_INFO
1385   else if (write_symbols == DWARF2_DEBUG)
1386     debug_hooks = &dwarf2_debug_hooks;
1387 #endif
1388 #ifdef VMS_DEBUGGING_INFO
1389   else if (write_symbols == VMS_DEBUG || write_symbols == VMS_AND_DWARF2_DEBUG)
1390     debug_hooks = &vmsdbg_debug_hooks;
1391 #endif
1392   else
1393     error ("target system does not support the \"%s\" debug format",
1394            debug_type_names[write_symbols]);
1395
1396   /* We know which debug output will be used so we can set flag_var_tracking
1397      and flag_var_tracking_uninit if the user has not specified them.  */
1398   if (debug_info_level < DINFO_LEVEL_NORMAL
1399       || debug_hooks->var_location == do_nothing_debug_hooks.var_location)
1400     {
1401       if (flag_var_tracking == 1
1402           || flag_var_tracking_uninit == 1)
1403         {
1404           if (debug_info_level < DINFO_LEVEL_NORMAL)
1405             warning (0, "variable tracking requested, but useless unless "
1406                      "producing debug info");
1407           else
1408             warning (0, "variable tracking requested, but not supported "
1409                      "by this debug format");
1410         }
1411       flag_var_tracking = 0;
1412       flag_var_tracking_uninit = 0;
1413     }
1414
1415   /* The debug hooks are used to implement -fdump-go-spec because it
1416      gives a simple and stable API for all the information we need to
1417      dump.  */
1418   if (flag_dump_go_spec != NULL)
1419     debug_hooks = dump_go_spec_init (flag_dump_go_spec, debug_hooks);
1420
1421   /* If the user specifically requested variable tracking with tagging
1422      uninitialized variables, we need to turn on variable tracking.
1423      (We already determined above that variable tracking is feasible.)  */
1424   if (flag_var_tracking_uninit == 1)
1425     flag_var_tracking = 1;
1426
1427   if (flag_var_tracking == AUTODETECT_VALUE)
1428     flag_var_tracking = optimize >= 1;
1429
1430   if (flag_var_tracking_uninit == AUTODETECT_VALUE)
1431     flag_var_tracking_uninit = flag_var_tracking;
1432
1433   if (flag_var_tracking_assignments == AUTODETECT_VALUE)
1434     flag_var_tracking_assignments = flag_var_tracking
1435       && !(flag_selective_scheduling || flag_selective_scheduling2);
1436
1437   if (flag_var_tracking_assignments_toggle)
1438     flag_var_tracking_assignments = !flag_var_tracking_assignments;
1439
1440   if (flag_var_tracking_assignments && !flag_var_tracking)
1441     flag_var_tracking = flag_var_tracking_assignments = -1;
1442
1443   if (flag_var_tracking_assignments
1444       && (flag_selective_scheduling || flag_selective_scheduling2))
1445     warning (0, "var-tracking-assignments changes selective scheduling");
1446
1447   if (flag_tree_cselim == AUTODETECT_VALUE)
1448 #ifdef HAVE_conditional_move
1449     flag_tree_cselim = 1;
1450 #else
1451     flag_tree_cselim = 0;
1452 #endif
1453
1454   /* If auxiliary info generation is desired, open the output file.
1455      This goes in the same directory as the source file--unlike
1456      all the other output files.  */
1457   if (flag_gen_aux_info)
1458     {
1459       aux_info_file = fopen (aux_info_file_name, "w");
1460       if (aux_info_file == 0)
1461         fatal_error ("can%'t open %s: %m", aux_info_file_name);
1462     }
1463
1464   if (!targetm_common.have_named_sections)
1465     {
1466       if (flag_function_sections)
1467         {
1468           warning (0, "-ffunction-sections not supported for this target");
1469           flag_function_sections = 0;
1470         }
1471       if (flag_data_sections)
1472         {
1473           warning (0, "-fdata-sections not supported for this target");
1474           flag_data_sections = 0;
1475         }
1476     }
1477
1478   if (flag_function_sections && profile_flag)
1479     {
1480       warning (0, "-ffunction-sections disabled; it makes profiling impossible");
1481       flag_function_sections = 0;
1482     }
1483
1484 #ifndef HAVE_prefetch
1485   if (flag_prefetch_loop_arrays > 0)
1486     {
1487       warning (0, "-fprefetch-loop-arrays not supported for this target");
1488       flag_prefetch_loop_arrays = 0;
1489     }
1490 #else
1491   if (flag_prefetch_loop_arrays > 0 && !HAVE_prefetch)
1492     {
1493       warning (0, "-fprefetch-loop-arrays not supported for this target (try -march switches)");
1494       flag_prefetch_loop_arrays = 0;
1495     }
1496 #endif
1497
1498   /* This combination of options isn't handled for i386 targets and doesn't
1499      make much sense anyway, so don't allow it.  */
1500   if (flag_prefetch_loop_arrays > 0 && optimize_size)
1501     {
1502       warning (0, "-fprefetch-loop-arrays is not supported with -Os");
1503       flag_prefetch_loop_arrays = 0;
1504     }
1505
1506   /* The presence of IEEE signaling NaNs, implies all math can trap.  */
1507   if (flag_signaling_nans)
1508     flag_trapping_math = 1;
1509
1510   /* We cannot reassociate if we want traps or signed zeros.  */
1511   if (flag_associative_math && (flag_trapping_math || flag_signed_zeros))
1512     {
1513       warning (0, "-fassociative-math disabled; other options take precedence");
1514       flag_associative_math = 0;
1515     }
1516
1517   /* With -fcx-limited-range, we do cheap and quick complex arithmetic.  */
1518   if (flag_cx_limited_range)
1519     flag_complex_method = 0;
1520
1521   /* With -fcx-fortran-rules, we do something in-between cheap and C99.  */
1522   if (flag_cx_fortran_rules)
1523     flag_complex_method = 1;
1524
1525   /* Targets must be able to place spill slots at lower addresses.  If the
1526      target already uses a soft frame pointer, the transition is trivial.  */
1527   if (!FRAME_GROWS_DOWNWARD && flag_stack_protect)
1528     {
1529       warning (0, "-fstack-protector not supported for this target");
1530       flag_stack_protect = 0;
1531     }
1532   if (!flag_stack_protect)
1533     warn_stack_protect = 0;
1534
1535   /* ??? Unwind info is not correct around the CFG unless either a frame
1536      pointer is present or A_O_A is set.  Fixing this requires rewriting
1537      unwind info generation to be aware of the CFG and propagating states
1538      around edges.  */
1539   if (flag_unwind_tables && !ACCUMULATE_OUTGOING_ARGS
1540       && flag_omit_frame_pointer)
1541     {
1542       warning (0, "unwind tables currently require a frame pointer "
1543                "for correctness");
1544       flag_omit_frame_pointer = 0;
1545     }
1546
1547   /* Address Sanitizer needs porting to each target architecture.  */
1548   if (flag_asan
1549       && (targetm.asan_shadow_offset == NULL
1550           || !FRAME_GROWS_DOWNWARD))
1551     {
1552       warning (0, "-fsanitize=address not supported for this target");
1553       flag_asan = 0;
1554     }
1555
1556   /* Enable -Werror=coverage-mismatch when -Werror and -Wno-error
1557      have not been set.  */
1558   if (!global_options_set.x_warnings_are_errors
1559       && warn_coverage_mismatch
1560       && (global_dc->classify_diagnostic[OPT_Wcoverage_mismatch] ==
1561           DK_UNSPECIFIED))
1562     diagnostic_classify_diagnostic (global_dc, OPT_Wcoverage_mismatch,
1563                                     DK_ERROR, UNKNOWN_LOCATION);
1564
1565   /* Save the current optimization options.  */
1566   optimization_default_node = build_optimization_node ();
1567   optimization_current_node = optimization_default_node;
1568 }
1569
1570 /* This function can be called multiple times to reinitialize the compiler
1571    back end when register classes or instruction sets have changed,
1572    before each function.  */
1573 static void
1574 backend_init_target (void)
1575 {
1576   /* Initialize alignment variables.  */
1577   init_alignments ();
1578
1579   /* This reinitializes hard_frame_pointer, and calls init_reg_modes_target()
1580      to initialize reg_raw_mode[].  */
1581   init_emit_regs ();
1582
1583   /* This invokes target hooks to set fixed_reg[] etc, which is
1584      mode-dependent.  */
1585   init_regs ();
1586
1587   /* This depends on stack_pointer_rtx.  */
1588   init_fake_stack_mems ();
1589
1590   /* Sets static_base_value[HARD_FRAME_POINTER_REGNUM], which is
1591      mode-dependent.  */
1592   init_alias_target ();
1593
1594   /* Depends on HARD_FRAME_POINTER_REGNUM.  */
1595   init_reload ();
1596
1597   /* The following initialization functions need to generate rtl, so
1598      provide a dummy function context for them.  */
1599   init_dummy_function_start ();
1600
1601   /* rtx_cost is mode-dependent, so cached values need to be recomputed
1602      on a mode change.  */
1603   init_expmed ();
1604   init_lower_subreg ();
1605
1606   /* We may need to recompute regno_save_code[] and regno_restore_code[]
1607      after a mode change as well.  */
1608   caller_save_initialized_p = false;
1609
1610   expand_dummy_function_end ();
1611 }
1612
1613 /* Initialize the compiler back end.  This function is called only once,
1614    when starting the compiler.  */
1615 static void
1616 backend_init (void)
1617 {
1618   init_emit_once ();
1619
1620   init_rtlanal ();
1621   init_inline_once ();
1622   init_varasm_once ();
1623   save_register_info ();
1624
1625   /* Initialize the target-specific back end pieces.  */
1626   ira_init_once ();
1627   backend_init_target ();
1628 }
1629
1630 /* Initialize excess precision settings.  */
1631 static void
1632 init_excess_precision (void)
1633 {
1634   /* Adjust excess precision handling based on the target options.  If
1635      the front end cannot handle it, flag_excess_precision_cmdline
1636      will already have been set accordingly in the post_options
1637      hook.  */
1638   gcc_assert (flag_excess_precision_cmdline != EXCESS_PRECISION_DEFAULT);
1639   flag_excess_precision = flag_excess_precision_cmdline;
1640   if (flag_unsafe_math_optimizations)
1641     flag_excess_precision = EXCESS_PRECISION_FAST;
1642   if (flag_excess_precision == EXCESS_PRECISION_STANDARD)
1643     {
1644       int flt_eval_method = TARGET_FLT_EVAL_METHOD;
1645       switch (flt_eval_method)
1646         {
1647         case -1:
1648         case 0:
1649           /* Either the target acts unpredictably (-1) or has all the
1650              operations required not to have excess precision (0).  */
1651           flag_excess_precision = EXCESS_PRECISION_FAST;
1652           break;
1653         case 1:
1654         case 2:
1655           /* In these cases, predictable excess precision makes
1656              sense.  */
1657           break;
1658         default:
1659           /* Any other implementation-defined FLT_EVAL_METHOD values
1660              require the compiler to handle the associated excess
1661              precision rules in excess_precision_type.  */
1662           gcc_unreachable ();
1663         }
1664     }
1665 }
1666
1667 /* Initialize things that are both lang-dependent and target-dependent.
1668    This function can be called more than once if target parameters change.  */
1669 static void
1670 lang_dependent_init_target (void)
1671 {
1672   /* This determines excess precision settings.  */
1673   init_excess_precision ();
1674
1675   /* This creates various _DECL nodes, so needs to be called after the
1676      front end is initialized.  It also depends on the HAVE_xxx macros
1677      generated from the target machine description.  */
1678   init_optabs ();
1679
1680   /* The following initialization functions need to generate rtl, so
1681      provide a dummy function context for them.  */
1682   init_dummy_function_start ();
1683
1684   /* Do the target-specific parts of expr initialization.  */
1685   init_expr_target ();
1686
1687   /* Although the actions of these functions are language-independent,
1688      they use optabs, so we cannot call them from backend_init.  */
1689   init_set_costs ();
1690   ira_init ();
1691
1692   expand_dummy_function_end ();
1693 }
1694
1695 /* Language-dependent initialization.  Returns nonzero on success.  */
1696 static int
1697 lang_dependent_init (const char *name)
1698 {
1699   location_t save_loc = input_location;
1700   if (dump_base_name == 0)
1701     dump_base_name = name && name[0] ? name : "gccdump";
1702
1703   /* Other front-end initialization.  */
1704   input_location = BUILTINS_LOCATION;
1705   if (lang_hooks.init () == 0)
1706     return 0;
1707   input_location = save_loc;
1708
1709   if (!flag_wpa)
1710     {
1711       init_asm_output (name);
1712
1713       /* If stack usage information is desired, open the output file.  */
1714       if (flag_stack_usage)
1715         stack_usage_file = open_auxiliary_file ("su");
1716     }
1717
1718   /* This creates various _DECL nodes, so needs to be called after the
1719      front end is initialized.  */
1720   init_eh ();
1721
1722   /* Do the target-specific parts of the initialization.  */
1723   lang_dependent_init_target ();
1724
1725   if (!flag_wpa)
1726     {
1727       /* If dbx symbol table desired, initialize writing it and output the
1728          predefined types.  */
1729       timevar_push (TV_SYMOUT);
1730
1731       /* Now we have the correct original filename, we can initialize
1732          debug output.  */
1733       (*debug_hooks->init) (name);
1734
1735       timevar_pop (TV_SYMOUT);
1736     }
1737
1738   return 1;
1739 }
1740
1741
1742 /* Reinitialize everything when target parameters, such as register usage,
1743    have changed.  */
1744 void
1745 target_reinit (void)
1746 {
1747   struct rtl_data saved_x_rtl;
1748   rtx *saved_regno_reg_rtx;
1749
1750   /* Save *crtl and regno_reg_rtx around the reinitialization
1751      to allow target_reinit being called even after prepare_function_start.  */
1752   saved_regno_reg_rtx = regno_reg_rtx;
1753   if (saved_regno_reg_rtx)
1754     {  
1755       saved_x_rtl = *crtl;
1756       memset (crtl, '\0', sizeof (*crtl));
1757       regno_reg_rtx = NULL;
1758     }
1759
1760   /* Reinitialize RTL backend.  */
1761   backend_init_target ();
1762
1763   /* Reinitialize lang-dependent parts.  */
1764   lang_dependent_init_target ();
1765
1766   /* And restore it at the end, as free_after_compilation from
1767      expand_dummy_function_end clears it.  */
1768   if (saved_regno_reg_rtx)
1769     {
1770       *crtl = saved_x_rtl;
1771       regno_reg_rtx = saved_regno_reg_rtx;
1772       saved_regno_reg_rtx = NULL;
1773     }
1774 }
1775
1776 void
1777 dump_memory_report (bool final)
1778 {
1779   dump_line_table_statistics ();
1780   ggc_print_statistics ();
1781   stringpool_statistics ();
1782   dump_tree_statistics ();
1783   dump_gimple_statistics ();
1784   dump_rtx_statistics ();
1785   dump_alloc_pool_statistics ();
1786   dump_bitmap_statistics ();
1787   dump_vec_loc_statistics ();
1788   dump_ggc_loc_statistics (final);
1789   dump_alias_stats (stderr);
1790   dump_pta_stats (stderr);
1791 }
1792
1793 /* Clean up: close opened files, etc.  */
1794
1795 static void
1796 finalize (bool no_backend)
1797 {
1798   /* Close the dump files.  */
1799   if (flag_gen_aux_info)
1800     {
1801       fclose (aux_info_file);
1802       if (seen_error ())
1803         unlink (aux_info_file_name);
1804     }
1805
1806   /* Close non-debugging input and output files.  Take special care to note
1807      whether fclose returns an error, since the pages might still be on the
1808      buffer chain while the file is open.  */
1809
1810   if (asm_out_file)
1811     {
1812       if (ferror (asm_out_file) != 0)
1813         fatal_error ("error writing to %s: %m", asm_file_name);
1814       if (fclose (asm_out_file) != 0)
1815         fatal_error ("error closing %s: %m", asm_file_name);
1816     }
1817
1818   if (stack_usage_file)
1819     fclose (stack_usage_file);
1820
1821   if (!no_backend)
1822     {
1823       statistics_fini ();
1824
1825       finish_optimization_passes ();
1826
1827       ira_finish_once ();
1828     }
1829
1830   if (mem_report)
1831     dump_memory_report (true);
1832
1833   if (profile_report)
1834     dump_profile_report ();
1835
1836   /* Language-specific end of compilation actions.  */
1837   lang_hooks.finish ();
1838 }
1839
1840 /* Initialize the compiler, and compile the input file.  */
1841 static void
1842 do_compile (void)
1843 {
1844   /* Initialize timing first.  The C front ends read the main file in
1845      the post_options hook, and C++ does file timings.  */
1846   if (time_report || !quiet_flag  || flag_detailed_statistics)
1847     timevar_init ();
1848   timevar_start (TV_TOTAL);
1849
1850   process_options ();
1851
1852   /* Don't do any more if an error has already occurred.  */
1853   if (!seen_error ())
1854     {
1855       timevar_start (TV_PHASE_SETUP);
1856
1857       /* This must be run always, because it is needed to compute the FP
1858          predefined macros, such as __LDBL_MAX__, for targets using non
1859          default FP formats.  */
1860       init_adjust_machine_modes ();
1861
1862       /* Set up the back-end if requested.  */
1863       if (!no_backend)
1864         backend_init ();
1865
1866       /* Language-dependent initialization.  Returns true on success.  */
1867       if (lang_dependent_init (main_input_filename))
1868         {
1869           /* Initialize yet another pass.  */
1870
1871           ggc_protect_identifiers = true;
1872
1873           init_cgraph ();
1874           init_final (main_input_filename);
1875           coverage_init (aux_base_name);
1876           statistics_init ();
1877           invoke_plugin_callbacks (PLUGIN_START_UNIT, NULL);
1878
1879           timevar_stop (TV_PHASE_SETUP);
1880
1881           compile_file ();
1882         }
1883       else
1884         {
1885           timevar_stop (TV_PHASE_SETUP);
1886         }
1887
1888       timevar_start (TV_PHASE_FINALIZE);
1889
1890       finalize (no_backend);
1891
1892       timevar_stop (TV_PHASE_FINALIZE);
1893     }
1894
1895   /* Stop timing and print the times.  */
1896   timevar_stop (TV_TOTAL);
1897   timevar_print (stderr);
1898 }
1899
1900 /* Entry point of cc1, cc1plus, jc1, f771, etc.
1901    Exit code is FATAL_EXIT_CODE if can't open files or if there were
1902    any errors, or SUCCESS_EXIT_CODE if compilation succeeded.
1903
1904    It is not safe to call this function more than once.  */
1905
1906 int
1907 toplev_main (int argc, char **argv)
1908 {
1909   /* Parsing and gimplification sometimes need quite large stack.
1910      Increase stack size limits if possible.  */
1911   stack_limit_increase (64 * 1024 * 1024);
1912
1913   expandargv (&argc, &argv);
1914
1915   /* Initialization of GCC's environment, and diagnostics.  */
1916   general_init (argv[0]);
1917
1918   /* One-off initialization of options that does not need to be
1919      repeated when options are added for particular functions.  */
1920   init_options_once ();
1921
1922   /* Initialize global options structures; this must be repeated for
1923      each structure used for parsing options.  */
1924   init_options_struct (&global_options, &global_options_set);
1925   lang_hooks.init_options_struct (&global_options);
1926
1927   /* Convert the options to an array.  */
1928   decode_cmdline_options_to_array_default_mask (argc,
1929                                                 CONST_CAST2 (const char **,
1930                                                              char **, argv),
1931                                                 &save_decoded_options,
1932                                                 &save_decoded_options_count);
1933
1934   /* Perform language-specific options initialization.  */
1935   lang_hooks.init_options (save_decoded_options_count, save_decoded_options);
1936
1937   /* Parse the options and do minimal processing; basically just
1938      enough to default flags appropriately.  */
1939   decode_options (&global_options, &global_options_set,
1940                   save_decoded_options, save_decoded_options_count,
1941                   UNKNOWN_LOCATION, global_dc);
1942
1943   handle_common_deferred_options ();
1944
1945   init_local_tick ();
1946
1947   initialize_plugins ();
1948
1949   if (version_flag)
1950     print_version (stderr, "");
1951
1952   if (help_flag)
1953     print_plugins_help (stderr, "");
1954
1955   /* Exit early if we can (e.g. -help).  */
1956   if (!exit_after_options)
1957     do_compile ();
1958
1959   if (warningcount || errorcount)
1960     print_ignored_options ();
1961   diagnostic_finish (global_dc);
1962
1963   /* Invoke registered plugin callbacks if any.  */
1964   invoke_plugin_callbacks (PLUGIN_FINISH, NULL);
1965
1966   finalize_plugins ();
1967   location_adhoc_data_fini (line_table);
1968   if (seen_error ())
1969     return (FATAL_EXIT_CODE);
1970
1971   return (SUCCESS_EXIT_CODE);
1972 }