[gcc/testsuite]
[official-gcc.git] / gcc / toplev.c
blob7d2b8fffa0bc545159302e7537beb098c616bedf
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 a random number or -1 if
243 flag_random_seed is set. */
245 static void
246 init_local_tick (void)
248 if (!flag_random_seed)
250 /* Try urandom first. Time of day is too likely to collide.
251 In case of any error we just use the local tick. */
253 int fd = open ("/dev/urandom", O_RDONLY);
254 if (fd >= 0)
256 if (read (fd, &random_seed, sizeof (random_seed))
257 != sizeof (random_seed))
258 random_seed = 0;
259 close (fd);
262 /* Now get the tick anyways */
263 #ifdef HAVE_GETTIMEOFDAY
265 struct timeval tv;
267 gettimeofday (&tv, NULL);
268 local_tick = (unsigned) tv.tv_sec * 1000 + tv.tv_usec / 1000;
270 #else
272 time_t now = time (NULL);
274 if (now != (time_t)-1)
275 local_tick = (unsigned) now;
277 #endif
279 else
280 local_tick = -1;
283 /* Set up a default flag_random_seed and local_tick, unless the user
284 already specified one. Must be called after init_local_tick. */
286 static void
287 init_random_seed (void)
289 if (!random_seed)
290 random_seed = local_tick ^ getpid (); /* Old racey fallback method */
293 /* Obtain the random_seed. Unless NOINIT, initialize it if
294 it's not provided in the command line. */
296 HOST_WIDE_INT
297 get_random_seed (bool noinit)
299 if (!flag_random_seed && !noinit)
300 init_random_seed ();
301 return random_seed;
304 /* Modify the random_seed string to VAL. Return its previous
305 value. */
307 const char *
308 set_random_seed (const char *val)
310 const char *old = flag_random_seed;
311 flag_random_seed = val;
312 if (flag_random_seed)
314 char *endp;
316 /* When the driver passed in a hex number don't crc it again */
317 random_seed = strtoul (flag_random_seed, &endp, 0);
318 if (!(endp > flag_random_seed && *endp == 0))
319 random_seed = crc32_string (0, flag_random_seed);
321 return old;
324 /* Handler for fatal signals, such as SIGSEGV. These are transformed
325 into ICE messages, which is much more user friendly. In case the
326 error printer crashes, reset the signal to prevent infinite recursion. */
328 static void
329 crash_signal (int signo)
331 signal (signo, SIG_DFL);
333 /* If we crashed while processing an ASM statement, then be a little more
334 graceful. It's most likely the user's fault. */
335 if (this_is_asm_operands)
337 output_operand_lossage ("unrecoverable error");
338 exit (FATAL_EXIT_CODE);
341 internal_error ("%s", strsignal (signo));
344 /* A subroutine of wrapup_global_declarations. We've come to the end of
345 the compilation unit. All deferred variables should be undeferred,
346 and all incomplete decls should be finalized. */
348 void
349 wrapup_global_declaration_1 (tree decl)
351 /* We're not deferring this any longer. Assignment is conditional to
352 avoid needlessly dirtying PCH pages. */
353 if (CODE_CONTAINS_STRUCT (TREE_CODE (decl), TS_DECL_WITH_VIS)
354 && DECL_DEFER_OUTPUT (decl) != 0)
355 DECL_DEFER_OUTPUT (decl) = 0;
357 if (VAR_P (decl) && DECL_SIZE (decl) == 0)
358 lang_hooks.finish_incomplete_decl (decl);
361 /* A subroutine of wrapup_global_declarations. Decide whether or not DECL
362 needs to be output. Return true if it is output. */
364 bool
365 wrapup_global_declaration_2 (tree decl)
367 if (TREE_ASM_WRITTEN (decl) || DECL_EXTERNAL (decl)
368 || (VAR_P (decl) && DECL_HAS_VALUE_EXPR_P (decl)))
369 return false;
371 /* Don't write out static consts, unless we still need them.
373 We also keep static consts if not optimizing (for debugging),
374 unless the user specified -fno-keep-static-consts.
375 ??? They might be better written into the debug information.
376 This is possible when using DWARF.
378 A language processor that wants static constants to be always
379 written out (even if it is not used) is responsible for
380 calling rest_of_decl_compilation itself. E.g. the C front-end
381 calls rest_of_decl_compilation from finish_decl.
382 One motivation for this is that is conventional in some
383 environments to write things like:
384 static const char rcsid[] = "... version string ...";
385 intending to force the string to be in the executable.
387 A language processor that would prefer to have unneeded
388 static constants "optimized away" would just defer writing
389 them out until here. E.g. C++ does this, because static
390 constants are often defined in header files.
392 ??? A tempting alternative (for both C and C++) would be
393 to force a constant to be written if and only if it is
394 defined in a main file, as opposed to an include file. */
396 if (VAR_P (decl) && TREE_STATIC (decl))
398 varpool_node *node;
399 bool needed = true;
400 node = varpool_node::get (decl);
402 if (!node && flag_ltrans)
403 needed = false;
404 else if (node && node->definition)
405 needed = false;
406 else if (node && node->alias)
407 needed = false;
408 else if (!symtab->global_info_ready
409 && (TREE_USED (decl)
410 || TREE_USED (DECL_ASSEMBLER_NAME (decl))))
411 /* needed */;
412 else if (node && node->analyzed)
413 /* needed */;
414 else if (DECL_COMDAT (decl))
415 needed = false;
416 else if (TREE_READONLY (decl) && !TREE_PUBLIC (decl)
417 && (optimize || !flag_keep_static_consts
418 || DECL_ARTIFICIAL (decl)))
419 needed = false;
421 if (needed)
423 rest_of_decl_compilation (decl, 1, 1);
424 return true;
428 return false;
431 /* Do any final processing required for the declarations in VEC, of
432 which there are LEN. We write out inline functions and variables
433 that have been deferred until this point, but which are required.
434 Returns nonzero if anything was put out. */
436 bool
437 wrapup_global_declarations (tree *vec, int len)
439 bool reconsider, output_something = false;
440 int i;
442 for (i = 0; i < len; i++)
443 wrapup_global_declaration_1 (vec[i]);
445 /* Now emit any global variables or functions that we have been
446 putting off. We need to loop in case one of the things emitted
447 here references another one which comes earlier in the list. */
450 reconsider = false;
451 for (i = 0; i < len; i++)
452 reconsider |= wrapup_global_declaration_2 (vec[i]);
453 if (reconsider)
454 output_something = true;
456 while (reconsider);
458 return output_something;
461 /* Compile an entire translation unit. Write a file of assembly
462 output and various debugging dumps. */
464 static void
465 compile_file (void)
467 timevar_start (TV_PHASE_PARSING);
468 timevar_push (TV_PARSE_GLOBAL);
470 /* Parse entire file and generate initial debug information. */
471 lang_hooks.parse_file ();
473 timevar_pop (TV_PARSE_GLOBAL);
474 timevar_stop (TV_PHASE_PARSING);
476 if (flag_dump_locations)
477 dump_location_info (stderr);
479 /* Compilation is now finished except for writing
480 what's left of the symbol table output. */
482 if (flag_syntax_only || flag_wpa)
483 return;
485 /* Reset maximum_field_alignment, it can be adjusted by #pragma pack
486 and this shouldn't influence any types built by the middle-end
487 from now on (like gcov_info_type). */
488 maximum_field_alignment = initial_max_fld_align * BITS_PER_UNIT;
490 ggc_protect_identifiers = false;
492 /* Run the actual compilation process. */
493 if (!in_lto_p)
495 timevar_start (TV_PHASE_OPT_GEN);
496 symtab->finalize_compilation_unit ();
497 timevar_stop (TV_PHASE_OPT_GEN);
500 /* Perform any post compilation-proper parser cleanups and
501 processing. This is currently only needed for the C++ parser,
502 which can be hopefully cleaned up so this hook is no longer
503 necessary. */
504 if (lang_hooks.decls.post_compilation_parsing_cleanups)
505 lang_hooks.decls.post_compilation_parsing_cleanups ();
507 if (seen_error ())
508 return;
510 timevar_start (TV_PHASE_LATE_ASM);
512 /* Compilation unit is finalized. When producing non-fat LTO object, we are
513 basically finished. */
514 if (in_lto_p || !flag_lto || flag_fat_lto_objects)
516 /* File-scope initialization for AddressSanitizer. */
517 if (flag_sanitize & SANITIZE_ADDRESS)
518 asan_finish_file ();
520 if (flag_sanitize & SANITIZE_THREAD)
521 tsan_finish_file ();
523 if (flag_check_pointer_bounds)
524 chkp_finish_file ();
526 omp_finish_file ();
528 hsa_output_brig ();
530 output_shared_constant_pool ();
531 output_object_blocks ();
532 finish_tm_clone_pairs ();
534 /* Write out any pending weak symbol declarations. */
535 weak_finish ();
537 /* This must be at the end before unwind and debug info.
538 Some target ports emit PIC setup thunks here. */
539 targetm.asm_out.code_end ();
541 /* Do dbx symbols. */
542 timevar_push (TV_SYMOUT);
544 #if defined DWARF2_DEBUGGING_INFO || defined DWARF2_UNWIND_INFO
545 if (dwarf2out_do_frame ())
546 dwarf2out_frame_finish ();
547 #endif
549 (*debug_hooks->finish) (main_input_filename);
550 timevar_pop (TV_SYMOUT);
552 /* Output some stuff at end of file if nec. */
554 dw2_output_indirect_constants ();
556 /* Flush any pending external directives. */
557 process_pending_assemble_externals ();
560 /* Emit LTO marker if LTO info has been previously emitted. This is
561 used by collect2 to determine whether an object file contains IL.
562 We used to emit an undefined reference here, but this produces
563 link errors if an object file with IL is stored into a shared
564 library without invoking lto1. */
565 if (flag_generate_lto || flag_generate_offload)
567 #if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
568 ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE,
569 "__gnu_lto_v1",
570 HOST_WIDE_INT_1U, 8);
571 #elif defined ASM_OUTPUT_ALIGNED_COMMON
572 ASM_OUTPUT_ALIGNED_COMMON (asm_out_file, "__gnu_lto_v1",
573 HOST_WIDE_INT_1U, 8);
574 #else
575 ASM_OUTPUT_COMMON (asm_out_file, "__gnu_lto_v1",
576 HOST_WIDE_INT_1U,
577 HOST_WIDE_INT_1U);
578 #endif
581 /* Let linker plugin know that this is a slim object and must be LTOed
582 even when user did not ask for it. */
583 if (flag_generate_lto && !flag_fat_lto_objects)
585 #if defined ASM_OUTPUT_ALIGNED_DECL_COMMON
586 ASM_OUTPUT_ALIGNED_DECL_COMMON (asm_out_file, NULL_TREE, "__gnu_lto_slim",
587 HOST_WIDE_INT_1U, 8);
588 #elif defined ASM_OUTPUT_ALIGNED_COMMON
589 ASM_OUTPUT_ALIGNED_COMMON (asm_out_file, "__gnu_lto_slim",
590 HOST_WIDE_INT_1U, 8);
591 #else
592 ASM_OUTPUT_COMMON (asm_out_file, "__gnu_lto_slim",
593 HOST_WIDE_INT_1U,
594 HOST_WIDE_INT_1U);
595 #endif
598 /* Attach a special .ident directive to the end of the file to identify
599 the version of GCC which compiled this code. The format of the .ident
600 string is patterned after the ones produced by native SVR4 compilers. */
601 if (!flag_no_ident)
603 const char *pkg_version = "(GNU) ";
604 char *ident_str;
606 if (strcmp ("(GCC) ", pkgversion_string))
607 pkg_version = pkgversion_string;
609 ident_str = ACONCAT (("GCC: ", pkg_version, version_string, NULL));
610 targetm.asm_out.output_ident (ident_str);
613 /* Auto profile finalization. */
614 if (flag_auto_profile)
615 end_auto_profile ();
617 /* Invoke registered plugin callbacks. */
618 invoke_plugin_callbacks (PLUGIN_FINISH_UNIT, NULL);
620 /* This must be at the end. Some target ports emit end of file directives
621 into the assembly file here, and hence we can not output anything to the
622 assembly file after this point. */
623 targetm.asm_out.file_end ();
625 timevar_stop (TV_PHASE_LATE_ASM);
628 /* Print version information to FILE.
629 Each line begins with INDENT (for the case where FILE is the
630 assembler output file).
632 If SHOW_GLOBAL_STATE is true (for cc1 etc), we are within the compiler
633 proper and can print pertinent state (e.g. params and plugins).
635 If SHOW_GLOBAL_STATE is false (for use by libgccjit), we are outside the
636 compiler, and we don't hold the mutex on the compiler's global state:
637 we can't print params and plugins, since they might not be initialized,
638 or might be being manipulated by a compile running in another
639 thread. */
641 void
642 print_version (FILE *file, const char *indent, bool show_global_state)
644 static const char fmt1[] =
645 #ifdef __GNUC__
646 N_("%s%s%s %sversion %s (%s)\n%s\tcompiled by GNU C version %s, ")
647 #else
648 N_("%s%s%s %sversion %s (%s) compiled by CC, ")
649 #endif
651 static const char fmt2[] =
652 N_("GMP version %s, MPFR version %s, MPC version %s, isl version %s\n");
653 static const char fmt3[] =
654 N_("%s%swarning: %s header version %s differs from library version %s.\n");
655 static const char fmt4[] =
656 N_("%s%sGGC heuristics: --param ggc-min-expand=%d --param ggc-min-heapsize=%d\n");
657 #ifndef __VERSION__
658 #define __VERSION__ "[?]"
659 #endif
660 fprintf (file,
661 file == stderr ? _(fmt1) : fmt1,
662 indent, *indent != 0 ? " " : "",
663 lang_hooks.name, pkgversion_string, version_string, TARGET_NAME,
664 indent, __VERSION__);
666 /* We need to stringify the GMP macro values. Ugh, gmp_version has
667 two string formats, "i.j.k" and "i.j" when k is zero. As of
668 gmp-4.3.0, GMP always uses the 3 number format. */
669 #define GCC_GMP_STRINGIFY_VERSION3(X) #X
670 #define GCC_GMP_STRINGIFY_VERSION2(X) GCC_GMP_STRINGIFY_VERSION3 (X)
671 #define GCC_GMP_VERSION_NUM(X,Y,Z) (((X) << 16L) | ((Y) << 8) | (Z))
672 #define GCC_GMP_VERSION \
673 GCC_GMP_VERSION_NUM(__GNU_MP_VERSION, __GNU_MP_VERSION_MINOR, __GNU_MP_VERSION_PATCHLEVEL)
674 #if GCC_GMP_VERSION < GCC_GMP_VERSION_NUM(4,3,0) && __GNU_MP_VERSION_PATCHLEVEL == 0
675 #define GCC_GMP_STRINGIFY_VERSION \
676 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION) "." \
677 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION_MINOR)
678 #else
679 #define GCC_GMP_STRINGIFY_VERSION \
680 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION) "." \
681 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION_MINOR) "." \
682 GCC_GMP_STRINGIFY_VERSION2 (__GNU_MP_VERSION_PATCHLEVEL)
683 #endif
684 fprintf (file,
685 file == stderr ? _(fmt2) : fmt2,
686 GCC_GMP_STRINGIFY_VERSION, MPFR_VERSION_STRING, MPC_VERSION_STRING,
687 #ifndef HAVE_isl
688 "none"
689 #else
690 isl_version ()
691 #endif
693 if (strcmp (GCC_GMP_STRINGIFY_VERSION, gmp_version))
694 fprintf (file,
695 file == stderr ? _(fmt3) : fmt3,
696 indent, *indent != 0 ? " " : "",
697 "GMP", GCC_GMP_STRINGIFY_VERSION, gmp_version);
698 if (strcmp (MPFR_VERSION_STRING, mpfr_get_version ()))
699 fprintf (file,
700 file == stderr ? _(fmt3) : fmt3,
701 indent, *indent != 0 ? " " : "",
702 "MPFR", MPFR_VERSION_STRING, mpfr_get_version ());
703 if (strcmp (MPC_VERSION_STRING, mpc_get_version ()))
704 fprintf (file,
705 file == stderr ? _(fmt3) : fmt3,
706 indent, *indent != 0 ? " " : "",
707 "MPC", MPC_VERSION_STRING, mpc_get_version ());
709 if (show_global_state)
711 fprintf (file,
712 file == stderr ? _(fmt4) : fmt4,
713 indent, *indent != 0 ? " " : "",
714 PARAM_VALUE (GGC_MIN_EXPAND), PARAM_VALUE (GGC_MIN_HEAPSIZE));
716 print_plugins_versions (file, indent);
720 static int
721 print_to_asm_out_file (print_switch_type type, const char * text)
723 bool prepend_sep = true;
725 switch (type)
727 case SWITCH_TYPE_LINE_END:
728 putc ('\n', asm_out_file);
729 return 1;
731 case SWITCH_TYPE_LINE_START:
732 fputs (ASM_COMMENT_START, asm_out_file);
733 return strlen (ASM_COMMENT_START);
735 case SWITCH_TYPE_DESCRIPTIVE:
736 if (ASM_COMMENT_START[0] == 0)
737 prepend_sep = false;
738 /* FALLTHRU */
739 case SWITCH_TYPE_PASSED:
740 case SWITCH_TYPE_ENABLED:
741 if (prepend_sep)
742 fputc (' ', asm_out_file);
743 fputs (text, asm_out_file);
744 /* No need to return the length here as
745 print_single_switch has already done it. */
746 return 0;
748 default:
749 return -1;
753 static int
754 print_to_stderr (print_switch_type type, const char * text)
756 switch (type)
758 case SWITCH_TYPE_LINE_END:
759 putc ('\n', stderr);
760 return 1;
762 case SWITCH_TYPE_LINE_START:
763 return 0;
765 case SWITCH_TYPE_PASSED:
766 case SWITCH_TYPE_ENABLED:
767 fputc (' ', stderr);
768 /* FALLTHRU */
770 case SWITCH_TYPE_DESCRIPTIVE:
771 fputs (text, stderr);
772 /* No need to return the length here as
773 print_single_switch has already done it. */
774 return 0;
776 default:
777 return -1;
781 /* Print an option value and return the adjusted position in the line.
782 ??? print_fn doesn't handle errors, eg disk full; presumably other
783 code will catch a disk full though. */
785 static int
786 print_single_switch (print_switch_fn_type print_fn,
787 int pos,
788 print_switch_type type,
789 const char * text)
791 /* The ultrix fprintf returns 0 on success, so compute the result
792 we want here since we need it for the following test. The +1
793 is for the separator character that will probably be emitted. */
794 int len = strlen (text) + 1;
796 if (pos != 0
797 && pos + len > MAX_LINE)
799 print_fn (SWITCH_TYPE_LINE_END, NULL);
800 pos = 0;
803 if (pos == 0)
804 pos += print_fn (SWITCH_TYPE_LINE_START, NULL);
806 print_fn (type, text);
807 return pos + len;
810 /* Print active target switches using PRINT_FN.
811 POS is the current cursor position and MAX is the size of a "line".
812 Each line begins with INDENT and ends with TERM.
813 Each switch is separated from the next by SEP. */
815 static void
816 print_switch_values (print_switch_fn_type print_fn)
818 int pos = 0;
819 size_t j;
821 /* Fill in the -frandom-seed option, if the user didn't pass it, so
822 that it can be printed below. This helps reproducibility. */
823 if (!flag_random_seed)
824 init_random_seed ();
826 /* Print the options as passed. */
827 pos = print_single_switch (print_fn, pos,
828 SWITCH_TYPE_DESCRIPTIVE, _("options passed: "));
830 for (j = 1; j < save_decoded_options_count; j++)
832 switch (save_decoded_options[j].opt_index)
834 case OPT_o:
835 case OPT_d:
836 case OPT_dumpbase:
837 case OPT_dumpdir:
838 case OPT_auxbase:
839 case OPT_quiet:
840 case OPT_version:
841 /* Ignore these. */
842 continue;
845 pos = print_single_switch (print_fn, pos, SWITCH_TYPE_PASSED,
846 save_decoded_options[j].orig_option_with_args_text);
849 if (pos > 0)
850 print_fn (SWITCH_TYPE_LINE_END, NULL);
852 /* Print the -f and -m options that have been enabled.
853 We don't handle language specific options but printing argv
854 should suffice. */
855 pos = print_single_switch (print_fn, 0,
856 SWITCH_TYPE_DESCRIPTIVE, _("options enabled: "));
858 for (j = 0; j < cl_options_count; j++)
859 if (cl_options[j].cl_report
860 && option_enabled (j, &global_options) > 0)
861 pos = print_single_switch (print_fn, pos,
862 SWITCH_TYPE_ENABLED, cl_options[j].opt_text);
864 print_fn (SWITCH_TYPE_LINE_END, NULL);
867 /* Open assembly code output file. Do this even if -fsyntax-only is
868 on, because then the driver will have provided the name of a
869 temporary file or bit bucket for us. NAME is the file specified on
870 the command line, possibly NULL. */
871 static void
872 init_asm_output (const char *name)
874 if (name == NULL && asm_file_name == 0)
875 asm_out_file = stdout;
876 else
878 if (asm_file_name == 0)
880 int len = strlen (dump_base_name);
881 char *dumpname = XNEWVEC (char, len + 6);
883 memcpy (dumpname, dump_base_name, len + 1);
884 strip_off_ending (dumpname, len);
885 strcat (dumpname, ".s");
886 asm_file_name = dumpname;
888 if (!strcmp (asm_file_name, "-"))
889 asm_out_file = stdout;
890 else if (!canonical_filename_eq (asm_file_name, name)
891 || !strcmp (asm_file_name, HOST_BIT_BUCKET))
892 asm_out_file = fopen (asm_file_name, "w");
893 else
894 /* Use UNKOWN_LOCATION to prevent gcc from printing the first
895 line in the current file. */
896 fatal_error (UNKNOWN_LOCATION,
897 "input file %qs is the same as output file",
898 asm_file_name);
899 if (asm_out_file == 0)
900 fatal_error (UNKNOWN_LOCATION,
901 "can%'t open %qs for writing: %m", asm_file_name);
904 if (!flag_syntax_only)
906 targetm.asm_out.file_start ();
908 if (flag_record_gcc_switches)
910 if (targetm.asm_out.record_gcc_switches)
912 /* Let the target know that we are about to start recording. */
913 targetm.asm_out.record_gcc_switches (SWITCH_TYPE_DESCRIPTIVE,
914 NULL);
915 /* Now record the switches. */
916 print_switch_values (targetm.asm_out.record_gcc_switches);
917 /* Let the target know that the recording is over. */
918 targetm.asm_out.record_gcc_switches (SWITCH_TYPE_DESCRIPTIVE,
919 NULL);
921 else
922 inform (UNKNOWN_LOCATION,
923 "-frecord-gcc-switches is not supported by "
924 "the current target");
927 if (flag_verbose_asm)
929 /* Print the list of switches in effect
930 into the assembler file as comments. */
931 print_version (asm_out_file, ASM_COMMENT_START, true);
932 print_switch_values (print_to_asm_out_file);
933 putc ('\n', asm_out_file);
938 /* A helper function; used as the reallocator function for cpp's line
939 table. */
940 static void *
941 realloc_for_line_map (void *ptr, size_t len)
943 return ggc_realloc (ptr, len);
946 /* A helper function: used as the allocator function for
947 identifier_to_locale. */
948 static void *
949 alloc_for_identifier_to_locale (size_t len)
951 return ggc_alloc_atomic (len);
954 /* Output stack usage information. */
955 void
956 output_stack_usage (void)
958 static bool warning_issued = false;
959 enum stack_usage_kind_type { STATIC = 0, DYNAMIC, DYNAMIC_BOUNDED };
960 const char *stack_usage_kind_str[] = {
961 "static",
962 "dynamic",
963 "dynamic,bounded"
965 HOST_WIDE_INT stack_usage = current_function_static_stack_size;
966 enum stack_usage_kind_type stack_usage_kind;
968 if (stack_usage < 0)
970 if (!warning_issued)
972 warning (0, "stack usage computation not supported for this target");
973 warning_issued = true;
975 return;
978 stack_usage_kind = STATIC;
980 /* Add the maximum amount of space pushed onto the stack. */
981 if (current_function_pushed_stack_size > 0)
983 stack_usage += current_function_pushed_stack_size;
984 stack_usage_kind = DYNAMIC_BOUNDED;
987 /* Now on to the tricky part: dynamic stack allocation. */
988 if (current_function_allocates_dynamic_stack_space)
990 if (current_function_has_unbounded_dynamic_stack_size)
991 stack_usage_kind = DYNAMIC;
992 else
993 stack_usage_kind = DYNAMIC_BOUNDED;
995 /* Add the size even in the unbounded case, this can't hurt. */
996 stack_usage += current_function_dynamic_stack_size;
999 if (flag_stack_usage)
1001 expanded_location loc
1002 = expand_location (DECL_SOURCE_LOCATION (current_function_decl));
1003 /* We don't want to print the full qualified name because it can be long,
1004 so we strip the scope prefix, but we may need to deal with the suffix
1005 created by the compiler. */
1006 const char *suffix
1007 = strchr (IDENTIFIER_POINTER (DECL_NAME (current_function_decl)), '.');
1008 const char *name
1009 = lang_hooks.decl_printable_name (current_function_decl, 2);
1010 if (suffix)
1012 const char *dot = strchr (name, '.');
1013 while (dot && strcasecmp (dot, suffix) != 0)
1015 name = dot + 1;
1016 dot = strchr (name, '.');
1019 else
1021 const char *dot = strrchr (name, '.');
1022 if (dot)
1023 name = dot + 1;
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 name,
1032 stack_usage,
1033 stack_usage_kind_str[stack_usage_kind]);
1036 if (warn_stack_usage >= 0)
1038 const location_t loc = DECL_SOURCE_LOCATION (current_function_decl);
1040 if (stack_usage_kind == DYNAMIC)
1041 warning_at (loc, OPT_Wstack_usage_, "stack usage might be unbounded");
1042 else if (stack_usage > warn_stack_usage)
1044 if (stack_usage_kind == DYNAMIC_BOUNDED)
1045 warning_at (loc,
1046 OPT_Wstack_usage_, "stack usage might be %wd bytes",
1047 stack_usage);
1048 else
1049 warning_at (loc, OPT_Wstack_usage_, "stack usage is %wd bytes",
1050 stack_usage);
1055 /* Open an auxiliary output file. */
1056 static FILE *
1057 open_auxiliary_file (const char *ext)
1059 char *filename;
1060 FILE *file;
1062 filename = concat (aux_base_name, ".", ext, NULL);
1063 file = fopen (filename, "w");
1064 if (!file)
1065 fatal_error (input_location, "can%'t open %s for writing: %m", filename);
1066 free (filename);
1067 return file;
1070 /* Alternative diagnostics callback for reentered ICE reporting. */
1072 static void
1073 internal_error_reentered (diagnostic_context *, const char *, va_list *)
1075 /* Flush the dump file if emergency_dump_function itself caused an ICE. */
1076 if (dump_file)
1077 fflush (dump_file);
1080 /* Auxiliary callback for the diagnostics code. */
1082 static void
1083 internal_error_function (diagnostic_context *, const char *, va_list *)
1085 global_dc->internal_error = internal_error_reentered;
1086 warn_if_plugins ();
1087 emergency_dump_function ();
1090 /* Initialization of the front end environment, before command line
1091 options are parsed. Signal handlers, internationalization etc.
1092 ARGV0 is main's argv[0]. */
1093 static void
1094 general_init (const char *argv0, bool init_signals)
1096 const char *p;
1098 p = argv0 + strlen (argv0);
1099 while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
1100 --p;
1101 progname = p;
1103 xmalloc_set_program_name (progname);
1105 hex_init ();
1107 /* Unlock the stdio streams. */
1108 unlock_std_streams ();
1110 gcc_init_libintl ();
1112 identifier_to_locale_alloc = alloc_for_identifier_to_locale;
1113 identifier_to_locale_free = ggc_free;
1115 /* Initialize the diagnostics reporting machinery, so option parsing
1116 can give warnings and errors. */
1117 diagnostic_initialize (global_dc, N_OPTS);
1118 /* Set a default printer. Language specific initializations will
1119 override it later. */
1120 tree_diagnostics_defaults (global_dc);
1122 global_dc->show_caret
1123 = global_options_init.x_flag_diagnostics_show_caret;
1124 global_dc->show_option_requested
1125 = global_options_init.x_flag_diagnostics_show_option;
1126 global_dc->show_column
1127 = global_options_init.x_flag_show_column;
1128 global_dc->internal_error = internal_error_function;
1129 global_dc->option_enabled = option_enabled;
1130 global_dc->option_state = &global_options;
1131 global_dc->option_name = option_name;
1133 if (init_signals)
1135 /* Trap fatal signals, e.g. SIGSEGV, and convert them to ICE messages. */
1136 #ifdef SIGSEGV
1137 signal (SIGSEGV, crash_signal);
1138 #endif
1139 #ifdef SIGILL
1140 signal (SIGILL, crash_signal);
1141 #endif
1142 #ifdef SIGBUS
1143 signal (SIGBUS, crash_signal);
1144 #endif
1145 #ifdef SIGABRT
1146 signal (SIGABRT, crash_signal);
1147 #endif
1148 #if defined SIGIOT && (!defined SIGABRT || SIGABRT != SIGIOT)
1149 signal (SIGIOT, crash_signal);
1150 #endif
1151 #ifdef SIGFPE
1152 signal (SIGFPE, crash_signal);
1153 #endif
1155 /* Other host-specific signal setup. */
1156 (*host_hooks.extra_signals)();
1159 /* Initialize the garbage-collector, string pools and tree type hash
1160 table. */
1161 init_ggc ();
1162 init_stringpool ();
1163 input_location = UNKNOWN_LOCATION;
1164 line_table = ggc_alloc<line_maps> ();
1165 linemap_init (line_table, BUILTINS_LOCATION);
1166 line_table->reallocator = realloc_for_line_map;
1167 line_table->round_alloc_size = ggc_round_alloc_size;
1168 line_table->default_range_bits = 5;
1169 init_ttree ();
1171 /* Initialize register usage now so switches may override. */
1172 init_reg_sets ();
1174 /* Register the language-independent parameters. */
1175 global_init_params ();
1177 /* This must be done after global_init_params but before argument
1178 processing. */
1179 init_ggc_heuristics ();
1181 /* Create the singleton holder for global state. This creates the
1182 dump manager. */
1183 g = new gcc::context ();
1185 /* Allow languages and middle-end to register their dumps before the
1186 optimization passes. */
1187 g->get_dumps ()->register_dumps ();
1189 /* Create the passes. */
1190 g->set_passes (new gcc::pass_manager (g));
1192 symtab = new (ggc_cleared_alloc <symbol_table> ()) symbol_table ();
1194 statistics_early_init ();
1195 finish_params ();
1198 /* Return true if the current target supports -fsection-anchors. */
1200 static bool
1201 target_supports_section_anchors_p (void)
1203 if (targetm.min_anchor_offset == 0 && targetm.max_anchor_offset == 0)
1204 return false;
1206 if (targetm.asm_out.output_anchor == NULL)
1207 return false;
1209 return true;
1212 /* Default the align_* variables to 1 if they're still unset, and
1213 set up the align_*_log variables. */
1214 static void
1215 init_alignments (void)
1217 if (align_loops <= 0)
1218 align_loops = 1;
1219 if (align_loops_max_skip > align_loops)
1220 align_loops_max_skip = align_loops - 1;
1221 align_loops_log = floor_log2 (align_loops * 2 - 1);
1222 if (align_jumps <= 0)
1223 align_jumps = 1;
1224 if (align_jumps_max_skip > align_jumps)
1225 align_jumps_max_skip = align_jumps - 1;
1226 align_jumps_log = floor_log2 (align_jumps * 2 - 1);
1227 if (align_labels <= 0)
1228 align_labels = 1;
1229 align_labels_log = floor_log2 (align_labels * 2 - 1);
1230 if (align_labels_max_skip > align_labels)
1231 align_labels_max_skip = align_labels - 1;
1232 if (align_functions <= 0)
1233 align_functions = 1;
1234 align_functions_log = floor_log2 (align_functions * 2 - 1);
1237 /* Process the options that have been parsed. */
1238 static void
1239 process_options (void)
1241 /* Just in case lang_hooks.post_options ends up calling a debug_hook.
1242 This can happen with incorrect pre-processed input. */
1243 debug_hooks = &do_nothing_debug_hooks;
1245 maximum_field_alignment = initial_max_fld_align * BITS_PER_UNIT;
1247 /* Allow the front end to perform consistency checks and do further
1248 initialization based on the command line options. This hook also
1249 sets the original filename if appropriate (e.g. foo.i -> foo.c)
1250 so we can correctly initialize debug output. */
1251 no_backend = lang_hooks.post_options (&main_input_filename);
1253 /* Some machines may reject certain combinations of options. */
1254 location_t saved_location = input_location;
1255 input_location = UNKNOWN_LOCATION;
1256 targetm.target_option.override ();
1257 input_location = saved_location;
1259 if (flag_diagnostics_generate_patch)
1260 global_dc->edit_context_ptr = new edit_context ();
1262 /* Avoid any informative notes in the second run of -fcompare-debug. */
1263 if (flag_compare_debug)
1264 diagnostic_inhibit_notes (global_dc);
1266 if (flag_section_anchors && !target_supports_section_anchors_p ())
1268 warning_at (UNKNOWN_LOCATION, OPT_fsection_anchors,
1269 "this target does not support %qs",
1270 "-fsection-anchors");
1271 flag_section_anchors = 0;
1274 if (flag_short_enums == 2)
1275 flag_short_enums = targetm.default_short_enums ();
1277 /* Set aux_base_name if not already set. */
1278 if (aux_base_name)
1280 else if (main_input_filename)
1282 char *name = xstrdup (lbasename (main_input_filename));
1284 strip_off_ending (name, strlen (name));
1285 aux_base_name = name;
1287 else
1288 aux_base_name = "gccaux";
1290 #ifndef HAVE_isl
1291 if (flag_graphite
1292 || flag_loop_nest_optimize
1293 || flag_graphite_identity
1294 || flag_loop_parallelize_all)
1295 sorry ("Graphite loop optimizations cannot be used (isl is not available) "
1296 "(-fgraphite, -fgraphite-identity, -floop-nest-optimize, "
1297 "-floop-parallelize-all)");
1298 #endif
1300 if (flag_check_pointer_bounds)
1302 if (targetm.chkp_bound_mode () == VOIDmode)
1304 error_at (UNKNOWN_LOCATION,
1305 "%<-fcheck-pointer-bounds%> is not supported for this "
1306 "target");
1307 flag_check_pointer_bounds = 0;
1310 if (flag_sanitize & SANITIZE_BOUNDS_STRICT)
1312 error_at (UNKNOWN_LOCATION,
1313 "%<-fcheck-pointer-bounds%> is not supported with "
1314 "%<-fsanitize=bounds-strict%>");
1315 flag_check_pointer_bounds = 0;
1317 else if (flag_sanitize & SANITIZE_BOUNDS)
1319 error_at (UNKNOWN_LOCATION,
1320 "%<-fcheck-pointer-bounds%> is not supported with "
1321 "%<-fsanitize=bounds%>");
1322 flag_check_pointer_bounds = 0;
1325 if (flag_sanitize & SANITIZE_ADDRESS)
1327 error_at (UNKNOWN_LOCATION,
1328 "%<-fcheck-pointer-bounds%> is not supported with "
1329 "Address Sanitizer");
1330 flag_check_pointer_bounds = 0;
1333 if (flag_sanitize & SANITIZE_THREAD)
1335 error_at (UNKNOWN_LOCATION,
1336 "%<-fcheck-pointer-bounds%> is not supported with "
1337 "Thread Sanitizer");
1339 flag_check_pointer_bounds = 0;
1343 /* One region RA really helps to decrease the code size. */
1344 if (flag_ira_region == IRA_REGION_AUTODETECT)
1345 flag_ira_region
1346 = optimize_size || !optimize ? IRA_REGION_ONE : IRA_REGION_MIXED;
1348 if (!abi_version_at_least (2))
1350 /* -fabi-version=1 support was removed after GCC 4.9. */
1351 error_at (UNKNOWN_LOCATION,
1352 "%<-fabi-version=1%> is no longer supported");
1353 flag_abi_version = 2;
1356 /* Unrolling all loops implies that standard loop unrolling must also
1357 be done. */
1358 if (flag_unroll_all_loops)
1359 flag_unroll_loops = 1;
1361 /* web and rename-registers help when run after loop unrolling. */
1362 if (flag_web == AUTODETECT_VALUE)
1363 flag_web = flag_unroll_loops;
1365 if (flag_rename_registers == AUTODETECT_VALUE)
1366 flag_rename_registers = flag_unroll_loops;
1368 if (flag_non_call_exceptions)
1369 flag_asynchronous_unwind_tables = 1;
1370 if (flag_asynchronous_unwind_tables)
1371 flag_unwind_tables = 1;
1373 if (flag_value_profile_transformations)
1374 flag_profile_values = 1;
1376 /* Warn about options that are not supported on this machine. */
1377 #ifndef INSN_SCHEDULING
1378 if (flag_schedule_insns || flag_schedule_insns_after_reload)
1379 warning_at (UNKNOWN_LOCATION, 0,
1380 "instruction scheduling not supported on this target machine");
1381 #endif
1382 if (!DELAY_SLOTS && flag_delayed_branch)
1383 warning_at (UNKNOWN_LOCATION, 0,
1384 "this target machine does not have delayed branches");
1386 user_label_prefix = USER_LABEL_PREFIX;
1387 if (flag_leading_underscore != -1)
1389 /* If the default prefix is more complicated than "" or "_",
1390 issue a warning and ignore this option. */
1391 if (user_label_prefix[0] == 0 ||
1392 (user_label_prefix[0] == '_' && user_label_prefix[1] == 0))
1394 user_label_prefix = flag_leading_underscore ? "_" : "";
1396 else
1397 warning_at (UNKNOWN_LOCATION, 0,
1398 "-f%sleading-underscore not supported on this "
1399 "target machine", flag_leading_underscore ? "" : "no-");
1402 /* If we are in verbose mode, write out the version and maybe all the
1403 option flags in use. */
1404 if (version_flag)
1406 print_version (stderr, "", true);
1407 if (! quiet_flag)
1408 print_switch_values (print_to_stderr);
1411 if (flag_syntax_only)
1413 write_symbols = NO_DEBUG;
1414 profile_flag = 0;
1417 if (flag_gtoggle)
1419 if (debug_info_level == DINFO_LEVEL_NONE)
1421 debug_info_level = DINFO_LEVEL_NORMAL;
1423 if (write_symbols == NO_DEBUG)
1424 write_symbols = PREFERRED_DEBUGGING_TYPE;
1426 else
1427 debug_info_level = DINFO_LEVEL_NONE;
1430 if (flag_dump_final_insns && !flag_syntax_only && !no_backend)
1432 FILE *final_output = fopen (flag_dump_final_insns, "w");
1433 if (!final_output)
1435 error_at (UNKNOWN_LOCATION,
1436 "could not open final insn dump file %qs: %m",
1437 flag_dump_final_insns);
1438 flag_dump_final_insns = NULL;
1440 else if (fclose (final_output))
1442 error_at (UNKNOWN_LOCATION,
1443 "could not close zeroed insn dump file %qs: %m",
1444 flag_dump_final_insns);
1445 flag_dump_final_insns = NULL;
1449 /* A lot of code assumes write_symbols == NO_DEBUG if the debugging
1450 level is 0. */
1451 if (debug_info_level == DINFO_LEVEL_NONE)
1452 write_symbols = NO_DEBUG;
1454 if (write_symbols == NO_DEBUG)
1456 #if defined(DBX_DEBUGGING_INFO)
1457 else if (write_symbols == DBX_DEBUG)
1458 debug_hooks = &dbx_debug_hooks;
1459 #endif
1460 #if defined(XCOFF_DEBUGGING_INFO)
1461 else if (write_symbols == XCOFF_DEBUG)
1462 debug_hooks = &xcoff_debug_hooks;
1463 #endif
1464 else if (SDB_DEBUGGING_INFO && write_symbols == SDB_DEBUG)
1465 debug_hooks = &sdb_debug_hooks;
1466 #ifdef DWARF2_DEBUGGING_INFO
1467 else if (write_symbols == DWARF2_DEBUG)
1468 debug_hooks = &dwarf2_debug_hooks;
1469 #endif
1470 #ifdef VMS_DEBUGGING_INFO
1471 else if (write_symbols == VMS_DEBUG || write_symbols == VMS_AND_DWARF2_DEBUG)
1472 debug_hooks = &vmsdbg_debug_hooks;
1473 #endif
1474 #ifdef DWARF2_LINENO_DEBUGGING_INFO
1475 else if (write_symbols == DWARF2_DEBUG)
1476 debug_hooks = &dwarf2_lineno_debug_hooks;
1477 #endif
1478 else
1479 error_at (UNKNOWN_LOCATION,
1480 "target system does not support the %qs debug format",
1481 debug_type_names[write_symbols]);
1483 /* We know which debug output will be used so we can set flag_var_tracking
1484 and flag_var_tracking_uninit if the user has not specified them. */
1485 if (debug_info_level < DINFO_LEVEL_NORMAL
1486 || debug_hooks->var_location == do_nothing_debug_hooks.var_location)
1488 if (flag_var_tracking == 1
1489 || flag_var_tracking_uninit == 1)
1491 if (debug_info_level < DINFO_LEVEL_NORMAL)
1492 warning_at (UNKNOWN_LOCATION, 0,
1493 "variable tracking requested, but useless unless "
1494 "producing debug info");
1495 else
1496 warning_at (UNKNOWN_LOCATION, 0,
1497 "variable tracking requested, but not supported "
1498 "by this debug format");
1500 flag_var_tracking = 0;
1501 flag_var_tracking_uninit = 0;
1504 /* The debug hooks are used to implement -fdump-go-spec because it
1505 gives a simple and stable API for all the information we need to
1506 dump. */
1507 if (flag_dump_go_spec != NULL)
1508 debug_hooks = dump_go_spec_init (flag_dump_go_spec, debug_hooks);
1510 /* If the user specifically requested variable tracking with tagging
1511 uninitialized variables, we need to turn on variable tracking.
1512 (We already determined above that variable tracking is feasible.) */
1513 if (flag_var_tracking_uninit == 1)
1514 flag_var_tracking = 1;
1516 if (flag_var_tracking == AUTODETECT_VALUE)
1517 flag_var_tracking = optimize >= 1;
1519 if (flag_var_tracking_uninit == AUTODETECT_VALUE)
1520 flag_var_tracking_uninit = flag_var_tracking;
1522 if (flag_var_tracking_assignments == AUTODETECT_VALUE)
1523 flag_var_tracking_assignments = flag_var_tracking
1524 && !(flag_selective_scheduling || flag_selective_scheduling2);
1526 if (flag_var_tracking_assignments_toggle)
1527 flag_var_tracking_assignments = !flag_var_tracking_assignments;
1529 if (flag_var_tracking_assignments && !flag_var_tracking)
1530 flag_var_tracking = flag_var_tracking_assignments = -1;
1532 if (flag_var_tracking_assignments
1533 && (flag_selective_scheduling || flag_selective_scheduling2))
1534 warning_at (UNKNOWN_LOCATION, 0,
1535 "var-tracking-assignments changes selective scheduling");
1537 if (flag_tree_cselim == AUTODETECT_VALUE)
1539 if (HAVE_conditional_move)
1540 flag_tree_cselim = 1;
1541 else
1542 flag_tree_cselim = 0;
1545 /* If auxiliary info generation is desired, open the output file.
1546 This goes in the same directory as the source file--unlike
1547 all the other output files. */
1548 if (flag_gen_aux_info)
1550 aux_info_file = fopen (aux_info_file_name, "w");
1551 if (aux_info_file == 0)
1552 fatal_error (UNKNOWN_LOCATION,
1553 "can%'t open %s: %m", aux_info_file_name);
1556 if (!targetm_common.have_named_sections)
1558 if (flag_function_sections)
1560 warning_at (UNKNOWN_LOCATION, 0,
1561 "-ffunction-sections not supported for this target");
1562 flag_function_sections = 0;
1564 if (flag_data_sections)
1566 warning_at (UNKNOWN_LOCATION, 0,
1567 "-fdata-sections not supported for this target");
1568 flag_data_sections = 0;
1572 if (flag_prefetch_loop_arrays > 0 && !targetm.code_for_prefetch)
1574 warning_at (UNKNOWN_LOCATION, 0,
1575 "-fprefetch-loop-arrays not supported for this target");
1576 flag_prefetch_loop_arrays = 0;
1578 else if (flag_prefetch_loop_arrays > 0 && !targetm.have_prefetch ())
1580 warning_at (UNKNOWN_LOCATION, 0,
1581 "-fprefetch-loop-arrays not supported for this target "
1582 "(try -march switches)");
1583 flag_prefetch_loop_arrays = 0;
1586 /* This combination of options isn't handled for i386 targets and doesn't
1587 make much sense anyway, so don't allow it. */
1588 if (flag_prefetch_loop_arrays > 0 && optimize_size)
1590 warning_at (UNKNOWN_LOCATION, 0,
1591 "-fprefetch-loop-arrays is not supported with -Os");
1592 flag_prefetch_loop_arrays = 0;
1595 /* The presence of IEEE signaling NaNs, implies all math can trap. */
1596 if (flag_signaling_nans)
1597 flag_trapping_math = 1;
1599 /* We cannot reassociate if we want traps or signed zeros. */
1600 if (flag_associative_math && (flag_trapping_math || flag_signed_zeros))
1602 warning_at (UNKNOWN_LOCATION, 0,
1603 "-fassociative-math disabled; other options take "
1604 "precedence");
1605 flag_associative_math = 0;
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;