Fix indentation issues seen by -Wmisleading-indentation
[official-gcc.git] / gcc / lto-wrapper.c
blob11bf9ad063913518326eaec429eb236f796024a8
1 /* Wrapper to call lto. Used by collect2 and the linker plugin.
2 Copyright (C) 2009-2015 Free Software Foundation, Inc.
4 Factored out of collect2 by Rafael Espindola <espindola@google.com>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
23 /* This program is passed a gcc, a list of gcc arguments and a list of
24 object files containing IL. It scans the argument list to check if
25 we are in whopr mode or not modifies the arguments and needed and
26 prints a list of output files on stdout.
28 Example:
30 $ lto-wrapper gcc/xgcc -B gcc a.o b.o -o test -flto
32 The above will print something like
33 /tmp/ccwbQ8B2.lto.o
35 If WHOPR is used instead, more than one file might be produced
36 ./ccXj2DTk.lto.ltrans.o
37 ./ccCJuXGv.lto.ltrans.o
40 #include "config.h"
41 #include "system.h"
42 #include "coretypes.h"
43 #include "intl.h"
44 #include "diagnostic.h"
45 #include "obstack.h"
46 #include "opts.h"
47 #include "options.h"
48 #include "simple-object.h"
49 #include "lto-section-names.h"
50 #include "collect-utils.h"
52 /* Environment variable, used for passing the names of offload targets from GCC
53 driver to lto-wrapper. */
54 #define OFFLOAD_TARGET_NAMES_ENV "OFFLOAD_TARGET_NAMES"
56 enum lto_mode_d {
57 LTO_MODE_NONE, /* Not doing LTO. */
58 LTO_MODE_LTO, /* Normal LTO. */
59 LTO_MODE_WHOPR /* WHOPR. */
62 /* Current LTO mode. */
63 static enum lto_mode_d lto_mode = LTO_MODE_NONE;
65 static char *ltrans_output_file;
66 static char *flto_out;
67 static unsigned int nr;
68 static char **input_names;
69 static char **output_names;
70 static char **offload_names;
71 static const char *offloadbegin, *offloadend;
72 static char *makefile;
74 const char tool_name[] = "lto-wrapper";
76 /* Delete tempfiles. Called from utils_cleanup. */
78 void
79 tool_cleanup (bool)
81 unsigned int i;
83 if (ltrans_output_file)
84 maybe_unlink (ltrans_output_file);
85 if (flto_out)
86 maybe_unlink (flto_out);
87 if (makefile)
88 maybe_unlink (makefile);
89 for (i = 0; i < nr; ++i)
91 maybe_unlink (input_names[i]);
92 if (output_names[i])
93 maybe_unlink (output_names[i]);
97 static void
98 lto_wrapper_cleanup (void)
100 utils_cleanup (false);
103 /* Unlink a temporary LTRANS file unless requested otherwise. */
105 void
106 maybe_unlink (const char *file)
108 if (!save_temps)
110 if (unlink_if_ordinary (file)
111 && errno != ENOENT)
112 fatal_error (input_location, "deleting LTRANS file %s: %m", file);
114 else if (verbose)
115 fprintf (stderr, "[Leaving LTRANS %s]\n", file);
118 /* Template of LTRANS dumpbase suffix. */
119 #define DUMPBASE_SUFFIX ".ltrans18446744073709551615"
121 /* Create decoded options from the COLLECT_GCC and COLLECT_GCC_OPTIONS
122 environment according to LANG_MASK. */
124 static void
125 get_options_from_collect_gcc_options (const char *collect_gcc,
126 const char *collect_gcc_options,
127 unsigned int lang_mask,
128 struct cl_decoded_option **decoded_options,
129 unsigned int *decoded_options_count)
131 struct obstack argv_obstack;
132 char *argv_storage;
133 const char **argv;
134 int j, k, argc;
136 argv_storage = xstrdup (collect_gcc_options);
137 obstack_init (&argv_obstack);
138 obstack_ptr_grow (&argv_obstack, collect_gcc);
140 for (j = 0, k = 0; argv_storage[j] != '\0'; ++j)
142 if (argv_storage[j] == '\'')
144 obstack_ptr_grow (&argv_obstack, &argv_storage[k]);
145 ++j;
148 if (argv_storage[j] == '\0')
149 fatal_error (input_location, "malformed COLLECT_GCC_OPTIONS");
150 else if (strncmp (&argv_storage[j], "'\\''", 4) == 0)
152 argv_storage[k++] = '\'';
153 j += 4;
155 else if (argv_storage[j] == '\'')
156 break;
157 else
158 argv_storage[k++] = argv_storage[j++];
160 while (1);
161 argv_storage[k++] = '\0';
165 obstack_ptr_grow (&argv_obstack, NULL);
166 argc = obstack_object_size (&argv_obstack) / sizeof (void *) - 1;
167 argv = XOBFINISH (&argv_obstack, const char **);
169 decode_cmdline_options_to_array (argc, (const char **)argv,
170 lang_mask,
171 decoded_options, decoded_options_count);
172 obstack_free (&argv_obstack, NULL);
175 /* Append OPTION to the options array DECODED_OPTIONS with size
176 DECODED_OPTIONS_COUNT. */
178 static void
179 append_option (struct cl_decoded_option **decoded_options,
180 unsigned int *decoded_options_count,
181 struct cl_decoded_option *option)
183 ++*decoded_options_count;
184 *decoded_options
185 = (struct cl_decoded_option *)
186 xrealloc (*decoded_options,
187 (*decoded_options_count
188 * sizeof (struct cl_decoded_option)));
189 memcpy (&(*decoded_options)[*decoded_options_count - 1], option,
190 sizeof (struct cl_decoded_option));
193 /* Try to merge and complain about options FDECODED_OPTIONS when applied
194 ontop of DECODED_OPTIONS. */
196 static void
197 merge_and_complain (struct cl_decoded_option **decoded_options,
198 unsigned int *decoded_options_count,
199 struct cl_decoded_option *fdecoded_options,
200 unsigned int fdecoded_options_count)
202 unsigned int i, j;
204 /* ??? Merge options from files. Most cases can be
205 handled by either unioning or intersecting
206 (for example -fwrapv is a case for unioning,
207 -ffast-math is for intersection). Most complaints
208 about real conflicts between different options can
209 be deferred to the compiler proper. Options that
210 we can neither safely handle by intersection nor
211 unioning would need to be complained about here.
212 Ideally we'd have a flag in the opt files that
213 tells whether to union or intersect or reject.
214 In absence of that it's unclear what a good default is.
215 It's also difficult to get positional handling correct. */
217 /* The following does what the old LTO option code did,
218 union all target and a selected set of common options. */
219 for (i = 0; i < fdecoded_options_count; ++i)
221 struct cl_decoded_option *foption = &fdecoded_options[i];
222 switch (foption->opt_index)
224 case OPT_SPECIAL_unknown:
225 case OPT_SPECIAL_ignore:
226 case OPT_SPECIAL_program_name:
227 case OPT_SPECIAL_input_file:
228 break;
230 default:
231 if (!(cl_options[foption->opt_index].flags & CL_TARGET))
232 break;
234 /* Fallthru. */
235 case OPT_fPIC:
236 case OPT_fpic:
237 case OPT_fPIE:
238 case OPT_fpie:
239 case OPT_fcommon:
240 case OPT_fexceptions:
241 case OPT_fnon_call_exceptions:
242 case OPT_fgnu_tm:
243 /* Do what the old LTO code did - collect exactly one option
244 setting per OPT code, we pick the first we encounter.
245 ??? This doesn't make too much sense, but when it doesn't
246 then we should complain. */
247 for (j = 0; j < *decoded_options_count; ++j)
248 if ((*decoded_options)[j].opt_index == foption->opt_index)
249 break;
250 if (j == *decoded_options_count)
251 append_option (decoded_options, decoded_options_count, foption);
252 break;
254 case OPT_ftrapv:
255 case OPT_fstrict_overflow:
256 case OPT_ffp_contract_:
257 /* For selected options we can merge conservatively. */
258 for (j = 0; j < *decoded_options_count; ++j)
259 if ((*decoded_options)[j].opt_index == foption->opt_index)
260 break;
261 if (j == *decoded_options_count)
262 append_option (decoded_options, decoded_options_count, foption);
263 /* FP_CONTRACT_OFF < FP_CONTRACT_ON < FP_CONTRACT_FAST,
264 -fno-trapv < -ftrapv,
265 -fno-strict-overflow < -fstrict-overflow */
266 else if (foption->value < (*decoded_options)[j].value)
267 (*decoded_options)[j] = *foption;
268 break;
270 case OPT_fmath_errno:
271 case OPT_fsigned_zeros:
272 case OPT_ftrapping_math:
273 case OPT_fwrapv:
274 case OPT_fopenmp:
275 case OPT_fopenacc:
276 /* For selected options we can merge conservatively. */
277 for (j = 0; j < *decoded_options_count; ++j)
278 if ((*decoded_options)[j].opt_index == foption->opt_index)
279 break;
280 if (j == *decoded_options_count)
281 append_option (decoded_options, decoded_options_count, foption);
282 /* -fmath-errno > -fno-math-errno,
283 -fsigned-zeros > -fno-signed-zeros,
284 -ftrapping-math -> -fno-trapping-math,
285 -fwrapv > -fno-wrapv. */
286 else if (foption->value > (*decoded_options)[j].value)
287 (*decoded_options)[j] = *foption;
288 break;
290 case OPT_freg_struct_return:
291 case OPT_fpcc_struct_return:
292 case OPT_fshort_double:
293 for (j = 0; j < *decoded_options_count; ++j)
294 if ((*decoded_options)[j].opt_index == foption->opt_index)
295 break;
296 if (j == *decoded_options_count)
297 fatal_error (input_location,
298 "Option %s not used consistently in all LTO input"
299 " files", foption->orig_option_with_args_text);
300 break;
302 case OPT_foffload_abi_:
303 for (j = 0; j < *decoded_options_count; ++j)
304 if ((*decoded_options)[j].opt_index == foption->opt_index)
305 break;
306 if (j == *decoded_options_count)
307 append_option (decoded_options, decoded_options_count, foption);
308 else if (foption->value != (*decoded_options)[j].value)
309 fatal_error (input_location,
310 "Option %s not used consistently in all LTO input"
311 " files", foption->orig_option_with_args_text);
312 break;
314 case OPT_O:
315 case OPT_Ofast:
316 case OPT_Og:
317 case OPT_Os:
318 for (j = 0; j < *decoded_options_count; ++j)
319 if ((*decoded_options)[j].opt_index == OPT_O
320 || (*decoded_options)[j].opt_index == OPT_Ofast
321 || (*decoded_options)[j].opt_index == OPT_Og
322 || (*decoded_options)[j].opt_index == OPT_Os)
323 break;
324 if (j == *decoded_options_count)
325 append_option (decoded_options, decoded_options_count, foption);
326 else if ((*decoded_options)[j].opt_index == foption->opt_index
327 && foption->opt_index != OPT_O)
328 /* Exact same options get merged. */
330 else
332 /* For mismatched option kinds preserve the optimization
333 level only, thus merge it as -On. This also handles
334 merging of same optimization level -On. */
335 int level = 0;
336 switch (foption->opt_index)
338 case OPT_O:
339 if (foption->arg[0] == '\0')
340 level = MAX (level, 1);
341 else
342 level = MAX (level, atoi (foption->arg));
343 break;
344 case OPT_Ofast:
345 level = MAX (level, 3);
346 break;
347 case OPT_Og:
348 level = MAX (level, 1);
349 break;
350 case OPT_Os:
351 level = MAX (level, 2);
352 break;
353 default:
354 gcc_unreachable ();
356 switch ((*decoded_options)[j].opt_index)
358 case OPT_O:
359 if ((*decoded_options)[j].arg[0] == '\0')
360 level = MAX (level, 1);
361 else
362 level = MAX (level, atoi ((*decoded_options)[j].arg));
363 break;
364 case OPT_Ofast:
365 level = MAX (level, 3);
366 break;
367 case OPT_Og:
368 level = MAX (level, 1);
369 break;
370 case OPT_Os:
371 level = MAX (level, 2);
372 break;
373 default:
374 gcc_unreachable ();
376 (*decoded_options)[j].opt_index = OPT_O;
377 char *tem;
378 tem = xasprintf ("-O%d", level);
379 (*decoded_options)[j].arg = &tem[2];
380 (*decoded_options)[j].canonical_option[0] = tem;
381 (*decoded_options)[j].value = 1;
383 break;
385 case OPT_foffload_:
386 append_option (decoded_options, decoded_options_count, foption);
387 break;
392 /* Auxiliary function that frees elements of PTR and PTR itself.
393 N is number of elements to be freed. If PTR is NULL, nothing is freed.
394 If an element is NULL, subsequent elements are not freed. */
396 static void **
397 free_array_of_ptrs (void **ptr, unsigned n)
399 if (!ptr)
400 return NULL;
401 for (unsigned i = 0; i < n; i++)
403 if (!ptr[i])
404 break;
405 free (ptr[i]);
407 free (ptr);
408 return NULL;
411 /* Parse STR, saving found tokens into PVALUES and return their number.
412 Tokens are assumed to be delimited by ':'. If APPEND is non-null,
413 append it to every token we find. */
415 static unsigned
416 parse_env_var (const char *str, char ***pvalues, const char *append)
418 const char *curval, *nextval;
419 char **values;
420 unsigned num = 1, i;
422 curval = strchr (str, ':');
423 while (curval)
425 num++;
426 curval = strchr (curval + 1, ':');
429 values = (char**) xmalloc (num * sizeof (char*));
430 curval = str;
431 nextval = strchr (curval, ':');
432 if (nextval == NULL)
433 nextval = strchr (curval, '\0');
435 int append_len = append ? strlen (append) : 0;
436 for (i = 0; i < num; i++)
438 int l = nextval - curval;
439 values[i] = (char*) xmalloc (l + 1 + append_len);
440 memcpy (values[i], curval, l);
441 values[i][l] = 0;
442 if (append)
443 strcat (values[i], append);
444 curval = nextval + 1;
445 nextval = strchr (curval, ':');
446 if (nextval == NULL)
447 nextval = strchr (curval, '\0');
449 *pvalues = values;
450 return num;
453 /* Append options OPTS from lto or offload_lto sections to ARGV_OBSTACK. */
455 static void
456 append_compiler_options (obstack *argv_obstack, struct cl_decoded_option *opts,
457 unsigned int count)
459 /* Append compiler driver arguments as far as they were merged. */
460 for (unsigned int j = 1; j < count; ++j)
462 struct cl_decoded_option *option = &opts[j];
464 /* File options have been properly filtered by lto-opts.c. */
465 switch (option->opt_index)
467 /* Drop arguments that we want to take from the link line. */
468 case OPT_flto_:
469 case OPT_flto:
470 case OPT_flto_partition_:
471 continue;
473 default:
474 break;
477 /* For now do what the original LTO option code was doing - pass
478 on any CL_TARGET flag and a few selected others. */
479 switch (option->opt_index)
481 case OPT_fPIC:
482 case OPT_fpic:
483 case OPT_fPIE:
484 case OPT_fpie:
485 case OPT_fcommon:
486 case OPT_fexceptions:
487 case OPT_fnon_call_exceptions:
488 case OPT_fgnu_tm:
489 case OPT_freg_struct_return:
490 case OPT_fpcc_struct_return:
491 case OPT_fshort_double:
492 case OPT_ffp_contract_:
493 case OPT_fmath_errno:
494 case OPT_fsigned_zeros:
495 case OPT_ftrapping_math:
496 case OPT_fwrapv:
497 case OPT_fopenmp:
498 case OPT_fopenacc:
499 case OPT_ftrapv:
500 case OPT_fstrict_overflow:
501 case OPT_foffload_abi_:
502 case OPT_O:
503 case OPT_Ofast:
504 case OPT_Og:
505 case OPT_Os:
506 break;
508 default:
509 if (!(cl_options[option->opt_index].flags & CL_TARGET))
510 continue;
513 /* Pass the option on. */
514 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
515 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
519 /* Append linker options OPTS to ARGV_OBSTACK. */
521 static void
522 append_linker_options (obstack *argv_obstack, struct cl_decoded_option *opts,
523 unsigned int count)
525 /* Append linker driver arguments. Compiler options from the linker
526 driver arguments will override / merge with those from the compiler. */
527 for (unsigned int j = 1; j < count; ++j)
529 struct cl_decoded_option *option = &opts[j];
531 /* Do not pass on frontend specific flags not suitable for lto. */
532 if (!(cl_options[option->opt_index].flags
533 & (CL_COMMON|CL_TARGET|CL_DRIVER|CL_LTO)))
534 continue;
536 switch (option->opt_index)
538 case OPT_o:
539 case OPT_flto_:
540 case OPT_flto:
541 /* We've handled these LTO options, do not pass them on. */
542 continue;
544 case OPT_freg_struct_return:
545 case OPT_fpcc_struct_return:
546 case OPT_fshort_double:
547 /* Ignore these, they are determined by the input files.
548 ??? We fail to diagnose a possible mismatch here. */
549 continue;
551 default:
552 break;
555 /* Pass the option on. */
556 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
557 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
561 /* Extract options for TARGET offload compiler from OPTIONS and append
562 them to ARGV_OBSTACK. */
564 static void
565 append_offload_options (obstack *argv_obstack, const char *target,
566 struct cl_decoded_option *options,
567 unsigned int options_count)
569 for (unsigned i = 0; i < options_count; i++)
571 const char *cur, *next, *opts;
572 char **argv;
573 unsigned argc;
574 struct cl_decoded_option *option = &options[i];
576 if (option->opt_index != OPT_foffload_)
577 continue;
579 /* If option argument starts with '-' then no target is specified. That
580 means offload options are specified for all targets, so we need to
581 append them. */
582 if (option->arg[0] == '-')
583 opts = option->arg;
584 else
586 opts = strchr (option->arg, '=');
587 if (!opts)
588 continue;
590 cur = option->arg;
592 while (cur < opts)
594 next = strchr (cur, ',');
595 if (next == NULL)
596 next = opts;
597 next = (next > opts) ? opts : next;
599 if (strlen (target) == (size_t) (next - cur)
600 && strncmp (target, cur, next - cur) == 0)
601 break;
603 cur = next + 1;
606 if (cur >= opts)
607 continue;
609 opts++;
612 argv = buildargv (opts);
613 for (argc = 0; argv[argc]; argc++)
614 obstack_ptr_grow (argv_obstack, argv[argc]);
618 /* Check whether NAME can be accessed in MODE. This is like access,
619 except that it never considers directories to be executable. */
621 static int
622 access_check (const char *name, int mode)
624 if (mode == X_OK)
626 struct stat st;
628 if (stat (name, &st) < 0
629 || S_ISDIR (st.st_mode))
630 return -1;
633 return access (name, mode);
636 /* Prepare a target image for offload TARGET, using mkoffload tool from
637 COMPILER_PATH. Return the name of the resultant object file. */
639 static char *
640 compile_offload_image (const char *target, const char *compiler_path,
641 unsigned in_argc, char *in_argv[],
642 struct cl_decoded_option *compiler_opts,
643 unsigned int compiler_opt_count,
644 struct cl_decoded_option *linker_opts,
645 unsigned int linker_opt_count)
647 char *filename = NULL;
648 char **argv;
649 char *suffix
650 = XALLOCAVEC (char, sizeof ("/accel//mkoffload") + strlen (target));
651 strcpy (suffix, "/accel/");
652 strcat (suffix, target);
653 strcat (suffix, "/mkoffload");
655 char **paths = NULL;
656 unsigned n_paths = parse_env_var (compiler_path, &paths, suffix);
658 const char *compiler = NULL;
659 for (unsigned i = 0; i < n_paths; i++)
660 if (access_check (paths[i], X_OK) == 0)
662 compiler = paths[i];
663 break;
666 if (compiler)
668 /* Generate temporary output file name. */
669 filename = make_temp_file (".target.o");
671 struct obstack argv_obstack;
672 obstack_init (&argv_obstack);
673 obstack_ptr_grow (&argv_obstack, compiler);
674 obstack_ptr_grow (&argv_obstack, "-o");
675 obstack_ptr_grow (&argv_obstack, filename);
677 /* Append names of input object files. */
678 for (unsigned i = 0; i < in_argc; i++)
679 obstack_ptr_grow (&argv_obstack, in_argv[i]);
681 /* Append options from offload_lto sections. */
682 append_compiler_options (&argv_obstack, compiler_opts,
683 compiler_opt_count);
685 /* Append options specified by -foffload last. In case of conflicting
686 options we expect offload compiler to choose the latest. */
687 append_offload_options (&argv_obstack, target, compiler_opts,
688 compiler_opt_count);
689 append_offload_options (&argv_obstack, target, linker_opts,
690 linker_opt_count);
692 obstack_ptr_grow (&argv_obstack, NULL);
693 argv = XOBFINISH (&argv_obstack, char **);
694 fork_execute (argv[0], argv, true);
695 obstack_free (&argv_obstack, NULL);
698 free_array_of_ptrs ((void **) paths, n_paths);
699 return filename;
703 /* The main routine dealing with offloading.
704 The routine builds a target image for each offload target. IN_ARGC and
705 IN_ARGV specify options and input object files. As all of them could contain
706 target sections, we pass them all to target compilers. */
708 static void
709 compile_images_for_offload_targets (unsigned in_argc, char *in_argv[],
710 struct cl_decoded_option *compiler_opts,
711 unsigned int compiler_opt_count,
712 struct cl_decoded_option *linker_opts,
713 unsigned int linker_opt_count)
715 char **names = NULL;
716 const char *target_names = getenv (OFFLOAD_TARGET_NAMES_ENV);
717 if (!target_names)
718 return;
719 unsigned num_targets = parse_env_var (target_names, &names, NULL);
721 const char *compiler_path = getenv ("COMPILER_PATH");
722 if (!compiler_path)
723 goto out;
725 /* Prepare an image for each target and save the name of the resultant object
726 file to the OFFLOAD_NAMES array. It is terminated by a NULL entry. */
727 offload_names = XCNEWVEC (char *, num_targets + 1);
728 for (unsigned i = 0; i < num_targets; i++)
730 offload_names[i]
731 = compile_offload_image (names[i], compiler_path, in_argc, in_argv,
732 compiler_opts, compiler_opt_count,
733 linker_opts, linker_opt_count);
734 if (!offload_names[i])
735 fatal_error (input_location,
736 "problem with building target image for %s\n", names[i]);
739 out:
740 free_array_of_ptrs ((void **) names, num_targets);
743 /* Copy a file from SRC to DEST. */
745 static void
746 copy_file (const char *dest, const char *src)
748 FILE *d = fopen (dest, "wb");
749 FILE *s = fopen (src, "rb");
750 char buffer[512];
751 while (!feof (s))
753 size_t len = fread (buffer, 1, 512, s);
754 if (ferror (s) != 0)
755 fatal_error (input_location, "reading input file");
756 if (len > 0)
758 fwrite (buffer, 1, len, d);
759 if (ferror (d) != 0)
760 fatal_error (input_location, "writing output file");
765 /* Find the crtoffloadbegin.o and crtoffloadend.o files in LIBRARY_PATH, make
766 copies and store the names of the copies in offloadbegin and offloadend. */
768 static void
769 find_offloadbeginend (void)
771 char **paths = NULL;
772 const char *library_path = getenv ("LIBRARY_PATH");
773 if (!library_path)
774 return;
775 unsigned n_paths = parse_env_var (library_path, &paths, "/crtoffloadbegin.o");
777 unsigned i;
778 for (i = 0; i < n_paths; i++)
779 if (access_check (paths[i], R_OK) == 0)
781 size_t len = strlen (paths[i]);
782 char *tmp = xstrdup (paths[i]);
783 strcpy (paths[i] + len - strlen ("begin.o"), "end.o");
784 if (access_check (paths[i], R_OK) != 0)
785 fatal_error (input_location,
786 "installation error, can't find crtoffloadend.o");
787 /* The linker will delete the filenames we give it, so make
788 copies. */
789 offloadbegin = make_temp_file (".o");
790 offloadend = make_temp_file (".o");
791 copy_file (offloadbegin, tmp);
792 copy_file (offloadend, paths[i]);
793 free (tmp);
794 break;
796 if (i == n_paths)
797 fatal_error (input_location,
798 "installation error, can't find crtoffloadbegin.o");
800 free_array_of_ptrs ((void **) paths, n_paths);
803 /* A subroutine of run_gcc. Examine the open file FD for lto sections with
804 name prefix PREFIX, at FILE_OFFSET, and store any options we find in OPTS
805 and OPT_COUNT. Return true if we found a matchingn section, false
806 otherwise. COLLECT_GCC holds the value of the environment variable with
807 the same name. */
809 static bool
810 find_and_merge_options (int fd, off_t file_offset, const char *prefix,
811 struct cl_decoded_option **opts,
812 unsigned int *opt_count, const char *collect_gcc)
814 off_t offset, length;
815 char *data;
816 char *fopts;
817 const char *errmsg;
818 int err;
819 struct cl_decoded_option *fdecoded_options = *opts;
820 unsigned int fdecoded_options_count = *opt_count;
822 simple_object_read *sobj;
823 sobj = simple_object_start_read (fd, file_offset, "__GNU_LTO",
824 &errmsg, &err);
825 if (!sobj)
826 return false;
828 char *secname = XALLOCAVEC (char, strlen (prefix) + sizeof (".opts"));
829 strcpy (secname, prefix);
830 strcat (secname, ".opts");
831 if (!simple_object_find_section (sobj, secname, &offset, &length,
832 &errmsg, &err))
834 simple_object_release_read (sobj);
835 return false;
838 lseek (fd, file_offset + offset, SEEK_SET);
839 data = (char *)xmalloc (length);
840 read (fd, data, length);
841 fopts = data;
844 struct cl_decoded_option *f2decoded_options;
845 unsigned int f2decoded_options_count;
846 get_options_from_collect_gcc_options (collect_gcc,
847 fopts, CL_LANG_ALL,
848 &f2decoded_options,
849 &f2decoded_options_count);
850 if (!fdecoded_options)
852 fdecoded_options = f2decoded_options;
853 fdecoded_options_count = f2decoded_options_count;
855 else
856 merge_and_complain (&fdecoded_options,
857 &fdecoded_options_count,
858 f2decoded_options, f2decoded_options_count);
860 fopts += strlen (fopts) + 1;
862 while (fopts - data < length);
864 free (data);
865 simple_object_release_read (sobj);
866 *opts = fdecoded_options;
867 *opt_count = fdecoded_options_count;
868 return true;
871 /* Execute gcc. ARGC is the number of arguments. ARGV contains the arguments. */
873 static void
874 run_gcc (unsigned argc, char *argv[])
876 unsigned i, j;
877 const char **new_argv;
878 const char **argv_ptr;
879 char *list_option_full = NULL;
880 const char *linker_output = NULL;
881 const char *collect_gcc, *collect_gcc_options;
882 int parallel = 0;
883 int jobserver = 0;
884 bool no_partition = false;
885 struct cl_decoded_option *fdecoded_options = NULL;
886 struct cl_decoded_option *offload_fdecoded_options = NULL;
887 unsigned int fdecoded_options_count = 0;
888 unsigned int offload_fdecoded_options_count = 0;
889 struct cl_decoded_option *decoded_options;
890 unsigned int decoded_options_count;
891 struct obstack argv_obstack;
892 int new_head_argc;
893 bool have_lto = false;
894 bool have_offload = false;
895 unsigned lto_argc = 0, offload_argc = 0;
896 char **lto_argv, **offload_argv;
898 /* Get the driver and options. */
899 collect_gcc = getenv ("COLLECT_GCC");
900 if (!collect_gcc)
901 fatal_error (input_location,
902 "environment variable COLLECT_GCC must be set");
903 collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
904 if (!collect_gcc_options)
905 fatal_error (input_location,
906 "environment variable COLLECT_GCC_OPTIONS must be set");
907 get_options_from_collect_gcc_options (collect_gcc, collect_gcc_options,
908 CL_LANG_ALL,
909 &decoded_options,
910 &decoded_options_count);
912 /* Allocate arrays for input object files with LTO or offload IL,
913 and for possible preceding arguments. */
914 lto_argv = XNEWVEC (char *, argc);
915 offload_argv = XNEWVEC (char *, argc);
917 /* Look at saved options in the IL files. */
918 for (i = 1; i < argc; ++i)
920 char *p;
921 int fd;
922 off_t file_offset = 0;
923 long loffset;
924 int consumed;
925 char *filename = argv[i];
927 if ((p = strrchr (argv[i], '@'))
928 && p != argv[i]
929 && sscanf (p, "@%li%n", &loffset, &consumed) >= 1
930 && strlen (p) == (unsigned int) consumed)
932 filename = XNEWVEC (char, p - argv[i] + 1);
933 memcpy (filename, argv[i], p - argv[i]);
934 filename[p - argv[i]] = '\0';
935 file_offset = (off_t) loffset;
937 fd = open (filename, O_RDONLY | O_BINARY);
938 if (fd == -1)
940 lto_argv[lto_argc++] = argv[i];
941 continue;
944 if (find_and_merge_options (fd, file_offset, LTO_SECTION_NAME_PREFIX,
945 &fdecoded_options, &fdecoded_options_count,
946 collect_gcc))
948 have_lto = true;
949 lto_argv[lto_argc++] = argv[i];
952 if (find_and_merge_options (fd, file_offset, OFFLOAD_SECTION_NAME_PREFIX,
953 &offload_fdecoded_options,
954 &offload_fdecoded_options_count, collect_gcc))
956 have_offload = true;
957 offload_argv[offload_argc++] = argv[i];
960 close (fd);
963 /* Initalize the common arguments for the driver. */
964 obstack_init (&argv_obstack);
965 obstack_ptr_grow (&argv_obstack, collect_gcc);
966 obstack_ptr_grow (&argv_obstack, "-xlto");
967 obstack_ptr_grow (&argv_obstack, "-c");
969 append_compiler_options (&argv_obstack, fdecoded_options,
970 fdecoded_options_count);
971 append_linker_options (&argv_obstack, decoded_options, decoded_options_count);
973 /* Scan linker driver arguments for things that are of relevance to us. */
974 for (j = 1; j < decoded_options_count; ++j)
976 struct cl_decoded_option *option = &decoded_options[j];
977 switch (option->opt_index)
979 case OPT_o:
980 linker_output = option->arg;
981 break;
983 case OPT_save_temps:
984 save_temps = 1;
985 break;
987 case OPT_v:
988 verbose = 1;
989 break;
991 case OPT_flto_partition_:
992 if (strcmp (option->arg, "none") == 0)
993 no_partition = true;
994 break;
996 case OPT_flto_:
997 if (strcmp (option->arg, "jobserver") == 0)
999 jobserver = 1;
1000 parallel = 1;
1002 else
1004 parallel = atoi (option->arg);
1005 if (parallel <= 1)
1006 parallel = 0;
1008 /* Fallthru. */
1010 case OPT_flto:
1011 lto_mode = LTO_MODE_WHOPR;
1012 break;
1014 default:
1015 break;
1019 if (no_partition)
1021 lto_mode = LTO_MODE_LTO;
1022 jobserver = 0;
1023 parallel = 0;
1026 if (linker_output)
1028 char *output_dir, *base, *name;
1029 bool bit_bucket = strcmp (linker_output, HOST_BIT_BUCKET) == 0;
1031 output_dir = xstrdup (linker_output);
1032 base = output_dir;
1033 for (name = base; *name; name++)
1034 if (IS_DIR_SEPARATOR (*name))
1035 base = name + 1;
1036 *base = '\0';
1038 linker_output = &linker_output[base - output_dir];
1039 if (*output_dir == '\0')
1041 static char current_dir[] = { '.', DIR_SEPARATOR, '\0' };
1042 output_dir = current_dir;
1044 if (!bit_bucket)
1046 obstack_ptr_grow (&argv_obstack, "-dumpdir");
1047 obstack_ptr_grow (&argv_obstack, output_dir);
1050 obstack_ptr_grow (&argv_obstack, "-dumpbase");
1053 /* Remember at which point we can scrub args to re-use the commons. */
1054 new_head_argc = obstack_object_size (&argv_obstack) / sizeof (void *);
1056 if (have_offload)
1058 compile_images_for_offload_targets (offload_argc, offload_argv,
1059 offload_fdecoded_options,
1060 offload_fdecoded_options_count,
1061 decoded_options,
1062 decoded_options_count);
1063 if (offload_names)
1065 find_offloadbeginend ();
1066 for (i = 0; offload_names[i]; i++)
1067 printf ("%s\n", offload_names[i]);
1068 free_array_of_ptrs ((void **) offload_names, i);
1072 if (offloadbegin)
1073 printf ("%s\n", offloadbegin);
1075 /* If object files contain offload sections, but do not contain LTO sections,
1076 then there is no need to perform a link-time recompilation, i.e.
1077 lto-wrapper is used only for a compilation of offload images. */
1078 if (have_offload && !have_lto)
1080 for (i = 1; i < argc; ++i)
1081 if (strncmp (argv[i], "-fresolution=", sizeof ("-fresolution=") - 1))
1083 char *out_file;
1084 /* Can be ".o" or ".so". */
1085 char *ext = strrchr (argv[i], '.');
1086 if (ext == NULL)
1087 out_file = make_temp_file ("");
1088 else
1089 out_file = make_temp_file (ext);
1090 /* The linker will delete the files we give it, so make copies. */
1091 copy_file (out_file, argv[i]);
1092 printf ("%s\n", out_file);
1094 goto finish;
1097 if (lto_mode == LTO_MODE_LTO)
1099 flto_out = make_temp_file (".lto.o");
1100 if (linker_output)
1101 obstack_ptr_grow (&argv_obstack, linker_output);
1102 obstack_ptr_grow (&argv_obstack, "-o");
1103 obstack_ptr_grow (&argv_obstack, flto_out);
1105 else
1107 const char *list_option = "-fltrans-output-list=";
1108 size_t list_option_len = strlen (list_option);
1109 char *tmp;
1111 if (linker_output)
1113 char *dumpbase = (char *) xmalloc (strlen (linker_output)
1114 + sizeof (".wpa") + 1);
1115 strcpy (dumpbase, linker_output);
1116 strcat (dumpbase, ".wpa");
1117 obstack_ptr_grow (&argv_obstack, dumpbase);
1120 if (linker_output && save_temps)
1122 ltrans_output_file = (char *) xmalloc (strlen (linker_output)
1123 + sizeof (".ltrans.out") + 1);
1124 strcpy (ltrans_output_file, linker_output);
1125 strcat (ltrans_output_file, ".ltrans.out");
1127 else
1128 ltrans_output_file = make_temp_file (".ltrans.out");
1129 list_option_full = (char *) xmalloc (sizeof (char) *
1130 (strlen (ltrans_output_file) + list_option_len + 1));
1131 tmp = list_option_full;
1133 obstack_ptr_grow (&argv_obstack, tmp);
1134 strcpy (tmp, list_option);
1135 tmp += list_option_len;
1136 strcpy (tmp, ltrans_output_file);
1138 if (jobserver)
1139 obstack_ptr_grow (&argv_obstack, xstrdup ("-fwpa=jobserver"));
1140 else if (parallel > 1)
1142 char buf[256];
1143 sprintf (buf, "-fwpa=%i", parallel);
1144 obstack_ptr_grow (&argv_obstack, xstrdup (buf));
1146 else
1147 obstack_ptr_grow (&argv_obstack, "-fwpa");
1150 /* Append the input objects and possible preceding arguments. */
1151 for (i = 0; i < lto_argc; ++i)
1152 obstack_ptr_grow (&argv_obstack, lto_argv[i]);
1153 obstack_ptr_grow (&argv_obstack, NULL);
1155 new_argv = XOBFINISH (&argv_obstack, const char **);
1156 argv_ptr = &new_argv[new_head_argc];
1157 fork_execute (new_argv[0], CONST_CAST (char **, new_argv), true);
1159 if (lto_mode == LTO_MODE_LTO)
1161 printf ("%s\n", flto_out);
1162 free (flto_out);
1163 flto_out = NULL;
1165 else
1167 FILE *stream = fopen (ltrans_output_file, "r");
1168 FILE *mstream = NULL;
1169 struct obstack env_obstack;
1171 if (!stream)
1172 fatal_error (input_location, "fopen: %s: %m", ltrans_output_file);
1174 /* Parse the list of LTRANS inputs from the WPA stage. */
1175 obstack_init (&env_obstack);
1176 nr = 0;
1177 for (;;)
1179 const unsigned piece = 32;
1180 char *output_name = NULL;
1181 char *buf, *input_name = (char *)xmalloc (piece);
1182 size_t len;
1184 buf = input_name;
1185 cont:
1186 if (!fgets (buf, piece, stream))
1187 break;
1188 len = strlen (input_name);
1189 if (input_name[len - 1] != '\n')
1191 input_name = (char *)xrealloc (input_name, len + piece);
1192 buf = input_name + len;
1193 goto cont;
1195 input_name[len - 1] = '\0';
1197 if (input_name[0] == '*')
1198 output_name = &input_name[1];
1200 nr++;
1201 input_names = (char **)xrealloc (input_names, nr * sizeof (char *));
1202 output_names = (char **)xrealloc (output_names, nr * sizeof (char *));
1203 input_names[nr-1] = input_name;
1204 output_names[nr-1] = output_name;
1206 fclose (stream);
1207 maybe_unlink (ltrans_output_file);
1208 ltrans_output_file = NULL;
1210 if (parallel)
1212 makefile = make_temp_file (".mk");
1213 mstream = fopen (makefile, "w");
1216 /* Execute the LTRANS stage for each input file (or prepare a
1217 makefile to invoke this in parallel). */
1218 for (i = 0; i < nr; ++i)
1220 char *output_name;
1221 char *input_name = input_names[i];
1222 /* If it's a pass-through file do nothing. */
1223 if (output_names[i])
1224 continue;
1226 /* Replace the .o suffix with a .ltrans.o suffix and write
1227 the resulting name to the LTRANS output list. */
1228 obstack_grow (&env_obstack, input_name, strlen (input_name) - 2);
1229 obstack_grow (&env_obstack, ".ltrans.o", sizeof (".ltrans.o"));
1230 output_name = XOBFINISH (&env_obstack, char *);
1232 /* Adjust the dumpbase if the linker output file was seen. */
1233 if (linker_output)
1235 char *dumpbase
1236 = (char *) xmalloc (strlen (linker_output)
1237 + sizeof (DUMPBASE_SUFFIX) + 1);
1238 snprintf (dumpbase,
1239 strlen (linker_output) + sizeof (DUMPBASE_SUFFIX),
1240 "%s.ltrans%u", linker_output, i);
1241 argv_ptr[0] = dumpbase;
1244 argv_ptr[1] = "-fltrans";
1245 argv_ptr[2] = "-o";
1246 argv_ptr[3] = output_name;
1247 argv_ptr[4] = input_name;
1248 argv_ptr[5] = NULL;
1249 if (parallel)
1251 fprintf (mstream, "%s:\n\t@%s ", output_name, new_argv[0]);
1252 for (j = 1; new_argv[j] != NULL; ++j)
1253 fprintf (mstream, " '%s'", new_argv[j]);
1254 fprintf (mstream, "\n");
1255 /* If we are not preserving the ltrans input files then
1256 truncate them as soon as we have processed it. This
1257 reduces temporary disk-space usage. */
1258 if (! save_temps)
1259 fprintf (mstream, "\t@-touch -r %s %s.tem > /dev/null 2>&1 "
1260 "&& mv %s.tem %s\n",
1261 input_name, input_name, input_name, input_name);
1263 else
1265 fork_execute (new_argv[0], CONST_CAST (char **, new_argv),
1266 true);
1267 maybe_unlink (input_name);
1270 output_names[i] = output_name;
1272 if (parallel)
1274 struct pex_obj *pex;
1275 char jobs[32];
1277 fprintf (mstream, "all:");
1278 for (i = 0; i < nr; ++i)
1279 fprintf (mstream, " \\\n\t%s", output_names[i]);
1280 fprintf (mstream, "\n");
1281 fclose (mstream);
1282 if (!jobserver)
1284 /* Avoid passing --jobserver-fd= and similar flags
1285 unless jobserver mode is explicitly enabled. */
1286 putenv (xstrdup ("MAKEFLAGS="));
1287 putenv (xstrdup ("MFLAGS="));
1289 new_argv[0] = getenv ("MAKE");
1290 if (!new_argv[0])
1291 new_argv[0] = "make";
1292 new_argv[1] = "-f";
1293 new_argv[2] = makefile;
1294 i = 3;
1295 if (!jobserver)
1297 snprintf (jobs, 31, "-j%d", parallel);
1298 new_argv[i++] = jobs;
1300 new_argv[i++] = "all";
1301 new_argv[i++] = NULL;
1302 pex = collect_execute (new_argv[0], CONST_CAST (char **, new_argv),
1303 NULL, NULL, PEX_SEARCH, false);
1304 do_wait (new_argv[0], pex);
1305 maybe_unlink (makefile);
1306 makefile = NULL;
1307 for (i = 0; i < nr; ++i)
1308 maybe_unlink (input_names[i]);
1310 for (i = 0; i < nr; ++i)
1312 fputs (output_names[i], stdout);
1313 putc ('\n', stdout);
1314 free (input_names[i]);
1316 nr = 0;
1317 free (output_names);
1318 free (input_names);
1319 free (list_option_full);
1320 obstack_free (&env_obstack, NULL);
1323 finish:
1324 if (offloadend)
1325 printf ("%s\n", offloadend);
1327 XDELETE (lto_argv);
1328 XDELETE (offload_argv);
1329 obstack_free (&argv_obstack, NULL);
1333 /* Entry point. */
1336 main (int argc, char *argv[])
1338 const char *p;
1340 gcc_obstack_init (&opts_obstack);
1342 p = argv[0] + strlen (argv[0]);
1343 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
1344 --p;
1345 progname = p;
1347 xmalloc_set_program_name (progname);
1349 gcc_init_libintl ();
1351 diagnostic_initialize (global_dc, 0);
1353 if (atexit (lto_wrapper_cleanup) != 0)
1354 fatal_error (input_location, "atexit failed");
1356 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1357 signal (SIGINT, fatal_signal);
1358 #ifdef SIGHUP
1359 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1360 signal (SIGHUP, fatal_signal);
1361 #endif
1362 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
1363 signal (SIGTERM, fatal_signal);
1364 #ifdef SIGPIPE
1365 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
1366 signal (SIGPIPE, fatal_signal);
1367 #endif
1368 #ifdef SIGCHLD
1369 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
1370 receive the signal. A different setting is inheritable */
1371 signal (SIGCHLD, SIG_DFL);
1372 #endif
1374 /* We may be called with all the arguments stored in some file and
1375 passed with @file. Expand them into argv before processing. */
1376 expandargv (&argc, &argv);
1378 run_gcc (argc, argv);
1380 return 0;