PR testsuite/79036 - gcc.dg/tree-ssa/builtin-sprintf.c fails starting with r244037
[official-gcc.git] / gcc / lto-wrapper.c
blob2c81176913efdab4280aab1080cd07dfb7e016ca
1 /* Wrapper to call lto. Used by collect2 and the linker plugin.
2 Copyright (C) 2009-2017 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 char *offload_objects_file_name;
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 (offload_objects_file_name)
88 maybe_unlink (offload_objects_file_name);
89 if (makefile)
90 maybe_unlink (makefile);
91 for (i = 0; i < nr; ++i)
93 maybe_unlink (input_names[i]);
94 if (output_names[i])
95 maybe_unlink (output_names[i]);
99 static void
100 lto_wrapper_cleanup (void)
102 utils_cleanup (false);
105 /* Unlink a temporary LTRANS file unless requested otherwise. */
107 void
108 maybe_unlink (const char *file)
110 if (!save_temps)
112 if (unlink_if_ordinary (file)
113 && errno != ENOENT)
114 fatal_error (input_location, "deleting LTRANS file %s: %m", file);
116 else if (verbose)
117 fprintf (stderr, "[Leaving LTRANS %s]\n", file);
120 /* Template of LTRANS dumpbase suffix. */
121 #define DUMPBASE_SUFFIX ".ltrans18446744073709551615"
123 /* Create decoded options from the COLLECT_GCC and COLLECT_GCC_OPTIONS
124 environment according to LANG_MASK. */
126 static void
127 get_options_from_collect_gcc_options (const char *collect_gcc,
128 const char *collect_gcc_options,
129 unsigned int lang_mask,
130 struct cl_decoded_option **decoded_options,
131 unsigned int *decoded_options_count)
133 struct obstack argv_obstack;
134 char *argv_storage;
135 const char **argv;
136 int j, k, argc;
138 argv_storage = xstrdup (collect_gcc_options);
139 obstack_init (&argv_obstack);
140 obstack_ptr_grow (&argv_obstack, collect_gcc);
142 for (j = 0, k = 0; argv_storage[j] != '\0'; ++j)
144 if (argv_storage[j] == '\'')
146 obstack_ptr_grow (&argv_obstack, &argv_storage[k]);
147 ++j;
150 if (argv_storage[j] == '\0')
151 fatal_error (input_location, "malformed COLLECT_GCC_OPTIONS");
152 else if (strncmp (&argv_storage[j], "'\\''", 4) == 0)
154 argv_storage[k++] = '\'';
155 j += 4;
157 else if (argv_storage[j] == '\'')
158 break;
159 else
160 argv_storage[k++] = argv_storage[j++];
162 while (1);
163 argv_storage[k++] = '\0';
167 obstack_ptr_grow (&argv_obstack, NULL);
168 argc = obstack_object_size (&argv_obstack) / sizeof (void *) - 1;
169 argv = XOBFINISH (&argv_obstack, const char **);
171 decode_cmdline_options_to_array (argc, (const char **)argv,
172 lang_mask,
173 decoded_options, decoded_options_count);
174 obstack_free (&argv_obstack, NULL);
177 /* Append OPTION to the options array DECODED_OPTIONS with size
178 DECODED_OPTIONS_COUNT. */
180 static void
181 append_option (struct cl_decoded_option **decoded_options,
182 unsigned int *decoded_options_count,
183 struct cl_decoded_option *option)
185 ++*decoded_options_count;
186 *decoded_options
187 = (struct cl_decoded_option *)
188 xrealloc (*decoded_options,
189 (*decoded_options_count
190 * sizeof (struct cl_decoded_option)));
191 memcpy (&(*decoded_options)[*decoded_options_count - 1], option,
192 sizeof (struct cl_decoded_option));
195 /* Try to merge and complain about options FDECODED_OPTIONS when applied
196 ontop of DECODED_OPTIONS. */
198 static void
199 merge_and_complain (struct cl_decoded_option **decoded_options,
200 unsigned int *decoded_options_count,
201 struct cl_decoded_option *fdecoded_options,
202 unsigned int fdecoded_options_count)
204 unsigned int i, j;
206 /* ??? Merge options from files. Most cases can be
207 handled by either unioning or intersecting
208 (for example -fwrapv is a case for unioning,
209 -ffast-math is for intersection). Most complaints
210 about real conflicts between different options can
211 be deferred to the compiler proper. Options that
212 we can neither safely handle by intersection nor
213 unioning would need to be complained about here.
214 Ideally we'd have a flag in the opt files that
215 tells whether to union or intersect or reject.
216 In absence of that it's unclear what a good default is.
217 It's also difficult to get positional handling correct. */
219 /* The following does what the old LTO option code did,
220 union all target and a selected set of common options. */
221 for (i = 0; i < fdecoded_options_count; ++i)
223 struct cl_decoded_option *foption = &fdecoded_options[i];
224 switch (foption->opt_index)
226 case OPT_SPECIAL_unknown:
227 case OPT_SPECIAL_ignore:
228 case OPT_SPECIAL_program_name:
229 case OPT_SPECIAL_input_file:
230 break;
232 default:
233 if (!(cl_options[foption->opt_index].flags & CL_TARGET))
234 break;
236 /* Fallthru. */
237 case OPT_fdiagnostics_show_caret:
238 case OPT_fdiagnostics_show_option:
239 case OPT_fdiagnostics_show_location_:
240 case OPT_fshow_column:
241 case OPT_fPIC:
242 case OPT_fpic:
243 case OPT_fPIE:
244 case OPT_fpie:
245 case OPT_fcommon:
246 case OPT_fexceptions:
247 case OPT_fnon_call_exceptions:
248 case OPT_fgnu_tm:
249 /* Do what the old LTO code did - collect exactly one option
250 setting per OPT code, we pick the first we encounter.
251 ??? This doesn't make too much sense, but when it doesn't
252 then we should complain. */
253 for (j = 0; j < *decoded_options_count; ++j)
254 if ((*decoded_options)[j].opt_index == foption->opt_index)
255 break;
256 if (j == *decoded_options_count)
257 append_option (decoded_options, decoded_options_count, foption);
258 break;
260 case OPT_ftrapv:
261 case OPT_fstrict_overflow:
262 case OPT_ffp_contract_:
263 /* For selected options we can merge conservatively. */
264 for (j = 0; j < *decoded_options_count; ++j)
265 if ((*decoded_options)[j].opt_index == foption->opt_index)
266 break;
267 if (j == *decoded_options_count)
268 append_option (decoded_options, decoded_options_count, foption);
269 /* FP_CONTRACT_OFF < FP_CONTRACT_ON < FP_CONTRACT_FAST,
270 -fno-trapv < -ftrapv,
271 -fno-strict-overflow < -fstrict-overflow */
272 else if (foption->value < (*decoded_options)[j].value)
273 (*decoded_options)[j] = *foption;
274 break;
276 case OPT_fmath_errno:
277 case OPT_fsigned_zeros:
278 case OPT_ftrapping_math:
279 case OPT_fwrapv:
280 case OPT_fopenmp:
281 case OPT_fopenacc:
282 case OPT_fcilkplus:
283 case OPT_fcheck_pointer_bounds:
284 /* For selected options we can merge conservatively. */
285 for (j = 0; j < *decoded_options_count; ++j)
286 if ((*decoded_options)[j].opt_index == foption->opt_index)
287 break;
288 if (j == *decoded_options_count)
289 append_option (decoded_options, decoded_options_count, foption);
290 /* -fmath-errno > -fno-math-errno,
291 -fsigned-zeros > -fno-signed-zeros,
292 -ftrapping-math > -fno-trapping-math,
293 -fwrapv > -fno-wrapv. */
294 else if (foption->value > (*decoded_options)[j].value)
295 (*decoded_options)[j] = *foption;
296 break;
298 case OPT_fopenacc_dim_:
299 /* Append or check identical. */
300 for (j = 0; j < *decoded_options_count; ++j)
301 if ((*decoded_options)[j].opt_index == foption->opt_index)
302 break;
303 if (j == *decoded_options_count)
304 append_option (decoded_options, decoded_options_count, foption);
305 else if (strcmp ((*decoded_options)[j].arg, foption->arg))
306 fatal_error (input_location,
307 "Option %s with different values",
308 foption->orig_option_with_args_text);
309 break;
311 case OPT_freg_struct_return:
312 case OPT_fpcc_struct_return:
313 for (j = 0; j < *decoded_options_count; ++j)
314 if ((*decoded_options)[j].opt_index == foption->opt_index)
315 break;
316 if (j == *decoded_options_count)
317 fatal_error (input_location,
318 "Option %s not used consistently in all LTO input"
319 " files", foption->orig_option_with_args_text);
320 break;
322 case OPT_foffload_abi_:
323 for (j = 0; j < *decoded_options_count; ++j)
324 if ((*decoded_options)[j].opt_index == foption->opt_index)
325 break;
326 if (j == *decoded_options_count)
327 append_option (decoded_options, decoded_options_count, foption);
328 else if (foption->value != (*decoded_options)[j].value)
329 fatal_error (input_location,
330 "Option %s not used consistently in all LTO input"
331 " files", foption->orig_option_with_args_text);
332 break;
334 case OPT_O:
335 case OPT_Ofast:
336 case OPT_Og:
337 case OPT_Os:
338 for (j = 0; j < *decoded_options_count; ++j)
339 if ((*decoded_options)[j].opt_index == OPT_O
340 || (*decoded_options)[j].opt_index == OPT_Ofast
341 || (*decoded_options)[j].opt_index == OPT_Og
342 || (*decoded_options)[j].opt_index == OPT_Os)
343 break;
344 if (j == *decoded_options_count)
345 append_option (decoded_options, decoded_options_count, foption);
346 else if ((*decoded_options)[j].opt_index == foption->opt_index
347 && foption->opt_index != OPT_O)
348 /* Exact same options get merged. */
350 else
352 /* For mismatched option kinds preserve the optimization
353 level only, thus merge it as -On. This also handles
354 merging of same optimization level -On. */
355 int level = 0;
356 switch (foption->opt_index)
358 case OPT_O:
359 if (foption->arg[0] == '\0')
360 level = MAX (level, 1);
361 else
362 level = MAX (level, atoi (foption->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 switch ((*decoded_options)[j].opt_index)
378 case OPT_O:
379 if ((*decoded_options)[j].arg[0] == '\0')
380 level = MAX (level, 1);
381 else
382 level = MAX (level, atoi ((*decoded_options)[j].arg));
383 break;
384 case OPT_Ofast:
385 level = MAX (level, 3);
386 break;
387 case OPT_Og:
388 level = MAX (level, 1);
389 break;
390 case OPT_Os:
391 level = MAX (level, 2);
392 break;
393 default:
394 gcc_unreachable ();
396 (*decoded_options)[j].opt_index = OPT_O;
397 char *tem;
398 tem = xasprintf ("-O%d", level);
399 (*decoded_options)[j].arg = &tem[2];
400 (*decoded_options)[j].canonical_option[0] = tem;
401 (*decoded_options)[j].value = 1;
403 break;
405 case OPT_foffload_:
406 append_option (decoded_options, decoded_options_count, foption);
407 break;
412 /* Auxiliary function that frees elements of PTR and PTR itself.
413 N is number of elements to be freed. If PTR is NULL, nothing is freed.
414 If an element is NULL, subsequent elements are not freed. */
416 static void **
417 free_array_of_ptrs (void **ptr, unsigned n)
419 if (!ptr)
420 return NULL;
421 for (unsigned i = 0; i < n; i++)
423 if (!ptr[i])
424 break;
425 free (ptr[i]);
427 free (ptr);
428 return NULL;
431 /* Parse STR, saving found tokens into PVALUES and return their number.
432 Tokens are assumed to be delimited by ':'. If APPEND is non-null,
433 append it to every token we find. */
435 static unsigned
436 parse_env_var (const char *str, char ***pvalues, const char *append)
438 const char *curval, *nextval;
439 char **values;
440 unsigned num = 1, i;
442 curval = strchr (str, ':');
443 while (curval)
445 num++;
446 curval = strchr (curval + 1, ':');
449 values = (char**) xmalloc (num * sizeof (char*));
450 curval = str;
451 nextval = strchr (curval, ':');
452 if (nextval == NULL)
453 nextval = strchr (curval, '\0');
455 int append_len = append ? strlen (append) : 0;
456 for (i = 0; i < num; i++)
458 int l = nextval - curval;
459 values[i] = (char*) xmalloc (l + 1 + append_len);
460 memcpy (values[i], curval, l);
461 values[i][l] = 0;
462 if (append)
463 strcat (values[i], append);
464 curval = nextval + 1;
465 nextval = strchr (curval, ':');
466 if (nextval == NULL)
467 nextval = strchr (curval, '\0');
469 *pvalues = values;
470 return num;
473 /* Append options OPTS from lto or offload_lto sections to ARGV_OBSTACK. */
475 static void
476 append_compiler_options (obstack *argv_obstack, struct cl_decoded_option *opts,
477 unsigned int count)
479 /* Append compiler driver arguments as far as they were merged. */
480 for (unsigned int j = 1; j < count; ++j)
482 struct cl_decoded_option *option = &opts[j];
484 /* File options have been properly filtered by lto-opts.c. */
485 switch (option->opt_index)
487 /* Drop arguments that we want to take from the link line. */
488 case OPT_flto_:
489 case OPT_flto:
490 case OPT_flto_partition_:
491 continue;
493 default:
494 break;
497 /* For now do what the original LTO option code was doing - pass
498 on any CL_TARGET flag and a few selected others. */
499 switch (option->opt_index)
501 case OPT_fdiagnostics_show_caret:
502 case OPT_fdiagnostics_show_option:
503 case OPT_fdiagnostics_show_location_:
504 case OPT_fshow_column:
505 case OPT_fPIC:
506 case OPT_fpic:
507 case OPT_fPIE:
508 case OPT_fpie:
509 case OPT_fcommon:
510 case OPT_fexceptions:
511 case OPT_fnon_call_exceptions:
512 case OPT_fgnu_tm:
513 case OPT_freg_struct_return:
514 case OPT_fpcc_struct_return:
515 case OPT_ffp_contract_:
516 case OPT_fmath_errno:
517 case OPT_fsigned_zeros:
518 case OPT_ftrapping_math:
519 case OPT_fwrapv:
520 case OPT_fopenmp:
521 case OPT_fopenacc:
522 case OPT_fopenacc_dim_:
523 case OPT_fcilkplus:
524 case OPT_ftrapv:
525 case OPT_fstrict_overflow:
526 case OPT_foffload_abi_:
527 case OPT_O:
528 case OPT_Ofast:
529 case OPT_Og:
530 case OPT_Os:
531 case OPT_fcheck_pointer_bounds:
532 break;
534 default:
535 if (!(cl_options[option->opt_index].flags & CL_TARGET))
536 continue;
539 /* Pass the option on. */
540 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
541 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
545 /* Append diag options in OPTS with length COUNT to ARGV_OBSTACK. */
547 static void
548 append_diag_options (obstack *argv_obstack, struct cl_decoded_option *opts,
549 unsigned int count)
551 /* Append compiler driver arguments as far as they were merged. */
552 for (unsigned int j = 1; j < count; ++j)
554 struct cl_decoded_option *option = &opts[j];
556 switch (option->opt_index)
558 case OPT_fdiagnostics_color_:
559 case OPT_fdiagnostics_show_caret:
560 case OPT_fdiagnostics_show_option:
561 case OPT_fdiagnostics_show_location_:
562 case OPT_fshow_column:
563 break;
564 default:
565 continue;
568 /* Pass the option on. */
569 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
570 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
575 /* Append linker options OPTS to ARGV_OBSTACK. */
577 static void
578 append_linker_options (obstack *argv_obstack, struct cl_decoded_option *opts,
579 unsigned int count)
581 /* Append linker driver arguments. Compiler options from the linker
582 driver arguments will override / merge with those from the compiler. */
583 for (unsigned int j = 1; j < count; ++j)
585 struct cl_decoded_option *option = &opts[j];
587 /* Do not pass on frontend specific flags not suitable for lto. */
588 if (!(cl_options[option->opt_index].flags
589 & (CL_COMMON|CL_TARGET|CL_DRIVER|CL_LTO)))
590 continue;
592 switch (option->opt_index)
594 case OPT_o:
595 case OPT_flto_:
596 case OPT_flto:
597 /* We've handled these LTO options, do not pass them on. */
598 continue;
600 case OPT_freg_struct_return:
601 case OPT_fpcc_struct_return:
602 /* Ignore these, they are determined by the input files.
603 ??? We fail to diagnose a possible mismatch here. */
604 continue;
606 case OPT_fopenmp:
607 case OPT_fopenacc:
608 case OPT_fcilkplus:
609 /* Ignore -fno-XXX form of these options, as otherwise
610 corresponding builtins will not be enabled. */
611 if (option->value == 0)
612 continue;
613 break;
615 default:
616 break;
619 /* Pass the option on. */
620 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
621 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
625 /* Extract options for TARGET offload compiler from OPTIONS and append
626 them to ARGV_OBSTACK. */
628 static void
629 append_offload_options (obstack *argv_obstack, const char *target,
630 struct cl_decoded_option *options,
631 unsigned int options_count)
633 for (unsigned i = 0; i < options_count; i++)
635 const char *cur, *next, *opts;
636 char **argv;
637 unsigned argc;
638 struct cl_decoded_option *option = &options[i];
640 if (option->opt_index != OPT_foffload_)
641 continue;
643 /* If option argument starts with '-' then no target is specified. That
644 means offload options are specified for all targets, so we need to
645 append them. */
646 if (option->arg[0] == '-')
647 opts = option->arg;
648 else
650 opts = strchr (option->arg, '=');
651 /* If there are offload targets specified, but no actual options,
652 there is nothing to do here. */
653 if (!opts)
654 continue;
656 cur = option->arg;
658 while (cur < opts)
660 next = strchr (cur, ',');
661 if (next == NULL)
662 next = opts;
663 next = (next > opts) ? opts : next;
665 /* Are we looking for this offload target? */
666 if (strlen (target) == (size_t) (next - cur)
667 && strncmp (target, cur, next - cur) == 0)
668 break;
670 /* Skip the comma or equal sign. */
671 cur = next + 1;
674 if (cur >= opts)
675 continue;
677 opts++;
680 argv = buildargv (opts);
681 for (argc = 0; argv[argc]; argc++)
682 obstack_ptr_grow (argv_obstack, argv[argc]);
686 /* Check whether NAME can be accessed in MODE. This is like access,
687 except that it never considers directories to be executable. */
689 static int
690 access_check (const char *name, int mode)
692 if (mode == X_OK)
694 struct stat st;
696 if (stat (name, &st) < 0
697 || S_ISDIR (st.st_mode))
698 return -1;
701 return access (name, mode);
704 /* Prepare a target image for offload TARGET, using mkoffload tool from
705 COMPILER_PATH. Return the name of the resultant object file. */
707 static char *
708 compile_offload_image (const char *target, const char *compiler_path,
709 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 *filename = NULL;
716 char **argv;
717 char *suffix
718 = XALLOCAVEC (char, sizeof ("/accel//mkoffload") + strlen (target));
719 strcpy (suffix, "/accel/");
720 strcat (suffix, target);
721 strcat (suffix, "/mkoffload");
723 char **paths = NULL;
724 unsigned n_paths = parse_env_var (compiler_path, &paths, suffix);
726 const char *compiler = NULL;
727 for (unsigned i = 0; i < n_paths; i++)
728 if (access_check (paths[i], X_OK) == 0)
730 compiler = paths[i];
731 break;
734 if (compiler)
736 /* Generate temporary output file name. */
737 filename = make_temp_file (".target.o");
739 struct obstack argv_obstack;
740 obstack_init (&argv_obstack);
741 obstack_ptr_grow (&argv_obstack, compiler);
742 if (save_temps)
743 obstack_ptr_grow (&argv_obstack, "-save-temps");
744 if (verbose)
745 obstack_ptr_grow (&argv_obstack, "-v");
746 obstack_ptr_grow (&argv_obstack, "-o");
747 obstack_ptr_grow (&argv_obstack, filename);
749 /* Append names of input object files. */
750 for (unsigned i = 0; i < in_argc; i++)
751 obstack_ptr_grow (&argv_obstack, in_argv[i]);
753 /* Append options from offload_lto sections. */
754 append_compiler_options (&argv_obstack, compiler_opts,
755 compiler_opt_count);
756 append_diag_options (&argv_obstack, linker_opts, linker_opt_count);
758 /* Append options specified by -foffload last. In case of conflicting
759 options we expect offload compiler to choose the latest. */
760 append_offload_options (&argv_obstack, target, compiler_opts,
761 compiler_opt_count);
762 append_offload_options (&argv_obstack, target, linker_opts,
763 linker_opt_count);
765 obstack_ptr_grow (&argv_obstack, NULL);
766 argv = XOBFINISH (&argv_obstack, char **);
767 fork_execute (argv[0], argv, true);
768 obstack_free (&argv_obstack, NULL);
771 free_array_of_ptrs ((void **) paths, n_paths);
772 return filename;
776 /* The main routine dealing with offloading.
777 The routine builds a target image for each offload target. IN_ARGC and
778 IN_ARGV specify options and input object files. As all of them could contain
779 target sections, we pass them all to target compilers. */
781 static void
782 compile_images_for_offload_targets (unsigned in_argc, char *in_argv[],
783 struct cl_decoded_option *compiler_opts,
784 unsigned int compiler_opt_count,
785 struct cl_decoded_option *linker_opts,
786 unsigned int linker_opt_count)
788 char **names = NULL;
789 const char *target_names = getenv (OFFLOAD_TARGET_NAMES_ENV);
790 if (!target_names)
791 return;
792 unsigned num_targets = parse_env_var (target_names, &names, NULL);
794 int next_name_entry = 0;
795 const char *compiler_path = getenv ("COMPILER_PATH");
796 if (!compiler_path)
797 goto out;
799 /* Prepare an image for each target and save the name of the resultant object
800 file to the OFFLOAD_NAMES array. It is terminated by a NULL entry. */
801 offload_names = XCNEWVEC (char *, num_targets + 1);
802 for (unsigned i = 0; i < num_targets; i++)
804 /* HSA does not use LTO-like streaming and a different compiler, skip
805 it. */
806 if (strcmp (names[i], "hsa") == 0)
807 continue;
809 offload_names[next_name_entry]
810 = compile_offload_image (names[i], compiler_path, in_argc, in_argv,
811 compiler_opts, compiler_opt_count,
812 linker_opts, linker_opt_count);
813 if (!offload_names[next_name_entry])
814 fatal_error (input_location,
815 "problem with building target image for %s\n", names[i]);
816 next_name_entry++;
819 out:
820 free_array_of_ptrs ((void **) names, num_targets);
823 /* Copy a file from SRC to DEST. */
825 static void
826 copy_file (const char *dest, const char *src)
828 FILE *d = fopen (dest, "wb");
829 FILE *s = fopen (src, "rb");
830 char buffer[512];
831 while (!feof (s))
833 size_t len = fread (buffer, 1, 512, s);
834 if (ferror (s) != 0)
835 fatal_error (input_location, "reading input file");
836 if (len > 0)
838 fwrite (buffer, 1, len, d);
839 if (ferror (d) != 0)
840 fatal_error (input_location, "writing output file");
845 /* Find the crtoffloadtable.o file in LIBRARY_PATH, make copy and pass name of
846 the copy to the linker. */
848 static void
849 find_crtoffloadtable (void)
851 char **paths = NULL;
852 const char *library_path = getenv ("LIBRARY_PATH");
853 if (!library_path)
854 return;
855 unsigned n_paths = parse_env_var (library_path, &paths, "/crtoffloadtable.o");
857 unsigned i;
858 for (i = 0; i < n_paths; i++)
859 if (access_check (paths[i], R_OK) == 0)
861 /* The linker will delete the filename we give it, so make a copy. */
862 char *crtoffloadtable = make_temp_file (".crtoffloadtable.o");
863 copy_file (crtoffloadtable, paths[i]);
864 printf ("%s\n", crtoffloadtable);
865 XDELETEVEC (crtoffloadtable);
866 break;
868 if (i == n_paths)
869 fatal_error (input_location,
870 "installation error, can't find crtoffloadtable.o");
872 free_array_of_ptrs ((void **) paths, n_paths);
875 /* A subroutine of run_gcc. Examine the open file FD for lto sections with
876 name prefix PREFIX, at FILE_OFFSET, and store any options we find in OPTS
877 and OPT_COUNT. Return true if we found a matchingn section, false
878 otherwise. COLLECT_GCC holds the value of the environment variable with
879 the same name. */
881 static bool
882 find_and_merge_options (int fd, off_t file_offset, const char *prefix,
883 struct cl_decoded_option **opts,
884 unsigned int *opt_count, const char *collect_gcc)
886 off_t offset, length;
887 char *data;
888 char *fopts;
889 const char *errmsg;
890 int err;
891 struct cl_decoded_option *fdecoded_options = *opts;
892 unsigned int fdecoded_options_count = *opt_count;
894 simple_object_read *sobj;
895 sobj = simple_object_start_read (fd, file_offset, "__GNU_LTO",
896 &errmsg, &err);
897 if (!sobj)
898 return false;
900 char *secname = XALLOCAVEC (char, strlen (prefix) + sizeof (".opts"));
901 strcpy (secname, prefix);
902 strcat (secname, ".opts");
903 if (!simple_object_find_section (sobj, secname, &offset, &length,
904 &errmsg, &err))
906 simple_object_release_read (sobj);
907 return false;
910 lseek (fd, file_offset + offset, SEEK_SET);
911 data = (char *)xmalloc (length);
912 read (fd, data, length);
913 fopts = data;
916 struct cl_decoded_option *f2decoded_options;
917 unsigned int f2decoded_options_count;
918 get_options_from_collect_gcc_options (collect_gcc,
919 fopts, CL_LANG_ALL,
920 &f2decoded_options,
921 &f2decoded_options_count);
922 if (!fdecoded_options)
924 fdecoded_options = f2decoded_options;
925 fdecoded_options_count = f2decoded_options_count;
927 else
928 merge_and_complain (&fdecoded_options,
929 &fdecoded_options_count,
930 f2decoded_options, f2decoded_options_count);
932 fopts += strlen (fopts) + 1;
934 while (fopts - data < length);
936 free (data);
937 simple_object_release_read (sobj);
938 *opts = fdecoded_options;
939 *opt_count = fdecoded_options_count;
940 return true;
943 /* Execute gcc. ARGC is the number of arguments. ARGV contains the arguments. */
945 static void
946 run_gcc (unsigned argc, char *argv[])
948 unsigned i, j;
949 const char **new_argv;
950 const char **argv_ptr;
951 char *list_option_full = NULL;
952 const char *linker_output = NULL;
953 const char *collect_gcc, *collect_gcc_options;
954 int parallel = 0;
955 int jobserver = 0;
956 bool no_partition = false;
957 struct cl_decoded_option *fdecoded_options = NULL;
958 struct cl_decoded_option *offload_fdecoded_options = NULL;
959 unsigned int fdecoded_options_count = 0;
960 unsigned int offload_fdecoded_options_count = 0;
961 struct cl_decoded_option *decoded_options;
962 unsigned int decoded_options_count;
963 struct obstack argv_obstack;
964 int new_head_argc;
965 bool have_lto = false;
966 bool have_offload = false;
967 unsigned lto_argc = 0;
968 char **lto_argv;
970 /* Get the driver and options. */
971 collect_gcc = getenv ("COLLECT_GCC");
972 if (!collect_gcc)
973 fatal_error (input_location,
974 "environment variable COLLECT_GCC must be set");
975 collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
976 if (!collect_gcc_options)
977 fatal_error (input_location,
978 "environment variable COLLECT_GCC_OPTIONS must be set");
979 get_options_from_collect_gcc_options (collect_gcc, collect_gcc_options,
980 CL_LANG_ALL,
981 &decoded_options,
982 &decoded_options_count);
984 /* Allocate array for input object files with LTO IL,
985 and for possible preceding arguments. */
986 lto_argv = XNEWVEC (char *, argc);
988 /* Look at saved options in the IL files. */
989 for (i = 1; i < argc; ++i)
991 char *p;
992 int fd;
993 off_t file_offset = 0;
994 long loffset;
995 int consumed;
996 char *filename = argv[i];
998 if (strncmp (argv[i], "-foffload-objects=",
999 sizeof ("-foffload-objects=") - 1) == 0)
1001 have_offload = true;
1002 offload_objects_file_name
1003 = argv[i] + sizeof ("-foffload-objects=") - 1;
1004 continue;
1007 if ((p = strrchr (argv[i], '@'))
1008 && p != argv[i]
1009 && sscanf (p, "@%li%n", &loffset, &consumed) >= 1
1010 && strlen (p) == (unsigned int) consumed)
1012 filename = XNEWVEC (char, p - argv[i] + 1);
1013 memcpy (filename, argv[i], p - argv[i]);
1014 filename[p - argv[i]] = '\0';
1015 file_offset = (off_t) loffset;
1017 fd = open (filename, O_RDONLY | O_BINARY);
1018 if (fd == -1)
1020 lto_argv[lto_argc++] = argv[i];
1021 continue;
1024 if (find_and_merge_options (fd, file_offset, LTO_SECTION_NAME_PREFIX,
1025 &fdecoded_options, &fdecoded_options_count,
1026 collect_gcc))
1028 have_lto = true;
1029 lto_argv[lto_argc++] = argv[i];
1031 close (fd);
1034 /* Initalize the common arguments for the driver. */
1035 obstack_init (&argv_obstack);
1036 obstack_ptr_grow (&argv_obstack, collect_gcc);
1037 obstack_ptr_grow (&argv_obstack, "-xlto");
1038 obstack_ptr_grow (&argv_obstack, "-c");
1040 append_compiler_options (&argv_obstack, fdecoded_options,
1041 fdecoded_options_count);
1042 append_linker_options (&argv_obstack, decoded_options, decoded_options_count);
1044 /* Scan linker driver arguments for things that are of relevance to us. */
1045 for (j = 1; j < decoded_options_count; ++j)
1047 struct cl_decoded_option *option = &decoded_options[j];
1048 switch (option->opt_index)
1050 case OPT_o:
1051 linker_output = option->arg;
1052 break;
1054 case OPT_save_temps:
1055 save_temps = 1;
1056 break;
1058 case OPT_v:
1059 verbose = 1;
1060 break;
1062 case OPT_flto_partition_:
1063 if (strcmp (option->arg, "none") == 0)
1064 no_partition = true;
1065 break;
1067 case OPT_flto_:
1068 if (strcmp (option->arg, "jobserver") == 0)
1070 jobserver = 1;
1071 parallel = 1;
1073 else
1075 parallel = atoi (option->arg);
1076 if (parallel <= 1)
1077 parallel = 0;
1079 /* Fallthru. */
1081 case OPT_flto:
1082 lto_mode = LTO_MODE_WHOPR;
1083 break;
1085 default:
1086 break;
1090 if (no_partition)
1092 lto_mode = LTO_MODE_LTO;
1093 jobserver = 0;
1094 parallel = 0;
1097 if (linker_output)
1099 char *output_dir, *base, *name;
1100 bool bit_bucket = strcmp (linker_output, HOST_BIT_BUCKET) == 0;
1102 output_dir = xstrdup (linker_output);
1103 base = output_dir;
1104 for (name = base; *name; name++)
1105 if (IS_DIR_SEPARATOR (*name))
1106 base = name + 1;
1107 *base = '\0';
1109 linker_output = &linker_output[base - output_dir];
1110 if (*output_dir == '\0')
1112 static char current_dir[] = { '.', DIR_SEPARATOR, '\0' };
1113 output_dir = current_dir;
1115 if (!bit_bucket)
1117 obstack_ptr_grow (&argv_obstack, "-dumpdir");
1118 obstack_ptr_grow (&argv_obstack, output_dir);
1121 obstack_ptr_grow (&argv_obstack, "-dumpbase");
1124 /* Remember at which point we can scrub args to re-use the commons. */
1125 new_head_argc = obstack_object_size (&argv_obstack) / sizeof (void *);
1127 if (have_offload)
1129 unsigned i, num_offload_files;
1130 char **offload_argv;
1131 FILE *f;
1133 f = fopen (offload_objects_file_name, "r");
1134 if (f == NULL)
1135 fatal_error (input_location, "cannot open %s: %m",
1136 offload_objects_file_name);
1137 if (fscanf (f, "%u ", &num_offload_files) != 1)
1138 fatal_error (input_location, "cannot read %s: %m",
1139 offload_objects_file_name);
1140 offload_argv = XCNEWVEC (char *, num_offload_files);
1142 /* Read names of object files with offload. */
1143 for (i = 0; i < num_offload_files; i++)
1145 const unsigned piece = 32;
1146 char *buf, *filename = XNEWVEC (char, piece);
1147 size_t len;
1149 buf = filename;
1150 cont1:
1151 if (!fgets (buf, piece, f))
1152 break;
1153 len = strlen (filename);
1154 if (filename[len - 1] != '\n')
1156 filename = XRESIZEVEC (char, filename, len + piece);
1157 buf = filename + len;
1158 goto cont1;
1160 filename[len - 1] = '\0';
1161 offload_argv[i] = filename;
1163 fclose (f);
1164 if (offload_argv[num_offload_files - 1] == NULL)
1165 fatal_error (input_location, "invalid format of %s",
1166 offload_objects_file_name);
1167 maybe_unlink (offload_objects_file_name);
1168 offload_objects_file_name = NULL;
1170 /* Look at saved offload options in files. */
1171 for (i = 0; i < num_offload_files; i++)
1173 char *p;
1174 long loffset;
1175 int fd, consumed;
1176 off_t file_offset = 0;
1177 char *filename = offload_argv[i];
1179 if ((p = strrchr (offload_argv[i], '@'))
1180 && p != offload_argv[i]
1181 && sscanf (p, "@%li%n", &loffset, &consumed) >= 1
1182 && strlen (p) == (unsigned int) consumed)
1184 filename = XNEWVEC (char, p - offload_argv[i] + 1);
1185 memcpy (filename, offload_argv[i], p - offload_argv[i]);
1186 filename[p - offload_argv[i]] = '\0';
1187 file_offset = (off_t) loffset;
1189 fd = open (filename, O_RDONLY | O_BINARY);
1190 if (fd == -1)
1191 fatal_error (input_location, "cannot open %s: %m", filename);
1192 if (!find_and_merge_options (fd, file_offset,
1193 OFFLOAD_SECTION_NAME_PREFIX,
1194 &offload_fdecoded_options,
1195 &offload_fdecoded_options_count,
1196 collect_gcc))
1197 fatal_error (input_location, "cannot read %s: %m", filename);
1198 close (fd);
1199 if (filename != offload_argv[i])
1200 XDELETEVEC (filename);
1203 compile_images_for_offload_targets (num_offload_files, offload_argv,
1204 offload_fdecoded_options,
1205 offload_fdecoded_options_count,
1206 decoded_options,
1207 decoded_options_count);
1209 free_array_of_ptrs ((void **) offload_argv, num_offload_files);
1211 if (offload_names)
1213 find_crtoffloadtable ();
1214 for (i = 0; offload_names[i]; i++)
1215 printf ("%s\n", offload_names[i]);
1216 free_array_of_ptrs ((void **) offload_names, i);
1220 /* If object files contain offload sections, but do not contain LTO sections,
1221 then there is no need to perform a link-time recompilation, i.e.
1222 lto-wrapper is used only for a compilation of offload images. */
1223 if (have_offload && !have_lto)
1224 goto finish;
1226 if (lto_mode == LTO_MODE_LTO)
1228 flto_out = make_temp_file (".lto.o");
1229 if (linker_output)
1230 obstack_ptr_grow (&argv_obstack, linker_output);
1231 obstack_ptr_grow (&argv_obstack, "-o");
1232 obstack_ptr_grow (&argv_obstack, flto_out);
1234 else
1236 const char *list_option = "-fltrans-output-list=";
1237 size_t list_option_len = strlen (list_option);
1238 char *tmp;
1240 if (linker_output)
1242 char *dumpbase = (char *) xmalloc (strlen (linker_output)
1243 + sizeof (".wpa") + 1);
1244 strcpy (dumpbase, linker_output);
1245 strcat (dumpbase, ".wpa");
1246 obstack_ptr_grow (&argv_obstack, dumpbase);
1249 if (linker_output && save_temps)
1251 ltrans_output_file = (char *) xmalloc (strlen (linker_output)
1252 + sizeof (".ltrans.out") + 1);
1253 strcpy (ltrans_output_file, linker_output);
1254 strcat (ltrans_output_file, ".ltrans.out");
1256 else
1257 ltrans_output_file = make_temp_file (".ltrans.out");
1258 list_option_full = (char *) xmalloc (sizeof (char) *
1259 (strlen (ltrans_output_file) + list_option_len + 1));
1260 tmp = list_option_full;
1262 obstack_ptr_grow (&argv_obstack, tmp);
1263 strcpy (tmp, list_option);
1264 tmp += list_option_len;
1265 strcpy (tmp, ltrans_output_file);
1267 if (jobserver)
1268 obstack_ptr_grow (&argv_obstack, xstrdup ("-fwpa=jobserver"));
1269 else if (parallel > 1)
1271 char buf[256];
1272 sprintf (buf, "-fwpa=%i", parallel);
1273 obstack_ptr_grow (&argv_obstack, xstrdup (buf));
1275 else
1276 obstack_ptr_grow (&argv_obstack, "-fwpa");
1279 /* Append the input objects and possible preceding arguments. */
1280 for (i = 0; i < lto_argc; ++i)
1281 obstack_ptr_grow (&argv_obstack, lto_argv[i]);
1282 obstack_ptr_grow (&argv_obstack, NULL);
1284 new_argv = XOBFINISH (&argv_obstack, const char **);
1285 argv_ptr = &new_argv[new_head_argc];
1286 fork_execute (new_argv[0], CONST_CAST (char **, new_argv), true);
1288 if (lto_mode == LTO_MODE_LTO)
1290 printf ("%s\n", flto_out);
1291 free (flto_out);
1292 flto_out = NULL;
1294 else
1296 FILE *stream = fopen (ltrans_output_file, "r");
1297 FILE *mstream = NULL;
1298 struct obstack env_obstack;
1300 if (!stream)
1301 fatal_error (input_location, "fopen: %s: %m", ltrans_output_file);
1303 /* Parse the list of LTRANS inputs from the WPA stage. */
1304 obstack_init (&env_obstack);
1305 nr = 0;
1306 for (;;)
1308 const unsigned piece = 32;
1309 char *output_name = NULL;
1310 char *buf, *input_name = (char *)xmalloc (piece);
1311 size_t len;
1313 buf = input_name;
1314 cont:
1315 if (!fgets (buf, piece, stream))
1316 break;
1317 len = strlen (input_name);
1318 if (input_name[len - 1] != '\n')
1320 input_name = (char *)xrealloc (input_name, len + piece);
1321 buf = input_name + len;
1322 goto cont;
1324 input_name[len - 1] = '\0';
1326 if (input_name[0] == '*')
1327 output_name = &input_name[1];
1329 nr++;
1330 input_names = (char **)xrealloc (input_names, nr * sizeof (char *));
1331 output_names = (char **)xrealloc (output_names, nr * sizeof (char *));
1332 input_names[nr-1] = input_name;
1333 output_names[nr-1] = output_name;
1335 fclose (stream);
1336 maybe_unlink (ltrans_output_file);
1337 ltrans_output_file = NULL;
1339 if (parallel)
1341 makefile = make_temp_file (".mk");
1342 mstream = fopen (makefile, "w");
1345 /* Execute the LTRANS stage for each input file (or prepare a
1346 makefile to invoke this in parallel). */
1347 for (i = 0; i < nr; ++i)
1349 char *output_name;
1350 char *input_name = input_names[i];
1351 /* If it's a pass-through file do nothing. */
1352 if (output_names[i])
1353 continue;
1355 /* Replace the .o suffix with a .ltrans.o suffix and write
1356 the resulting name to the LTRANS output list. */
1357 obstack_grow (&env_obstack, input_name, strlen (input_name) - 2);
1358 obstack_grow (&env_obstack, ".ltrans.o", sizeof (".ltrans.o"));
1359 output_name = XOBFINISH (&env_obstack, char *);
1361 /* Adjust the dumpbase if the linker output file was seen. */
1362 if (linker_output)
1364 char *dumpbase
1365 = (char *) xmalloc (strlen (linker_output)
1366 + sizeof (DUMPBASE_SUFFIX) + 1);
1367 snprintf (dumpbase,
1368 strlen (linker_output) + sizeof (DUMPBASE_SUFFIX),
1369 "%s.ltrans%u", linker_output, i);
1370 argv_ptr[0] = dumpbase;
1373 argv_ptr[1] = "-fltrans";
1374 argv_ptr[2] = "-o";
1375 argv_ptr[3] = output_name;
1376 argv_ptr[4] = input_name;
1377 argv_ptr[5] = NULL;
1378 if (parallel)
1380 fprintf (mstream, "%s:\n\t@%s ", output_name, new_argv[0]);
1381 for (j = 1; new_argv[j] != NULL; ++j)
1382 fprintf (mstream, " '%s'", new_argv[j]);
1383 fprintf (mstream, "\n");
1384 /* If we are not preserving the ltrans input files then
1385 truncate them as soon as we have processed it. This
1386 reduces temporary disk-space usage. */
1387 if (! save_temps)
1388 fprintf (mstream, "\t@-touch -r %s %s.tem > /dev/null 2>&1 "
1389 "&& mv %s.tem %s\n",
1390 input_name, input_name, input_name, input_name);
1392 else
1394 fork_execute (new_argv[0], CONST_CAST (char **, new_argv),
1395 true);
1396 maybe_unlink (input_name);
1399 output_names[i] = output_name;
1401 if (parallel)
1403 struct pex_obj *pex;
1404 char jobs[32];
1406 fprintf (mstream, "all:");
1407 for (i = 0; i < nr; ++i)
1408 fprintf (mstream, " \\\n\t%s", output_names[i]);
1409 fprintf (mstream, "\n");
1410 fclose (mstream);
1411 if (!jobserver)
1413 /* Avoid passing --jobserver-fd= and similar flags
1414 unless jobserver mode is explicitly enabled. */
1415 putenv (xstrdup ("MAKEFLAGS="));
1416 putenv (xstrdup ("MFLAGS="));
1418 new_argv[0] = getenv ("MAKE");
1419 if (!new_argv[0])
1420 new_argv[0] = "make";
1421 new_argv[1] = "-f";
1422 new_argv[2] = makefile;
1423 i = 3;
1424 if (!jobserver)
1426 snprintf (jobs, 31, "-j%d", parallel);
1427 new_argv[i++] = jobs;
1429 new_argv[i++] = "all";
1430 new_argv[i++] = NULL;
1431 pex = collect_execute (new_argv[0], CONST_CAST (char **, new_argv),
1432 NULL, NULL, PEX_SEARCH, false);
1433 do_wait (new_argv[0], pex);
1434 maybe_unlink (makefile);
1435 makefile = NULL;
1436 for (i = 0; i < nr; ++i)
1437 maybe_unlink (input_names[i]);
1439 for (i = 0; i < nr; ++i)
1441 fputs (output_names[i], stdout);
1442 putc ('\n', stdout);
1443 free (input_names[i]);
1445 nr = 0;
1446 free (output_names);
1447 free (input_names);
1448 free (list_option_full);
1449 obstack_free (&env_obstack, NULL);
1452 finish:
1453 XDELETE (lto_argv);
1454 obstack_free (&argv_obstack, NULL);
1458 /* Entry point. */
1461 main (int argc, char *argv[])
1463 const char *p;
1465 init_opts_obstack ();
1467 p = argv[0] + strlen (argv[0]);
1468 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
1469 --p;
1470 progname = p;
1472 xmalloc_set_program_name (progname);
1474 gcc_init_libintl ();
1476 diagnostic_initialize (global_dc, 0);
1478 if (atexit (lto_wrapper_cleanup) != 0)
1479 fatal_error (input_location, "atexit failed");
1481 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1482 signal (SIGINT, fatal_signal);
1483 #ifdef SIGHUP
1484 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1485 signal (SIGHUP, fatal_signal);
1486 #endif
1487 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
1488 signal (SIGTERM, fatal_signal);
1489 #ifdef SIGPIPE
1490 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
1491 signal (SIGPIPE, fatal_signal);
1492 #endif
1493 #ifdef SIGCHLD
1494 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
1495 receive the signal. A different setting is inheritable */
1496 signal (SIGCHLD, SIG_DFL);
1497 #endif
1499 /* We may be called with all the arguments stored in some file and
1500 passed with @file. Expand them into argv before processing. */
1501 expandargv (&argc, &argv);
1503 run_gcc (argc, argv);
1505 return 0;