PR target/82524
[official-gcc.git] / gcc / toplev.c
blobac9d2fc18bb76f81caf24a14cf8f2787947e696f
1 /* Top level of GCC compilers (cc1, cc1plus, etc.)
2 Copyright (C) 1987-2017 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This is the top level of cc1/c++.
21 It parses command args, opens files, invokes the various passes
22 in the proper order, and counts the time used by each.
23 Error messages and low-level interface to malloc also handled here. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "backend.h"
29 #include "target.h"
30 #include "rtl.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "alloc-pool.h"
34 #include "timevar.h"
35 #include "memmodel.h"
36 #include "tm_p.h"
37 #include "optabs-libfuncs.h"
38 #include "insn-config.h"
39 #include "ira.h"
40 #include "recog.h"
41 #include "cgraph.h"
42 #include "coverage.h"
43 #include "diagnostic.h"
44 #include "varasm.h"
45 #include "tree-inline.h"
46 #include "realmpfr.h" /* For GMP/MPFR/MPC versions, in print_version. */
47 #include "version.h"
48 #include "flags.h"
49 #include "insn-attr.h"
50 #include "output.h"
51 #include "toplev.h"
52 #include "expr.h"
53 #include "intl.h"
54 #include "tree-diagnostic.h"
55 #include "params.h"
56 #include "reload.h"
57 #include "lra.h"
58 #include "dwarf2asm.h"
59 #include "debug.h"
60 #include "common/common-target.h"
61 #include "langhooks.h"
62 #include "cfgloop.h" /* for init_set_costs */
63 #include "hosthooks.h"
64 #include "opts.h"
65 #include "opts-diagnostic.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "asan.h"
69 #include "tsan.h"
70 #include "plugin.h"
71 #include "context.h"
72 #include "pass_manager.h"
73 #include "auto-profile.h"
74 #include "dwarf2out.h"
75 #include "ipa-reference.h"
76 #include "symbol-summary.h"
77 #include "tree-vrp.h"
78 #include "ipa-prop.h"
79 #include "gcse.h"
80 #include "tree-chkp.h"
81 #include "omp-offload.h"
82 #include "hsa-common.h"
83 #include "edit-context.h"
84 #include "tree-pass.h"
85 #include "dumpfile.h"
87 #if defined(DBX_DEBUGGING_INFO) || defined(XCOFF_DEBUGGING_INFO)
88 #include "dbxout.h"
89 #endif
91 #include "sdbout.h"
93 #ifdef XCOFF_DEBUGGING_INFO
94 #include "xcoffout.h" /* Needed for external data declarations. */
95 #endif
97 #include "selftest.h"
99 #ifdef HAVE_isl
100 #include <isl/version.h>
101 #endif
103 static void general_init (const char *, bool);
104 static void do_compile ();
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 (bool);
111 static void crash_signal (int) ATTRIBUTE_NORETURN;
112 static void compile_file (void);
114 /* True if we don't need a backend (e.g. preprocessing only). */
115 static bool no_backend;
117 /* Length of line when printing switch values. */
118 #define MAX_LINE 75
120 /* Decoded options, and number of such options. */
121 struct cl_decoded_option *save_decoded_options;
122 unsigned int save_decoded_options_count;
124 /* Used to enable -fvar-tracking, -fweb and -frename-registers according
125 to optimize in process_options (). */
126 #define AUTODETECT_VALUE 2
128 /* Debug hooks - dependent upon command line options. */
130 const struct gcc_debug_hooks *debug_hooks;
132 /* The FUNCTION_DECL for the function currently being compiled,
133 or 0 if between functions. */
134 tree current_function_decl;
136 /* Set to the FUNC_BEGIN label of the current function, or NULL
137 if none. */
138 const char * current_function_func_begin_label;
140 /* A random sequence of characters, unless overridden by user. */
141 static const char *flag_random_seed;
143 /* A local time stamp derived from the time of compilation. It will be
144 zero if the system cannot provide a time. It will be -1u, if the
145 user has specified a particular random seed. */
146 unsigned local_tick;
148 /* Random number for this compilation */
149 HOST_WIDE_INT random_seed;
151 /* -f flags. */
153 /* When non-NULL, indicates that whenever space is allocated on the
154 stack, the resulting stack pointer must not pass this
155 address---that is, for stacks that grow downward, the stack pointer
156 must always be greater than or equal to this address; for stacks
157 that grow upward, the stack pointer must be less than this address.
158 At present, the rtx may be either a REG or a SYMBOL_REF, although
159 the support provided depends on the backend. */
160 rtx stack_limit_rtx;
162 struct target_flag_state default_target_flag_state;
163 #if SWITCHABLE_TARGET
164 struct target_flag_state *this_target_flag_state = &default_target_flag_state;
165 #else
166 #define this_target_flag_state (&default_target_flag_state)
167 #endif
169 /* The user symbol prefix after having resolved same. */
170 const char *user_label_prefix;
172 /* Output files for assembler code (real compiler output)
173 and debugging dumps. */
175 FILE *asm_out_file;
176 FILE *aux_info_file;
177 FILE *stack_usage_file = NULL;
179 /* The current working directory of a translation. It's generally the
180 directory from which compilation was initiated, but a preprocessed
181 file may specify the original directory in which it was
182 created. */
184 static const char *src_pwd;
186 /* Initialize src_pwd with the given string, and return true. If it
187 was already initialized, return false. As a special case, it may
188 be called with a NULL argument to test whether src_pwd has NOT been
189 initialized yet. */
191 bool
192 set_src_pwd (const char *pwd)
194 if (src_pwd)
196 if (strcmp (src_pwd, pwd) == 0)
197 return true;
198 else
199 return false;
202 src_pwd = xstrdup (pwd);
203 return true;
206 /* Return the directory from which the translation unit was initiated,
207 in case set_src_pwd() was not called before to assign it a
208 different value. */
210 const char *
211 get_src_pwd (void)
213 if (! src_pwd)
215 src_pwd = getpwd ();
216 if (!src_pwd)
217 src_pwd = ".";
220 return src_pwd;
223 /* Called when the start of a function definition is parsed,
224 this function prints on stderr the name of the function. */
225 void
226 announce_function (tree decl)
228 if (!quiet_flag)
230 if (rtl_dump_and_exit)
231 fprintf (stderr, "%s ",
232 identifier_to_locale (IDENTIFIER_POINTER (DECL_NAME (decl))));
233 else
234 fprintf (stderr, " %s",
235 identifier_to_locale (lang_hooks.decl_printable_name (decl, 2)));
236 fflush (stderr);
237 pp_needs_newline (global_dc->printer) = true;
238 diagnostic_set_last_function (global_dc, (diagnostic_info *) NULL);
242 /* Initialize local_tick with the time of day, or -1 if
243 flag_random_seed is set. */
245 static void
246 init_local_tick (void)
248 if (!flag_random_seed)
250 #ifdef HAVE_GETTIMEOFDAY
252 struct timeval tv;
254 gettimeofday (&tv, NULL);
255 local_tick = (unsigned) tv.tv_sec * 1000 + tv.tv_usec / 1000;
257 #else
259 time_t now = time (NULL);
261 if (now != (time_t)-1)
262 local_tick = (unsigned) now;
264 #endif
266 else
267 local_tick = -1;
270 /* Obtain the random_seed. Unless NOINIT, initialize it if
271 it's not provided in the command line. */
273 HOST_WIDE_INT
274 get_random_seed (bool noinit)
276 if (!random_seed && !noinit)
278 int fd = open ("/dev/urandom", O_RDONLY);
279 if (fd >= 0)
281 if (read (fd, &random_seed, sizeof (random_seed))
282 != sizeof (random_seed))
283 random_seed = 0;
284 close (fd);
286 if (!random_seed)
287 random_seed = local_tick ^ getpid ();
289 return random_seed;
292 /* Set flag_random_seed to VAL, and if non-null, reinitialize random_seed. */
294 void
295 set_random_seed (const char *val)
297 flag_random_seed = val;
298 if (flag_random_seed)
300 char *endp;
302 /* When the driver passed in a hex number don't crc it again */
303 random_seed = strtoul (flag_random_seed, &endp, 0);
304 if (!(endp > flag_random_seed && *endp == 0))
305 random_seed = crc32_string (0, flag_random_seed);
309 /* Handler for fatal signals, such as SIGSEGV. These are transformed
310 into ICE messages, which is much more user friendly. In case the
311 error printer crashes, reset the signal to prevent infinite recursion. */
313 static void
314 crash_signal (int signo)
316 signal (signo, SIG_DFL);
318 /* If we crashed while processing an ASM statement, then be a little more
319 graceful. It's most likely the user's fault. */
320 if (this_is_asm_operands)
322 output_operand_lossage ("unrecoverable error");
323 exit (FATAL_EXIT_CODE);
326 internal_error ("%s", strsignal (signo));
329 /* A subroutine of wrapup_global_declarations. We've come to the end of
330 the compilation unit. All deferred variables should be undeferred,
331 and all incomplete decls should be finalized. */
333 void
334 wrapup_global_declaration_1 (tree decl)
336 /* We're not deferring this any longer. Assignment is conditional to
337 avoid needlessly dirtying PCH pages. */
338 if (CODE_CONTAINS_STRUCT (TREE_CODE (decl), TS_DECL_WITH_VIS)
339 && DECL_DEFER_OUTPUT (decl) != 0)
340 DECL_DEFER_OUTPUT (decl) = 0;
342 if (VAR_P (decl) && DECL_SIZE (decl) == 0)
343 lang_hooks.finish_incomplete_decl (decl);
346 /* A subroutine of wrapup_global_declarations. Decide whether or not DECL
347 needs to be output. Return true if it is output. */
349 bool
350 wrapup_global_declaration_2 (tree decl)
352 if (TREE_ASM_WRITTEN (decl) || DECL_EXTERNAL (decl)
353 || (VAR_P (decl) && DECL_HAS_VALUE_EXPR_P (decl)))
354 return false;
356 /* Don't write out static consts, unless we still need them.
358 We also keep static consts if not optimizing (for debugging),
359 unless the user specified -fno-keep-static-consts.
360 ??? They might be better written into the debug information.
361 This is possible when using DWARF.
363 A language processor that wants static constants to be always
364 written out (even if it is not used) is responsible for
365 calling rest_of_decl_compilation itself. E.g. the C front-end
366 calls rest_of_decl_compilation from finish_decl.
367 One motivation for this is that is conventional in some
368 environments to write things like:
369 static const char rcsid[] = "... version string ...";
370 intending to force the string to be in the executable.
372 A language processor that would prefer to have unneeded
373 static constants "optimized away" would just defer writing
374 them out until here. E.g. C++ does this, because static
375 constants are often defined in header files.
377 ??? A tempting alternative (for both C and C++) would be
378 to force a constant to be written if and only if it is
379 defined in a main file, as opposed to an include file. */
381 if (VAR_P (decl) && TREE_STATIC (decl))
383 varpool_node *node;
384 bool needed = true;
385 node = varpool_node::get (decl);
387 if (!node && flag_ltrans)
388 needed = false;
389 else if (node && node->definition)
390 needed = false;
391 else if (node && node->alias)
392 needed = false;
393 else if (!symtab->global_info_ready
394 && (TREE_USED (decl)
395 || TREE_USED (DECL_ASSEMBLER_NAME (decl))))
396 /* needed */;
397 else if (node && node->analyzed)
398 /* needed */;
399 else if (DECL_COMDAT (decl))
400 needed = false;
401 else if (TREE_READONLY (decl) && !TREE_PUBLIC (decl)
402 && (optimize || !flag_keep_static_consts
403 || DECL_ARTIFICIAL (decl)))
404 needed = false;
406 if (needed)
408 rest_of_decl_compilation (decl, 1, 1);
409 return true;
413 return false;
416 /* Do any final processing required for the declarations in VEC, of
417 which there are LEN. We write out inline functions and variables
418 that have been deferred until this point, but which are required.
419 Returns nonzero if anything was put out. */
421 bool
422 wrapup_global_declarations (tree *vec, int len)
424 bool reconsider, output_something = false;
425 int i;
427 for (i = 0; i < len; i++)
428 wrapup_global_declaration_1 (vec[i]);
430 /* Now emit any global variables or functions that we have been
431 putting off. We need to loop in case one of the things emitted
432 here references another one which comes earlier in the list. */
435 reconsider = false;
436 for (i = 0; i < len; i++)
437 reconsider |= wrapup_global_declaration_2 (vec[i]);
438 if (reconsider)
439 output_something = true;
441 while (reconsider);
443 return output_something;
446 /* Compile an entire translation unit. Write a file of assembly
447 output and various debugging dumps. */
449 static void
450 compile_file (void)
452 timevar_start (TV_PHASE_PARSING);
453 timevar_push (TV_PARSE_GLOBAL);
455 /* Parse entire file and generate initial debug information. */
456 lang_hooks.parse_file ();
458 timevar_pop (TV_PARSE_GLOBAL);
459 timevar_stop (TV_PHASE_PARSING);
461 if (flag_dump_locations)
462 dump_location_info (stderr);
464 /* Compilation is now finished except for writing
465 what's left of the symbol table output. */
467 if (flag_syntax_only || flag_wpa)
468 return;
470 /* Reset maximum_field_alignment, it can be adjusted by #pragma pack
471 and this shouldn't influence any types built by the middle-end
472 from now on (like gcov_info_type). */
473 maximum_field_alignment = initial_max_fld_align * BITS_PER_UNIT;
475 ggc_protect_identifiers = false;
477 /* Run the actual compilation process. */
478 if (!in_lto_p)
480 timevar_start (TV_PHASE_OPT_GEN);
481 symtab->finalize_compilation_unit ();
482 timevar_stop (TV_PHASE_OPT_GEN);
485 /* Perform any post compilation-proper parser cleanups and
486 processing. This is currently only needed for the C++ parser,
487 which can be hopefully cleaned up so this hook is no longer
488 necessary. */
489 if (lang_hooks.decls.post_compilation_parsing_cleanups)
490 lang_hooks.decls.post_compilation_parsing_cleanups ();
492 if (seen_error ())
493 return;
495 timevar_start (TV_PHASE_LATE_ASM);
497 /* Compilation unit is finalized. When producing non-fat LTO object, we are
498 basically finished. */
499 if (in_lto_p || !flag_lto || flag_fat_lto_objects)
501 /* File-scope initialization for AddressSanitizer. */
502 if (flag_sanitize & SANITIZE_ADDRESS)
503 asan_finish_file ();
505 if (flag_sanitize & SANITIZE_THREAD)
506 tsan_finish_file ();
508 if (flag_check_pointer_bounds)
509 chkp_finish_file ();
511 omp_finish_file ();
513 hsa_output_brig ();
515 output_shared_constant_pool ();
516 output_object_blocks ();
517 finish_tm_clone_pairs ();
519 /* Write out any pending weak symbol declarations. */
520 weak_finish ();
522 /* This must be at the end before unwind and debug info.
523 Some target ports emit PIC setup thunks here. */
524 targetm.asm_out.code_end ();
526 /* Do dbx symbols. */
527 timevar_push (TV_SYMOUT);
529 #if defined DWARF2_DEBUGGING_INFO || defined DWARF2_UNWIND_INFO
530 if (dwarf2out_do_frame ())
531 dwarf2out_frame_finish ();
532 #endif
534 (*debug_hooks->finish) (main_input_filename);
535 timevar_pop (TV_SYMOUT);
537 /* Output some stuff at end of file if nec. */
539 dw2_output_indirect_constants ();
541 /* Flush any pending external directives. */
542 process_pending_assemble_externals ();
545 /* Emit LTO marker if LTO info has been previously emitted. This is
546 used by collect2 to determine whether an object file contains IL.
547 We used to emit an undefined reference here, but this produces
548 link errors if an object file with IL is stored into a shared
549 library without invoking lto1. */
550 if (flag_generate_lto || flag_generate_offload)
552 #if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
553 ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE,
554 "__gnu_lto_v1",
555 HOST_WIDE_INT_1U, 8);
556 #elif defined ASM_OUTPUT_ALIGNED_COMMON
557 ASM_OUTPUT_ALIGNED_COMMON (asm_out_file, "__gnu_lto_v1",
558 HOST_WIDE_INT_1U, 8);
559 #else
560 ASM_OUTPUT_COMMON (asm_out_file, "__gnu_lto_v1",
561 HOST_WIDE_INT_1U,
562 HOST_WIDE_INT_1U);
563 #endif
566 /* Let linker plugin know that this is a slim object and must be LTOed
567 even when user did not ask for it. */
568 if (flag_generate_lto && !flag_fat_lto_objects)
570 #if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
571 ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE, "__gnu_lto_slim",
572 HOST_WIDE_INT_1U, 8);
573 #elif defined ASM_OUTPUT_ALIGNED_COMMON
574 ASM_OUTPUT_ALIGNED_COMMON (asm_out_file, "__gnu_lto_slim",
575 HOST_WIDE_INT_1U, 8);
576 #else
577 ASM_OUTPUT_COMMON (asm_out_file, "__gnu_lto_slim",
578 HOST_WIDE_INT_1U,
579 HOST_WIDE_INT_1U);
580 #endif
583 /* Attach a special .ident directive to the end of the file to identify
584 the version of GCC which compiled this code. The format of the .ident
585 string is patterned after the ones produced by native SVR4 compilers. */
586 if (!flag_no_ident)
588 const char *pkg_version = "(GNU) ";
589 char *ident_str;
591 if (strcmp ("(GCC) ", pkgversion_string))
592 pkg_version = pkgversion_string;
594 ident_str = ACONCAT (("GCC: ", pkg_version, version_string, NULL));
595 targetm.asm_out.output_ident (ident_str);
598 /* Auto profile finalization. */
599 if (flag_auto_profile)
600 end_auto_profile ();
602 /* Invoke registered plugin callbacks. */
603 invoke_plugin_callbacks (PLUGIN_FINISH_UNIT, NULL);
605 /* This must be at the end. Some target ports emit end of file directives
606 into the assembly file here, and hence we can not output anything to the
607 assembly file after this point. */
608 targetm.asm_out.file_end ();
610 timevar_stop (TV_PHASE_LATE_ASM);
613 /* Print version information to FILE.
614 Each line begins with INDENT (for the case where FILE is the
615 assembler output file).
617 If SHOW_GLOBAL_STATE is true (for cc1 etc), we are within the compiler
618 proper and can print pertinent state (e.g. params and plugins).
620 If SHOW_GLOBAL_STATE is false (for use by libgccjit), we are outside the
621 compiler, and we don't hold the mutex on the compiler's global state:
622 we can't print params and plugins, since they might not be initialized,
623 or might be being manipulated by a compile running in another
624 thread. */
626 void
627 print_version (FILE *file, const char *indent, bool show_global_state)
629 static const char fmt1[] =
630 #ifdef __GNUC__
631 N_("%s%s%s %sversion %s (%s)\n%s\tcompiled by GNU C version %s, ")
632 #else
633 N_("%s%s%s %sversion %s (%s) compiled by CC, ")
634 #endif
636 static const char fmt2[] =
637 N_("GMP version %s, MPFR version %s, MPC version %s, isl version %s\n");
638 static const char fmt3[] =
639 N_("%s%swarning: %s header version %s differs from library version %s.\n");
640 static const char fmt4[] =
641 N_("%s%sGGC heuristics: --param ggc-min-expand=%d --param ggc-min-heapsize=%d\n");
642 #ifndef __VERSION__
643 #define __VERSION__ "[?]"
644 #endif
645 fprintf (file,
646 file == stderr ? _(fmt1) : fmt1,
647 indent, *indent != 0 ? " " : "",
648 lang_hooks.name, pkgversion_string, version_string, TARGET_NAME,
649 indent, __VERSION__);
651 /* We need to stringify the GMP macro values. Ugh, gmp_version has
652 two string formats, "i.j.k" and "i.j" when k is zero. As of
653 gmp-4.3.0, GMP always uses the 3 number format. */
654 #define GCC_GMP_STRINGIFY_VERSION3(X) #X
655 #define GCC_GMP_STRINGIFY_VERSION2(X) GCC_GMP_STRINGIFY_VERSION3 (X)
656 #define GCC_GMP_VERSION_NUM(X,Y,Z) (((X) << 16L) | ((Y) << 8) | (Z))
657 #define GCC_GMP_VERSION \
658 GCC_GMP_VERSION_NUM(__GNU_MP_VERSION, __GNU_MP_VERSION_MINOR, __GNU_MP_VERSION_PATCHLEVEL)
659 #if GCC_GMP_VERSION < GCC_GMP_VERSION_NUM(4,3,0) && __GNU_MP_VERSION_PATCHLEVEL == 0
660 #define GCC_GMP_STRINGIFY_VERSION \
661 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION) "." \
662 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION_MINOR)
663 #else
664 #define GCC_GMP_STRINGIFY_VERSION \
665 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION) "." \
666 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION_MINOR) "." \
667 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION_PATCHLEVEL)
668 #endif
669 fprintf (file,
670 file == stderr ? _(fmt2) : fmt2,
671 GCC_GMP_STRINGIFY_VERSION, MPFR_VERSION_STRING, MPC_VERSION_STRING,
672 #ifndef HAVE_isl
673 "none"
674 #else
675 isl_version ()
676 #endif
678 if (strcmp (GCC_GMP_STRINGIFY_VERSION, gmp_version))
679 fprintf (file,
680 file == stderr ? _(fmt3) : fmt3,
681 indent, *indent != 0 ? " " : "",
682 "GMP", GCC_GMP_STRINGIFY_VERSION, gmp_version);
683 if (strcmp (MPFR_VERSION_STRING, mpfr_get_version ()))
684 fprintf (file,
685 file == stderr ? _(fmt3) : fmt3,
686 indent, *indent != 0 ? " " : "",
687 "MPFR", MPFR_VERSION_STRING, mpfr_get_version ());
688 if (strcmp (MPC_VERSION_STRING, mpc_get_version ()))
689 fprintf (file,
690 file == stderr ? _(fmt3) : fmt3,
691 indent, *indent != 0 ? " " : "",
692 "MPC", MPC_VERSION_STRING, mpc_get_version ());
694 if (show_global_state)
696 fprintf (file,
697 file == stderr ? _(fmt4) : fmt4,
698 indent, *indent != 0 ? " " : "",
699 PARAM_VALUE (GGC_MIN_EXPAND), PARAM_VALUE (GGC_MIN_HEAPSIZE));
701 print_plugins_versions (file, indent);
705 static int
706 print_to_asm_out_file (print_switch_type type, const char * text)
708 bool prepend_sep = true;
710 switch (type)
712 case SWITCH_TYPE_LINE_END:
713 putc ('\n', asm_out_file);
714 return 1;
716 case SWITCH_TYPE_LINE_START:
717 fputs (ASM_COMMENT_START, asm_out_file);
718 return strlen (ASM_COMMENT_START);
720 case SWITCH_TYPE_DESCRIPTIVE:
721 if (ASM_COMMENT_START[0] == 0)
722 prepend_sep = false;
723 /* FALLTHRU */
724 case SWITCH_TYPE_PASSED:
725 case SWITCH_TYPE_ENABLED:
726 if (prepend_sep)
727 fputc (' ', asm_out_file);
728 fputs (text, asm_out_file);
729 /* No need to return the length here as
730 print_single_switch has already done it. */
731 return 0;
733 default:
734 return -1;
738 static int
739 print_to_stderr (print_switch_type type, const char * text)
741 switch (type)
743 case SWITCH_TYPE_LINE_END:
744 putc ('\n', stderr);
745 return 1;
747 case SWITCH_TYPE_LINE_START:
748 return 0;
750 case SWITCH_TYPE_PASSED:
751 case SWITCH_TYPE_ENABLED:
752 fputc (' ', stderr);
753 /* FALLTHRU */
755 case SWITCH_TYPE_DESCRIPTIVE:
756 fputs (text, stderr);
757 /* No need to return the length here as
758 print_single_switch has already done it. */
759 return 0;
761 default:
762 return -1;
766 /* Print an option value and return the adjusted position in the line.
767 ??? print_fn doesn't handle errors, eg disk full; presumably other
768 code will catch a disk full though. */
770 static int
771 print_single_switch (print_switch_fn_type print_fn,
772 int pos,
773 print_switch_type type,
774 const char * text)
776 /* The ultrix fprintf returns 0 on success, so compute the result
777 we want here since we need it for the following test. The +1
778 is for the separator character that will probably be emitted. */
779 int len = strlen (text) + 1;
781 if (pos != 0
782 && pos + len > MAX_LINE)
784 print_fn (SWITCH_TYPE_LINE_END, NULL);
785 pos = 0;
788 if (pos == 0)
789 pos += print_fn (SWITCH_TYPE_LINE_START, NULL);
791 print_fn (type, text);
792 return pos + len;
795 /* Print active target switches using PRINT_FN.
796 POS is the current cursor position and MAX is the size of a "line".
797 Each line begins with INDENT and ends with TERM.
798 Each switch is separated from the next by SEP. */
800 static void
801 print_switch_values (print_switch_fn_type print_fn)
803 int pos = 0;
804 size_t j;
806 /* Print the options as passed. */
807 pos = print_single_switch (print_fn, pos,
808 SWITCH_TYPE_DESCRIPTIVE, _("options passed: "));
810 for (j = 1; j < save_decoded_options_count; j++)
812 switch (save_decoded_options[j].opt_index)
814 case OPT_o:
815 case OPT_d:
816 case OPT_dumpbase:
817 case OPT_dumpdir:
818 case OPT_auxbase:
819 case OPT_quiet:
820 case OPT_version:
821 /* Ignore these. */
822 continue;
825 pos = print_single_switch (print_fn, pos, SWITCH_TYPE_PASSED,
826 save_decoded_options[j].orig_option_with_args_text);
829 if (pos > 0)
830 print_fn (SWITCH_TYPE_LINE_END, NULL);
832 /* Print the -f and -m options that have been enabled.
833 We don't handle language specific options but printing argv
834 should suffice. */
835 pos = print_single_switch (print_fn, 0,
836 SWITCH_TYPE_DESCRIPTIVE, _("options enabled: "));
838 for (j = 0; j < cl_options_count; j++)
839 if (cl_options[j].cl_report
840 && option_enabled (j, &global_options) > 0)
841 pos = print_single_switch (print_fn, pos,
842 SWITCH_TYPE_ENABLED, cl_options[j].opt_text);
844 print_fn (SWITCH_TYPE_LINE_END, NULL);
847 /* Open assembly code output file. Do this even if -fsyntax-only is
848 on, because then the driver will have provided the name of a
849 temporary file or bit bucket for us. NAME is the file specified on
850 the command line, possibly NULL. */
851 static void
852 init_asm_output (const char *name)
854 if (name == NULL && asm_file_name == 0)
855 asm_out_file = stdout;
856 else
858 if (asm_file_name == 0)
860 int len = strlen (dump_base_name);
861 char *dumpname = XNEWVEC (char, len + 6);
863 memcpy (dumpname, dump_base_name, len + 1);
864 strip_off_ending (dumpname, len);
865 strcat (dumpname, ".s");
866 asm_file_name = dumpname;
868 if (!strcmp (asm_file_name, "-"))
869 asm_out_file = stdout;
870 else if (!canonical_filename_eq (asm_file_name, name)
871 || !strcmp (asm_file_name, HOST_BIT_BUCKET))
872 asm_out_file = fopen (asm_file_name, "w");
873 else
874 /* Use UNKOWN_LOCATION to prevent gcc from printing the first
875 line in the current file. */
876 fatal_error (UNKNOWN_LOCATION,
877 "input file %qs is the same as output file",
878 asm_file_name);
879 if (asm_out_file == 0)
880 fatal_error (UNKNOWN_LOCATION,
881 "can%'t open %qs for writing: %m", asm_file_name);
884 if (!flag_syntax_only)
886 targetm.asm_out.file_start ();
888 if (flag_record_gcc_switches)
890 if (targetm.asm_out.record_gcc_switches)
892 /* Let the target know that we are about to start recording. */
893 targetm.asm_out.record_gcc_switches (SWITCH_TYPE_DESCRIPTIVE,
894 NULL);
895 /* Now record the switches. */
896 print_switch_values (targetm.asm_out.record_gcc_switches);
897 /* Let the target know that the recording is over. */
898 targetm.asm_out.record_gcc_switches (SWITCH_TYPE_DESCRIPTIVE,
899 NULL);
901 else
902 inform (UNKNOWN_LOCATION,
903 "-frecord-gcc-switches is not supported by "
904 "the current target");
907 if (flag_verbose_asm)
909 /* Print the list of switches in effect
910 into the assembler file as comments. */
911 print_version (asm_out_file, ASM_COMMENT_START, true);
912 print_switch_values (print_to_asm_out_file);
913 putc ('\n', asm_out_file);
918 /* A helper function; used as the reallocator function for cpp's line
919 table. */
920 static void *
921 realloc_for_line_map (void *ptr, size_t len)
923 return ggc_realloc (ptr, len);
926 /* A helper function: used as the allocator function for
927 identifier_to_locale. */
928 static void *
929 alloc_for_identifier_to_locale (size_t len)
931 return ggc_alloc_atomic (len);
934 /* Output stack usage information. */
935 void
936 output_stack_usage (void)
938 static bool warning_issued = false;
939 enum stack_usage_kind_type { STATIC = 0, DYNAMIC, DYNAMIC_BOUNDED };
940 const char *stack_usage_kind_str[] = {
941 "static",
942 "dynamic",
943 "dynamic,bounded"
945 HOST_WIDE_INT stack_usage = current_function_static_stack_size;
946 enum stack_usage_kind_type stack_usage_kind;
948 if (stack_usage < 0)
950 if (!warning_issued)
952 warning (0, "stack usage computation not supported for this target");
953 warning_issued = true;
955 return;
958 stack_usage_kind = STATIC;
960 /* Add the maximum amount of space pushed onto the stack. */
961 if (current_function_pushed_stack_size > 0)
963 stack_usage += current_function_pushed_stack_size;
964 stack_usage_kind = DYNAMIC_BOUNDED;
967 /* Now on to the tricky part: dynamic stack allocation. */
968 if (current_function_allocates_dynamic_stack_space)
970 if (current_function_has_unbounded_dynamic_stack_size)
971 stack_usage_kind = DYNAMIC;
972 else
973 stack_usage_kind = DYNAMIC_BOUNDED;
975 /* Add the size even in the unbounded case, this can't hurt. */
976 stack_usage += current_function_dynamic_stack_size;
979 if (flag_stack_usage)
981 expanded_location loc
982 = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
983 /* We don't want to print the full qualified name because it can be long,
984 so we strip the scope prefix, but we may need to deal with the suffix
985 created by the compiler. */
986 const char *suffix
987 = strchr (IDENTIFIER_POINTER (DECL_NAME (current_function_decl)), '.');
988 const char *name
989 = lang_hooks.decl_printable_name (current_function_decl, 2);
990 if (suffix)
992 const char *dot = strchr (name, '.');
993 while (dot && strcasecmp (dot, suffix) != 0)
995 name = dot + 1;
996 dot = strchr (name, '.');
999 else
1001 const char *dot = strrchr (name, '.');
1002 if (dot)
1003 name = dot + 1;
1006 fprintf (stack_usage_file,
1007 "%s:%d:%d:%s\t" HOST_WIDE_INT_PRINT_DEC"\t%s\n",
1008 lbasename (loc.file),
1009 loc.line,
1010 loc.column,
1011 name,
1012 stack_usage,
1013 stack_usage_kind_str[stack_usage_kind]);
1016 if (warn_stack_usage >= 0)
1018 const location_t loc = DECL_SOURCE_LOCATION (current_function_decl);
1020 if (stack_usage_kind == DYNAMIC)
1021 warning_at (loc, OPT_Wstack_usage_, "stack usage might be unbounded");
1022 else if (stack_usage > warn_stack_usage)
1024 if (stack_usage_kind == DYNAMIC_BOUNDED)
1025 warning_at (loc,
1026 OPT_Wstack_usage_, "stack usage might be %wd bytes",
1027 stack_usage);
1028 else
1029 warning_at (loc, OPT_Wstack_usage_, "stack usage is %wd bytes",
1030 stack_usage);
1035 /* Open an auxiliary output file. */
1036 static FILE *
1037 open_auxiliary_file (const char *ext)
1039 char *filename;
1040 FILE *file;
1042 filename = concat (aux_base_name, ".", ext, NULL);
1043 file = fopen (filename, "w");
1044 if (!file)
1045 fatal_error (input_location, "can%'t open %s for writing: %m", filename);
1046 free (filename);
1047 return file;
1050 /* Alternative diagnostics callback for reentered ICE reporting. */
1052 static void
1053 internal_error_reentered (diagnostic_context *, const char *, va_list *)
1055 /* Flush the dump file if emergency_dump_function itself caused an ICE. */
1056 if (dump_file)
1057 fflush (dump_file);
1060 /* Auxiliary callback for the diagnostics code. */
1062 static void
1063 internal_error_function (diagnostic_context *, const char *, va_list *)
1065 global_dc->internal_error = internal_error_reentered;
1066 warn_if_plugins ();
1067 emergency_dump_function ();
1070 /* Initialization of the front end environment, before command line
1071 options are parsed. Signal handlers, internationalization etc.
1072 ARGV0 is main's argv[0]. */
1073 static void
1074 general_init (const char *argv0, bool init_signals)
1076 const char *p;
1078 p = argv0 + strlen (argv0);
1079 while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
1080 --p;
1081 progname = p;
1083 xmalloc_set_program_name (progname);
1085 hex_init ();
1087 /* Unlock the stdio streams. */
1088 unlock_std_streams ();
1090 gcc_init_libintl ();
1092 identifier_to_locale_alloc = alloc_for_identifier_to_locale;
1093 identifier_to_locale_free = ggc_free;
1095 /* Initialize the diagnostics reporting machinery, so option parsing
1096 can give warnings and errors. */
1097 diagnostic_initialize (global_dc, N_OPTS);
1098 /* Set a default printer. Language specific initializations will
1099 override it later. */
1100 tree_diagnostics_defaults (global_dc);
1102 global_dc->show_caret
1103 = global_options_init.x_flag_diagnostics_show_caret;
1104 global_dc->show_option_requested
1105 = global_options_init.x_flag_diagnostics_show_option;
1106 global_dc->show_column
1107 = global_options_init.x_flag_show_column;
1108 global_dc->internal_error = internal_error_function;
1109 global_dc->option_enabled = option_enabled;
1110 global_dc->option_state = &global_options;
1111 global_dc->option_name = option_name;
1113 if (init_signals)
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
1135 /* Other host-specific signal setup. */
1136 (*host_hooks.extra_signals)();
1139 /* Initialize the garbage-collector, string pools and tree type hash
1140 table. */
1141 init_ggc ();
1142 init_stringpool ();
1143 input_location = UNKNOWN_LOCATION;
1144 line_table = ggc_alloc<line_maps> ();
1145 linemap_init (line_table, BUILTINS_LOCATION);
1146 line_table->reallocator = realloc_for_line_map;
1147 line_table->round_alloc_size = ggc_round_alloc_size;
1148 line_table->default_range_bits = 5;
1149 init_ttree ();
1151 /* Initialize register usage now so switches may override. */
1152 init_reg_sets ();
1154 /* Register the language-independent parameters. */
1155 global_init_params ();
1157 /* This must be done after global_init_params but before argument
1158 processing. */
1159 init_ggc_heuristics ();
1161 /* Create the singleton holder for global state. This creates the
1162 dump manager. */
1163 g = new gcc::context ();
1165 /* Allow languages and middle-end to register their dumps before the
1166 optimization passes. */
1167 g->get_dumps ()->register_dumps ();
1169 /* Create the passes. */
1170 g->set_passes (new gcc::pass_manager (g));
1172 symtab = new (ggc_cleared_alloc <symbol_table> ()) symbol_table ();
1174 statistics_early_init ();
1175 finish_params ();
1178 /* Return true if the current target supports -fsection-anchors. */
1180 static bool
1181 target_supports_section_anchors_p (void)
1183 if (targetm.min_anchor_offset == 0 && targetm.max_anchor_offset == 0)
1184 return false;
1186 if (targetm.asm_out.output_anchor == NULL)
1187 return false;
1189 return true;
1192 /* Default the align_* variables to 1 if they're still unset, and
1193 set up the align_*_log variables. */
1194 static void
1195 init_alignments (void)
1197 if (align_loops <= 0)
1198 align_loops = 1;
1199 if (align_loops_max_skip > align_loops)
1200 align_loops_max_skip = align_loops - 1;
1201 align_loops_log = floor_log2 (align_loops * 2 - 1);
1202 if (align_jumps <= 0)
1203 align_jumps = 1;
1204 if (align_jumps_max_skip > align_jumps)
1205 align_jumps_max_skip = align_jumps - 1;
1206 align_jumps_log = floor_log2 (align_jumps * 2 - 1);
1207 if (align_labels <= 0)
1208 align_labels = 1;
1209 align_labels_log = floor_log2 (align_labels * 2 - 1);
1210 if (align_labels_max_skip > align_labels)
1211 align_labels_max_skip = align_labels - 1;
1212 if (align_functions <= 0)
1213 align_functions = 1;
1214 align_functions_log = floor_log2 (align_functions * 2 - 1);
1217 /* Process the options that have been parsed. */
1218 static void
1219 process_options (void)
1221 /* Just in case lang_hooks.post_options ends up calling a debug_hook.
1222 This can happen with incorrect pre-processed input. */
1223 debug_hooks = &do_nothing_debug_hooks;
1225 maximum_field_alignment = initial_max_fld_align * BITS_PER_UNIT;
1227 /* Allow the front end to perform consistency checks and do further
1228 initialization based on the command line options. This hook also
1229 sets the original filename if appropriate (e.g. foo.i -> foo.c)
1230 so we can correctly initialize debug output. */
1231 no_backend = lang_hooks.post_options (&main_input_filename);
1233 /* Some machines may reject certain combinations of options. */
1234 location_t saved_location = input_location;
1235 input_location = UNKNOWN_LOCATION;
1236 targetm.target_option.override ();
1237 input_location = saved_location;
1239 if (flag_diagnostics_generate_patch)
1240 global_dc->edit_context_ptr = new edit_context ();
1242 /* Avoid any informative notes in the second run of -fcompare-debug. */
1243 if (flag_compare_debug)
1244 diagnostic_inhibit_notes (global_dc);
1246 if (flag_section_anchors && !target_supports_section_anchors_p ())
1248 warning_at (UNKNOWN_LOCATION, OPT_fsection_anchors,
1249 "this target does not support %qs",
1250 "-fsection-anchors");
1251 flag_section_anchors = 0;
1254 if (flag_short_enums == 2)
1255 flag_short_enums = targetm.default_short_enums ();
1257 /* Set aux_base_name if not already set. */
1258 if (aux_base_name)
1260 else if (main_input_filename)
1262 char *name = xstrdup (lbasename (main_input_filename));
1264 strip_off_ending (name, strlen (name));
1265 aux_base_name = name;
1267 else
1268 aux_base_name = "gccaux";
1270 #ifndef HAVE_isl
1271 if (flag_graphite
1272 || flag_loop_nest_optimize
1273 || flag_graphite_identity
1274 || flag_loop_parallelize_all)
1275 sorry ("Graphite loop optimizations cannot be used (isl is not available) "
1276 "(-fgraphite, -fgraphite-identity, -floop-nest-optimize, "
1277 "-floop-parallelize-all)");
1278 #endif
1280 if (flag_check_pointer_bounds)
1282 if (targetm.chkp_bound_mode () == VOIDmode)
1284 error_at (UNKNOWN_LOCATION,
1285 "%<-fcheck-pointer-bounds%> is not supported for this "
1286 "target");
1287 flag_check_pointer_bounds = 0;
1290 if (flag_sanitize & SANITIZE_BOUNDS_STRICT)
1292 error_at (UNKNOWN_LOCATION,
1293 "%<-fcheck-pointer-bounds%> is not supported with "
1294 "%<-fsanitize=bounds-strict%>");
1295 flag_check_pointer_bounds = 0;
1297 else if (flag_sanitize & SANITIZE_BOUNDS)
1299 error_at (UNKNOWN_LOCATION,
1300 "%<-fcheck-pointer-bounds%> is not supported with "
1301 "%<-fsanitize=bounds%>");
1302 flag_check_pointer_bounds = 0;
1305 if (flag_sanitize & SANITIZE_ADDRESS)
1307 error_at (UNKNOWN_LOCATION,
1308 "%<-fcheck-pointer-bounds%> is not supported with "
1309 "Address Sanitizer");
1310 flag_check_pointer_bounds = 0;
1313 if (flag_sanitize & SANITIZE_THREAD)
1315 error_at (UNKNOWN_LOCATION,
1316 "%<-fcheck-pointer-bounds%> is not supported with "
1317 "Thread Sanitizer");
1319 flag_check_pointer_bounds = 0;
1323 /* One region RA really helps to decrease the code size. */
1324 if (flag_ira_region == IRA_REGION_AUTODETECT)
1325 flag_ira_region
1326 = optimize_size || !optimize ? IRA_REGION_ONE : IRA_REGION_MIXED;
1328 if (!abi_version_at_least (2))
1330 /* -fabi-version=1 support was removed after GCC 4.9. */
1331 error_at (UNKNOWN_LOCATION,
1332 "%<-fabi-version=1%> is no longer supported");
1333 flag_abi_version = 2;
1336 /* Unrolling all loops implies that standard loop unrolling must also
1337 be done. */
1338 if (flag_unroll_all_loops)
1339 flag_unroll_loops = 1;
1341 /* web and rename-registers help when run after loop unrolling. */
1342 if (flag_web == AUTODETECT_VALUE)
1343 flag_web = flag_unroll_loops;
1345 if (flag_rename_registers == AUTODETECT_VALUE)
1346 flag_rename_registers = flag_unroll_loops;
1348 if (flag_non_call_exceptions)
1349 flag_asynchronous_unwind_tables = 1;
1350 if (flag_asynchronous_unwind_tables)
1351 flag_unwind_tables = 1;
1353 if (flag_value_profile_transformations)
1354 flag_profile_values = 1;
1356 /* Warn about options that are not supported on this machine. */
1357 #ifndef INSN_SCHEDULING
1358 if (flag_schedule_insns || flag_schedule_insns_after_reload)
1359 warning_at (UNKNOWN_LOCATION, 0,
1360 "instruction scheduling not supported on this target machine");
1361 #endif
1362 if (!DELAY_SLOTS && flag_delayed_branch)
1363 warning_at (UNKNOWN_LOCATION, 0,
1364 "this target machine does not have delayed branches");
1366 user_label_prefix = USER_LABEL_PREFIX;
1367 if (flag_leading_underscore != -1)
1369 /* If the default prefix is more complicated than "" or "_",
1370 issue a warning and ignore this option. */
1371 if (user_label_prefix[0] == 0 ||
1372 (user_label_prefix[0] == '_' && user_label_prefix[1] == 0))
1374 user_label_prefix = flag_leading_underscore ? "_" : "";
1376 else
1377 warning_at (UNKNOWN_LOCATION, 0,
1378 "-f%sleading-underscore not supported on this "
1379 "target machine", flag_leading_underscore ? "" : "no-");
1382 /* If we are in verbose mode, write out the version and maybe all the
1383 option flags in use. */
1384 if (version_flag)
1386 print_version (stderr, "", true);
1387 if (! quiet_flag)
1388 print_switch_values (print_to_stderr);
1391 if (flag_syntax_only)
1393 write_symbols = NO_DEBUG;
1394 profile_flag = 0;
1397 if (flag_gtoggle)
1399 if (debug_info_level == DINFO_LEVEL_NONE)
1401 debug_info_level = DINFO_LEVEL_NORMAL;
1403 if (write_symbols == NO_DEBUG)
1404 write_symbols = PREFERRED_DEBUGGING_TYPE;
1406 else
1407 debug_info_level = DINFO_LEVEL_NONE;
1410 if (flag_dump_final_insns && !flag_syntax_only && !no_backend)
1412 FILE *final_output = fopen (flag_dump_final_insns, "w");
1413 if (!final_output)
1415 error_at (UNKNOWN_LOCATION,
1416 "could not open final insn dump file %qs: %m",
1417 flag_dump_final_insns);
1418 flag_dump_final_insns = NULL;
1420 else if (fclose (final_output))
1422 error_at (UNKNOWN_LOCATION,
1423 "could not close zeroed insn dump file %qs: %m",
1424 flag_dump_final_insns);
1425 flag_dump_final_insns = NULL;
1429 /* A lot of code assumes write_symbols == NO_DEBUG if the debugging
1430 level is 0. */
1431 if (debug_info_level == DINFO_LEVEL_NONE)
1432 write_symbols = NO_DEBUG;
1434 if (write_symbols == NO_DEBUG)
1436 #if defined(DBX_DEBUGGING_INFO)
1437 else if (write_symbols == DBX_DEBUG)
1438 debug_hooks = &dbx_debug_hooks;
1439 #endif
1440 #if defined(XCOFF_DEBUGGING_INFO)
1441 else if (write_symbols == XCOFF_DEBUG)
1442 debug_hooks = &xcoff_debug_hooks;
1443 #endif
1444 else if (SDB_DEBUGGING_INFO && write_symbols == SDB_DEBUG)
1445 debug_hooks = &sdb_debug_hooks;
1446 #ifdef DWARF2_DEBUGGING_INFO
1447 else if (write_symbols == DWARF2_DEBUG)
1448 debug_hooks = &dwarf2_debug_hooks;
1449 #endif
1450 #ifdef VMS_DEBUGGING_INFO
1451 else if (write_symbols == VMS_DEBUG || write_symbols == VMS_AND_DWARF2_DEBUG)
1452 debug_hooks = &vmsdbg_debug_hooks;
1453 #endif
1454 #ifdef DWARF2_LINENO_DEBUGGING_INFO
1455 else if (write_symbols == DWARF2_DEBUG)
1456 debug_hooks = &dwarf2_lineno_debug_hooks;
1457 #endif
1458 else
1459 error_at (UNKNOWN_LOCATION,
1460 "target system does not support the %qs debug format",
1461 debug_type_names[write_symbols]);
1463 /* We know which debug output will be used so we can set flag_var_tracking
1464 and flag_var_tracking_uninit if the user has not specified them. */
1465 if (debug_info_level < DINFO_LEVEL_NORMAL
1466 || debug_hooks->var_location == do_nothing_debug_hooks.var_location)
1468 if (flag_var_tracking == 1
1469 || flag_var_tracking_uninit == 1)
1471 if (debug_info_level < DINFO_LEVEL_NORMAL)
1472 warning_at (UNKNOWN_LOCATION, 0,
1473 "variable tracking requested, but useless unless "
1474 "producing debug info");
1475 else
1476 warning_at (UNKNOWN_LOCATION, 0,
1477 "variable tracking requested, but not supported "
1478 "by this debug format");
1480 flag_var_tracking = 0;
1481 flag_var_tracking_uninit = 0;
1484 /* The debug hooks are used to implement -fdump-go-spec because it
1485 gives a simple and stable API for all the information we need to
1486 dump. */
1487 if (flag_dump_go_spec != NULL)
1488 debug_hooks = dump_go_spec_init (flag_dump_go_spec, debug_hooks);
1490 /* If the user specifically requested variable tracking with tagging
1491 uninitialized variables, we need to turn on variable tracking.
1492 (We already determined above that variable tracking is feasible.) */
1493 if (flag_var_tracking_uninit == 1)
1494 flag_var_tracking = 1;
1496 if (flag_var_tracking == AUTODETECT_VALUE)
1497 flag_var_tracking = optimize >= 1;
1499 if (flag_var_tracking_uninit == AUTODETECT_VALUE)
1500 flag_var_tracking_uninit = flag_var_tracking;
1502 if (flag_var_tracking_assignments == AUTODETECT_VALUE)
1503 flag_var_tracking_assignments = flag_var_tracking
1504 && !(flag_selective_scheduling || flag_selective_scheduling2);
1506 if (flag_var_tracking_assignments_toggle)
1507 flag_var_tracking_assignments = !flag_var_tracking_assignments;
1509 if (flag_var_tracking_assignments && !flag_var_tracking)
1510 flag_var_tracking = flag_var_tracking_assignments = -1;
1512 if (flag_var_tracking_assignments
1513 && (flag_selective_scheduling || flag_selective_scheduling2))
1514 warning_at (UNKNOWN_LOCATION, 0,
1515 "var-tracking-assignments changes selective scheduling");
1517 if (flag_tree_cselim == AUTODETECT_VALUE)
1519 if (HAVE_conditional_move)
1520 flag_tree_cselim = 1;
1521 else
1522 flag_tree_cselim = 0;
1525 /* If auxiliary info generation is desired, open the output file.
1526 This goes in the same directory as the source file--unlike
1527 all the other output files. */
1528 if (flag_gen_aux_info)
1530 aux_info_file = fopen (aux_info_file_name, "w");
1531 if (aux_info_file == 0)
1532 fatal_error (UNKNOWN_LOCATION,
1533 "can%'t open %s: %m", aux_info_file_name);
1536 if (!targetm_common.have_named_sections)
1538 if (flag_function_sections)
1540 warning_at (UNKNOWN_LOCATION, 0,
1541 "-ffunction-sections not supported for this target");
1542 flag_function_sections = 0;
1544 if (flag_data_sections)
1546 warning_at (UNKNOWN_LOCATION, 0,
1547 "-fdata-sections not supported for this target");
1548 flag_data_sections = 0;
1552 if (flag_prefetch_loop_arrays > 0 && !targetm.code_for_prefetch)
1554 warning_at (UNKNOWN_LOCATION, 0,
1555 "-fprefetch-loop-arrays not supported for this target");
1556 flag_prefetch_loop_arrays = 0;
1558 else if (flag_prefetch_loop_arrays > 0 && !targetm.have_prefetch ())
1560 warning_at (UNKNOWN_LOCATION, 0,
1561 "-fprefetch-loop-arrays not supported for this target "
1562 "(try -march switches)");
1563 flag_prefetch_loop_arrays = 0;
1566 /* This combination of options isn't handled for i386 targets and doesn't
1567 make much sense anyway, so don't allow it. */
1568 if (flag_prefetch_loop_arrays > 0 && optimize_size)
1570 warning_at (UNKNOWN_LOCATION, 0,
1571 "-fprefetch-loop-arrays is not supported with -Os");
1572 flag_prefetch_loop_arrays = 0;
1575 /* The presence of IEEE signaling NaNs, implies all math can trap. */
1576 if (flag_signaling_nans)
1577 flag_trapping_math = 1;
1579 /* We cannot reassociate if we want traps or signed zeros. */
1580 if (flag_associative_math && (flag_trapping_math || flag_signed_zeros))
1582 warning_at (UNKNOWN_LOCATION, 0,
1583 "-fassociative-math disabled; other options take "
1584 "precedence");
1585 flag_associative_math = 0;
1588 /* -fstack-clash-protection is not currently supported on targets
1589 where the stack grows up. */
1590 if (flag_stack_clash_protection && !STACK_GROWS_DOWNWARD)
1592 warning_at (UNKNOWN_LOCATION, 0,
1593 "%<-fstack-clash-protection%> is not supported on targets "
1594 "where the stack grows from lower to higher addresses");
1595 flag_stack_clash_protection = 0;
1598 /* We can not support -fstack-check= and -fstack-clash-protection at
1599 the same time. */
1600 if (flag_stack_check != NO_STACK_CHECK && flag_stack_clash_protection)
1602 warning_at (UNKNOWN_LOCATION, 0,
1603 "%<-fstack-check=%> and %<-fstack-clash_protection%> are "
1604 "mutually exclusive. Disabling %<-fstack-check=%>");
1605 flag_stack_check = NO_STACK_CHECK;
1608 /* With -fcx-limited-range, we do cheap and quick complex arithmetic. */
1609 if (flag_cx_limited_range)
1610 flag_complex_method = 0;
1612 /* With -fcx-fortran-rules, we do something in-between cheap and C99. */
1613 if (flag_cx_fortran_rules)
1614 flag_complex_method = 1;
1616 /* Targets must be able to place spill slots at lower addresses. If the
1617 target already uses a soft frame pointer, the transition is trivial. */
1618 if (!FRAME_GROWS_DOWNWARD && flag_stack_protect)
1620 warning_at (UNKNOWN_LOCATION, 0,
1621 "-fstack-protector not supported for this target");
1622 flag_stack_protect = 0;
1624 if (!flag_stack_protect)
1625 warn_stack_protect = 0;
1627 /* Address Sanitizer needs porting to each target architecture. */
1629 if ((flag_sanitize & SANITIZE_ADDRESS)
1630 && !FRAME_GROWS_DOWNWARD)
1632 warning_at (UNKNOWN_LOCATION, 0,
1633 "-fsanitize=address and -fsanitize=kernel-address "
1634 "are not supported for this target");
1635 flag_sanitize &= ~SANITIZE_ADDRESS;
1638 if ((flag_sanitize & SANITIZE_USER_ADDRESS)
1639 && targetm.asan_shadow_offset == NULL)
1641 warning_at (UNKNOWN_LOCATION, 0,
1642 "-fsanitize=address not supported for this target");
1643 flag_sanitize &= ~SANITIZE_ADDRESS;
1646 /* Do not use IPA optimizations for register allocation if profiler is active
1647 or patchable function entries are inserted for run-time instrumentation
1648 or port does not emit prologue and epilogue as RTL. */
1649 if (profile_flag || function_entry_patch_area_size
1650 || !targetm.have_prologue () || !targetm.have_epilogue ())
1651 flag_ipa_ra = 0;
1653 /* Enable -Werror=coverage-mismatch when -Werror and -Wno-error
1654 have not been set. */
1655 if (!global_options_set.x_warnings_are_errors
1656 && warn_coverage_mismatch
1657 && (global_dc->classify_diagnostic[OPT_Wcoverage_mismatch] ==
1658 DK_UNSPECIFIED))
1659 diagnostic_classify_diagnostic (global_dc, OPT_Wcoverage_mismatch,
1660 DK_ERROR, UNKNOWN_LOCATION);
1662 /* Save the current optimization options. */
1663 optimization_default_node = build_optimization_node (&global_options);
1664 optimization_current_node = optimization_default_node;
1666 /* Please don't change global_options after this point, those changes won't
1667 be reflected in optimization_{default,current}_node. */
1670 /* This function can be called multiple times to reinitialize the compiler
1671 back end when register classes or instruction sets have changed,
1672 before each function. */
1673 static void
1674 backend_init_target (void)
1676 /* Initialize alignment variables. */
1677 init_alignments ();
1679 /* This depends on stack_pointer_rtx. */
1680 init_fake_stack_mems ();
1682 /* Sets static_base_value[HARD_FRAME_POINTER_REGNUM], which is
1683 mode-dependent. */
1684 init_alias_target ();
1686 /* Depends on HARD_FRAME_POINTER_REGNUM. */
1687 if (!ira_use_lra_p)
1688 init_reload ();
1690 /* Depends on the enabled attribute. */
1691 recog_init ();
1693 /* The following initialization functions need to generate rtl, so
1694 provide a dummy function context for them. */
1695 init_dummy_function_start ();
1697 /* rtx_cost is mode-dependent, so cached values need to be recomputed
1698 on a mode change. */
1699 init_expmed ();
1700 init_lower_subreg ();
1701 init_set_costs ();
1703 init_expr_target ();
1704 ira_init ();
1706 /* We may need to recompute regno_save_code[] and regno_restore_code[]
1707 after a mode change as well. */
1708 caller_save_initialized_p = false;
1710 expand_dummy_function_end ();
1713 /* Initialize the compiler back end. This function is called only once,
1714 when starting the compiler. */
1715 static void
1716 backend_init (void)
1718 init_emit_once ();
1720 init_rtlanal ();
1721 init_inline_once ();
1722 init_varasm_once ();
1723 save_register_info ();
1725 /* Middle end needs this initialization for default mem attributes
1726 used by early calls to make_decl_rtl. */
1727 init_emit_regs ();
1729 /* Middle end needs this initialization for mode tables used to assign
1730 modes to vector variables. */
1731 init_regs ();
1734 /* Initialize excess precision settings.
1736 We have no need to modify anything here, just keep track of what the
1737 user requested. We'll figure out any appropriate relaxations
1738 later. */
1740 static void
1741 init_excess_precision (void)
1743 gcc_assert (flag_excess_precision_cmdline != EXCESS_PRECISION_DEFAULT);
1744 flag_excess_precision = flag_excess_precision_cmdline;
1747 /* Initialize things that are both lang-dependent and target-dependent.
1748 This function can be called more than once if target parameters change. */
1749 static void
1750 lang_dependent_init_target (void)
1752 /* This determines excess precision settings. */
1753 init_excess_precision ();
1755 /* This creates various _DECL nodes, so needs to be called after the
1756 front end is initialized. It also depends on the HAVE_xxx macros
1757 generated from the target machine description. */
1758 init_optabs ();
1760 gcc_assert (!this_target_rtl->target_specific_initialized);
1763 /* Perform initializations that are lang-dependent or target-dependent.
1764 but matters only for late optimizations and RTL generation. */
1766 static int rtl_initialized;
1768 void
1769 initialize_rtl (void)
1771 auto_timevar tv (g_timer, TV_INITIALIZE_RTL);
1773 /* Initialization done just once per compilation, but delayed
1774 till code generation. */
1775 if (!rtl_initialized)
1776 ira_init_once ();
1777 rtl_initialized = true;
1779 /* Target specific RTL backend initialization. */
1780 if (!this_target_rtl->target_specific_initialized)
1782 backend_init_target ();
1783 this_target_rtl->target_specific_initialized = true;
1787 /* Language-dependent initialization. Returns nonzero on success. */
1788 static int
1789 lang_dependent_init (const char *name)
1791 location_t save_loc = input_location;
1792 if (dump_base_name == 0)
1793 dump_base_name = name && name[0] ? name : "gccdump";
1795 /* Other front-end initialization. */
1796 input_location = BUILTINS_LOCATION;
1797 if (lang_hooks.init () == 0)
1798 return 0;
1799 input_location = save_loc;
1801 if (!flag_wpa)
1803 init_asm_output (name);
1805 /* If stack usage information is desired, open the output file. */
1806 if (flag_stack_usage)
1807 stack_usage_file = open_auxiliary_file ("su");
1810 /* This creates various _DECL nodes, so needs to be called after the
1811 front end is initialized. */
1812 init_eh ();
1814 /* Do the target-specific parts of the initialization. */
1815 lang_dependent_init_target ();
1817 if (!flag_wpa)
1819 /* If dbx symbol table desired, initialize writing it and output the
1820 predefined types. */
1821 timevar_push (TV_SYMOUT);
1823 /* Now we have the correct original filename, we can initialize
1824 debug output. */
1825 (*debug_hooks->init) (name);
1827 timevar_pop (TV_SYMOUT);
1830 return 1;
1834 /* Reinitialize everything when target parameters, such as register usage,
1835 have changed. */
1836 void
1837 target_reinit (void)
1839 struct rtl_data saved_x_rtl;
1840 rtx *saved_regno_reg_rtx;
1841 tree saved_optimization_current_node;
1842 struct target_optabs *saved_this_fn_optabs;
1844 /* Temporarily switch to the default optimization node, so that
1845 *this_target_optabs is set to the default, not reflecting
1846 whatever a previous function used for the optimize
1847 attribute. */
1848 saved_optimization_current_node = optimization_current_node;
1849 saved_this_fn_optabs = this_fn_optabs;
1850 if (saved_optimization_current_node != optimization_default_node)
1852 optimization_current_node = optimization_default_node;
1853 cl_optimization_restore
1854 (&global_options,
1855 TREE_OPTIMIZATION (optimization_default_node));
1857 this_fn_optabs = this_target_optabs;
1859 /* Save *crtl and regno_reg_rtx around the reinitialization
1860 to allow target_reinit being called even after prepare_function_start. */
1861 saved_regno_reg_rtx = regno_reg_rtx;
1862 if (saved_regno_reg_rtx)
1864 saved_x_rtl = *crtl;
1865 memset (crtl, '\0', sizeof (*crtl));
1866 regno_reg_rtx = NULL;
1869 this_target_rtl->target_specific_initialized = false;
1871 /* This initializes hard_frame_pointer, and calls init_reg_modes_target()
1872 to initialize reg_raw_mode[]. */
1873 init_emit_regs ();
1875 /* This invokes target hooks to set fixed_reg[] etc, which is
1876 mode-dependent. */
1877 init_regs ();
1879 /* Reinitialize lang-dependent parts. */
1880 lang_dependent_init_target ();
1882 /* Restore the original optimization node. */
1883 if (saved_optimization_current_node != optimization_default_node)
1885 optimization_current_node = saved_optimization_current_node;
1886 cl_optimization_restore (&global_options,
1887 TREE_OPTIMIZATION (optimization_current_node));
1889 this_fn_optabs = saved_this_fn_optabs;
1891 /* Restore regno_reg_rtx at the end, as free_after_compilation from
1892 expand_dummy_function_end clears it. */
1893 if (saved_regno_reg_rtx)
1895 *crtl = saved_x_rtl;
1896 regno_reg_rtx = saved_regno_reg_rtx;
1897 saved_regno_reg_rtx = NULL;
1901 void
1902 dump_memory_report (bool final)
1904 dump_line_table_statistics ();
1905 ggc_print_statistics ();
1906 stringpool_statistics ();
1907 dump_tree_statistics ();
1908 dump_gimple_statistics ();
1909 dump_rtx_statistics ();
1910 dump_alloc_pool_statistics ();
1911 dump_bitmap_statistics ();
1912 dump_hash_table_loc_statistics ();
1913 dump_vec_loc_statistics ();
1914 dump_ggc_loc_statistics (final);
1915 dump_alias_stats (stderr);
1916 dump_pta_stats (stderr);
1919 /* Clean up: close opened files, etc. */
1921 static void
1922 finalize (bool no_backend)
1924 /* Close the dump files. */
1925 if (flag_gen_aux_info)
1927 fclose (aux_info_file);
1928 aux_info_file = NULL;
1929 if (seen_error ())
1930 unlink (aux_info_file_name);
1933 /* Close non-debugging input and output files. Take special care to note
1934 whether fclose returns an error, since the pages might still be on the
1935 buffer chain while the file is open. */
1937 if (asm_out_file)
1939 if (ferror (asm_out_file) != 0)
1940 fatal_error (input_location, "error writing to %s: %m", asm_file_name);
1941 if (fclose (asm_out_file) != 0)
1942 fatal_error (input_location, "error closing %s: %m", asm_file_name);
1943 asm_out_file = NULL;
1946 if (stack_usage_file)
1948 fclose (stack_usage_file);
1949 stack_usage_file = NULL;
1952 if (seen_error ())
1953 coverage_remove_note_file ();
1955 if (!no_backend)
1957 statistics_fini ();
1959 g->get_passes ()->finish_optimization_passes ();
1961 lra_finish_once ();
1964 if (mem_report)
1965 dump_memory_report (true);
1967 if (profile_report)
1968 dump_profile_report ();
1970 /* Language-specific end of compilation actions. */
1971 lang_hooks.finish ();
1974 static bool
1975 standard_type_bitsize (int bitsize)
1977 /* As a special exception, we always want __int128 enabled if possible. */
1978 if (bitsize == 128)
1979 return false;
1980 if (bitsize == CHAR_TYPE_SIZE
1981 || bitsize == SHORT_TYPE_SIZE
1982 || bitsize == INT_TYPE_SIZE
1983 || bitsize == LONG_TYPE_SIZE
1984 || bitsize == LONG_LONG_TYPE_SIZE)
1985 return true;
1986 return false;
1989 /* Initialize the compiler, and compile the input file. */
1990 static void
1991 do_compile ()
1993 process_options ();
1995 /* Don't do any more if an error has already occurred. */
1996 if (!seen_error ())
1998 int i;
2000 timevar_start (TV_PHASE_SETUP);
2002 /* This must be run always, because it is needed to compute the FP
2003 predefined macros, such as __LDBL_MAX__, for targets using non
2004 default FP formats. */
2005 init_adjust_machine_modes ();
2006 init_derived_machine_modes ();
2008 /* This must happen after the backend has a chance to process
2009 command line options, but before the parsers are
2010 initialized. */
2011 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2012 if (targetm.scalar_mode_supported_p (int_n_data[i].m)
2013 && ! standard_type_bitsize (int_n_data[i].bitsize))
2014 int_n_enabled_p[i] = true;
2015 else
2016 int_n_enabled_p[i] = false;
2018 /* Set up the back-end if requested. */
2019 if (!no_backend)
2020 backend_init ();
2022 /* Language-dependent initialization. Returns true on success. */
2023 if (lang_dependent_init (main_input_filename))
2025 /* Initialize yet another pass. */
2027 ggc_protect_identifiers = true;
2029 symtab->initialize ();
2030 init_final (main_input_filename);
2031 coverage_init (aux_base_name);
2032 statistics_init ();
2033 invoke_plugin_callbacks (PLUGIN_START_UNIT, NULL);
2035 timevar_stop (TV_PHASE_SETUP);
2037 compile_file ();
2039 else
2041 timevar_stop (TV_PHASE_SETUP);
2044 timevar_start (TV_PHASE_FINALIZE);
2046 finalize (no_backend);
2048 timevar_stop (TV_PHASE_FINALIZE);
2052 toplev::toplev (timer *external_timer,
2053 bool init_signals)
2054 : m_use_TV_TOTAL (external_timer == NULL),
2055 m_init_signals (init_signals)
2057 if (external_timer)
2058 g_timer = external_timer;
2061 toplev::~toplev ()
2063 if (g_timer && m_use_TV_TOTAL)
2065 g_timer->stop (TV_TOTAL);
2066 g_timer->print (stderr);
2067 delete g_timer;
2068 g_timer = NULL;
2072 /* Potentially call timevar_init (which will create g_timevars if it
2073 doesn't already exist). */
2075 void
2076 toplev::start_timevars ()
2078 if (time_report || !quiet_flag || flag_detailed_statistics)
2079 timevar_init ();
2081 timevar_start (TV_TOTAL);
2084 /* Handle -fself-test. */
2086 void
2087 toplev::run_self_tests ()
2089 if (no_backend)
2091 error_at (UNKNOWN_LOCATION, "self-tests incompatible with -E");
2092 return;
2094 #if CHECKING_P
2095 /* Reset some state. */
2096 input_location = UNKNOWN_LOCATION;
2097 bitmap_obstack_initialize (NULL);
2099 /* Run the tests; any failures will lead to an abort of the process.
2100 Use "make selftests-gdb" to run under the debugger. */
2101 ::selftest::run_tests ();
2103 /* Cleanup. */
2104 bitmap_obstack_release (NULL);
2105 #else
2106 inform (UNKNOWN_LOCATION, "self-tests are not enabled in this build");
2107 #endif /* #if CHECKING_P */
2110 /* Entry point of cc1, cc1plus, jc1, f771, etc.
2111 Exit code is FATAL_EXIT_CODE if can't open files or if there were
2112 any errors, or SUCCESS_EXIT_CODE if compilation succeeded.
2114 It is not safe to call this function more than once. */
2117 toplev::main (int argc, char **argv)
2119 /* Parsing and gimplification sometimes need quite large stack.
2120 Increase stack size limits if possible. */
2121 stack_limit_increase (64 * 1024 * 1024);
2123 expandargv (&argc, &argv);
2125 /* Initialization of GCC's environment, and diagnostics. */
2126 general_init (argv[0], m_init_signals);
2128 /* One-off initialization of options that does not need to be
2129 repeated when options are added for particular functions. */
2130 init_options_once ();
2131 init_opts_obstack ();
2133 /* Initialize global options structures; this must be repeated for
2134 each structure used for parsing options. */
2135 init_options_struct (&global_options, &global_options_set);
2136 lang_hooks.init_options_struct (&global_options);
2138 /* Convert the options to an array. */
2139 decode_cmdline_options_to_array_default_mask (argc,
2140 CONST_CAST2 (const char **,
2141 char **, argv),
2142 &save_decoded_options,
2143 &save_decoded_options_count);
2145 /* Perform language-specific options initialization. */
2146 lang_hooks.init_options (save_decoded_options_count, save_decoded_options);
2148 /* Parse the options and do minimal processing; basically just
2149 enough to default flags appropriately. */
2150 decode_options (&global_options, &global_options_set,
2151 save_decoded_options, save_decoded_options_count,
2152 UNKNOWN_LOCATION, global_dc,
2153 targetm.target_option.override);
2155 handle_common_deferred_options ();
2157 init_local_tick ();
2159 initialize_plugins ();
2161 if (version_flag)
2162 print_version (stderr, "", true);
2164 if (help_flag)
2165 print_plugins_help (stderr, "");
2167 /* Exit early if we can (e.g. -help). */
2168 if (!exit_after_options)
2170 if (m_use_TV_TOTAL)
2171 start_timevars ();
2172 do_compile ();
2175 if (warningcount || errorcount || werrorcount)
2176 print_ignored_options ();
2178 if (flag_self_test)
2179 run_self_tests ();
2181 /* Invoke registered plugin callbacks if any. Some plugins could
2182 emit some diagnostics here. */
2183 invoke_plugin_callbacks (PLUGIN_FINISH, NULL);
2185 if (flag_diagnostics_generate_patch)
2187 gcc_assert (global_dc->edit_context_ptr);
2189 pretty_printer pp;
2190 pp_show_color (&pp) = pp_show_color (global_dc->printer);
2191 global_dc->edit_context_ptr->print_diff (&pp, true);
2192 pp_flush (&pp);
2195 diagnostic_finish (global_dc);
2197 finalize_plugins ();
2199 after_memory_report = true;
2201 if (seen_error () || werrorcount)
2202 return (FATAL_EXIT_CODE);
2204 return (SUCCESS_EXIT_CODE);
2207 /* For those that want to, this function aims to clean up enough state that
2208 you can call toplev::main again. */
2209 void
2210 toplev::finalize (void)
2212 rtl_initialized = false;
2213 this_target_rtl->target_specific_initialized = false;
2215 /* Needs to be called before cgraph_c_finalize since it uses symtab. */
2216 ipa_reference_c_finalize ();
2218 cgraph_c_finalize ();
2219 cgraphunit_c_finalize ();
2220 dwarf2out_c_finalize ();
2221 gcse_c_finalize ();
2222 ipa_cp_c_finalize ();
2223 ira_costs_c_finalize ();
2224 params_c_finalize ();
2226 finalize_options_struct (&global_options);
2227 finalize_options_struct (&global_options_set);
2229 /* save_decoded_options uses opts_obstack, so these must
2230 be cleaned up together. */
2231 obstack_free (&opts_obstack, NULL);
2232 XDELETEVEC (save_decoded_options);
2233 save_decoded_options = NULL;
2234 save_decoded_options_count = 0;
2236 /* Clean up the context (and pass_manager etc). */
2237 delete g;
2238 g = NULL;