PR tree-optimization/78496
[official-gcc.git] / gcc / lto-wrapper.c
blob4b86f939ca23512b417834bc275e6465334ba815
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_ffp_contract_:
262 /* For selected options we can merge conservatively. */
263 for (j = 0; j < *decoded_options_count; ++j)
264 if ((*decoded_options)[j].opt_index == foption->opt_index)
265 break;
266 if (j == *decoded_options_count)
267 append_option (decoded_options, decoded_options_count, foption);
268 /* FP_CONTRACT_OFF < FP_CONTRACT_ON < FP_CONTRACT_FAST,
269 -fno-trapv < -ftrapv,
270 -fno-strict-overflow < -fstrict-overflow */
271 else if (foption->value < (*decoded_options)[j].value)
272 (*decoded_options)[j] = *foption;
273 break;
275 case OPT_fmath_errno:
276 case OPT_fsigned_zeros:
277 case OPT_ftrapping_math:
278 case OPT_fwrapv:
279 case OPT_fopenmp:
280 case OPT_fopenacc:
281 case OPT_fcilkplus:
282 case OPT_fcheck_pointer_bounds:
283 /* For selected options we can merge conservatively. */
284 for (j = 0; j < *decoded_options_count; ++j)
285 if ((*decoded_options)[j].opt_index == foption->opt_index)
286 break;
287 if (j == *decoded_options_count)
288 append_option (decoded_options, decoded_options_count, foption);
289 /* -fmath-errno > -fno-math-errno,
290 -fsigned-zeros > -fno-signed-zeros,
291 -ftrapping-math > -fno-trapping-math,
292 -fwrapv > -fno-wrapv. */
293 else if (foption->value > (*decoded_options)[j].value)
294 (*decoded_options)[j] = *foption;
295 break;
297 case OPT_fopenacc_dim_:
298 /* Append or check identical. */
299 for (j = 0; j < *decoded_options_count; ++j)
300 if ((*decoded_options)[j].opt_index == foption->opt_index)
301 break;
302 if (j == *decoded_options_count)
303 append_option (decoded_options, decoded_options_count, foption);
304 else if (strcmp ((*decoded_options)[j].arg, foption->arg))
305 fatal_error (input_location,
306 "Option %s with different values",
307 foption->orig_option_with_args_text);
308 break;
310 case OPT_freg_struct_return:
311 case OPT_fpcc_struct_return:
312 for (j = 0; j < *decoded_options_count; ++j)
313 if ((*decoded_options)[j].opt_index == foption->opt_index)
314 break;
315 if (j == *decoded_options_count)
316 fatal_error (input_location,
317 "Option %s not used consistently in all LTO input"
318 " files", foption->orig_option_with_args_text);
319 break;
321 case OPT_foffload_abi_:
322 for (j = 0; j < *decoded_options_count; ++j)
323 if ((*decoded_options)[j].opt_index == foption->opt_index)
324 break;
325 if (j == *decoded_options_count)
326 append_option (decoded_options, decoded_options_count, foption);
327 else if (foption->value != (*decoded_options)[j].value)
328 fatal_error (input_location,
329 "Option %s not used consistently in all LTO input"
330 " files", foption->orig_option_with_args_text);
331 break;
333 case OPT_O:
334 case OPT_Ofast:
335 case OPT_Og:
336 case OPT_Os:
337 for (j = 0; j < *decoded_options_count; ++j)
338 if ((*decoded_options)[j].opt_index == OPT_O
339 || (*decoded_options)[j].opt_index == OPT_Ofast
340 || (*decoded_options)[j].opt_index == OPT_Og
341 || (*decoded_options)[j].opt_index == OPT_Os)
342 break;
343 if (j == *decoded_options_count)
344 append_option (decoded_options, decoded_options_count, foption);
345 else if ((*decoded_options)[j].opt_index == foption->opt_index
346 && foption->opt_index != OPT_O)
347 /* Exact same options get merged. */
349 else
351 /* For mismatched option kinds preserve the optimization
352 level only, thus merge it as -On. This also handles
353 merging of same optimization level -On. */
354 int level = 0;
355 switch (foption->opt_index)
357 case OPT_O:
358 if (foption->arg[0] == '\0')
359 level = MAX (level, 1);
360 else
361 level = MAX (level, atoi (foption->arg));
362 break;
363 case OPT_Ofast:
364 level = MAX (level, 3);
365 break;
366 case OPT_Og:
367 level = MAX (level, 1);
368 break;
369 case OPT_Os:
370 level = MAX (level, 2);
371 break;
372 default:
373 gcc_unreachable ();
375 switch ((*decoded_options)[j].opt_index)
377 case OPT_O:
378 if ((*decoded_options)[j].arg[0] == '\0')
379 level = MAX (level, 1);
380 else
381 level = MAX (level, atoi ((*decoded_options)[j].arg));
382 break;
383 case OPT_Ofast:
384 level = MAX (level, 3);
385 break;
386 case OPT_Og:
387 level = MAX (level, 1);
388 break;
389 case OPT_Os:
390 level = MAX (level, 2);
391 break;
392 default:
393 gcc_unreachable ();
395 (*decoded_options)[j].opt_index = OPT_O;
396 char *tem;
397 tem = xasprintf ("-O%d", level);
398 (*decoded_options)[j].arg = &tem[2];
399 (*decoded_options)[j].canonical_option[0] = tem;
400 (*decoded_options)[j].value = 1;
402 break;
404 case OPT_foffload_:
405 append_option (decoded_options, decoded_options_count, foption);
406 break;
411 /* Auxiliary function that frees elements of PTR and PTR itself.
412 N is number of elements to be freed. If PTR is NULL, nothing is freed.
413 If an element is NULL, subsequent elements are not freed. */
415 static void **
416 free_array_of_ptrs (void **ptr, unsigned n)
418 if (!ptr)
419 return NULL;
420 for (unsigned i = 0; i < n; i++)
422 if (!ptr[i])
423 break;
424 free (ptr[i]);
426 free (ptr);
427 return NULL;
430 /* Parse STR, saving found tokens into PVALUES and return their number.
431 Tokens are assumed to be delimited by ':'. If APPEND is non-null,
432 append it to every token we find. */
434 static unsigned
435 parse_env_var (const char *str, char ***pvalues, const char *append)
437 const char *curval, *nextval;
438 char **values;
439 unsigned num = 1, i;
441 curval = strchr (str, ':');
442 while (curval)
444 num++;
445 curval = strchr (curval + 1, ':');
448 values = (char**) xmalloc (num * sizeof (char*));
449 curval = str;
450 nextval = strchr (curval, ':');
451 if (nextval == NULL)
452 nextval = strchr (curval, '\0');
454 int append_len = append ? strlen (append) : 0;
455 for (i = 0; i < num; i++)
457 int l = nextval - curval;
458 values[i] = (char*) xmalloc (l + 1 + append_len);
459 memcpy (values[i], curval, l);
460 values[i][l] = 0;
461 if (append)
462 strcat (values[i], append);
463 curval = nextval + 1;
464 nextval = strchr (curval, ':');
465 if (nextval == NULL)
466 nextval = strchr (curval, '\0');
468 *pvalues = values;
469 return num;
472 /* Append options OPTS from lto or offload_lto sections to ARGV_OBSTACK. */
474 static void
475 append_compiler_options (obstack *argv_obstack, struct cl_decoded_option *opts,
476 unsigned int count)
478 /* Append compiler driver arguments as far as they were merged. */
479 for (unsigned int j = 1; j < count; ++j)
481 struct cl_decoded_option *option = &opts[j];
483 /* File options have been properly filtered by lto-opts.c. */
484 switch (option->opt_index)
486 /* Drop arguments that we want to take from the link line. */
487 case OPT_flto_:
488 case OPT_flto:
489 case OPT_flto_partition_:
490 continue;
492 default:
493 break;
496 /* For now do what the original LTO option code was doing - pass
497 on any CL_TARGET flag and a few selected others. */
498 switch (option->opt_index)
500 case OPT_fdiagnostics_show_caret:
501 case OPT_fdiagnostics_show_option:
502 case OPT_fdiagnostics_show_location_:
503 case OPT_fshow_column:
504 case OPT_fPIC:
505 case OPT_fpic:
506 case OPT_fPIE:
507 case OPT_fpie:
508 case OPT_fcommon:
509 case OPT_fexceptions:
510 case OPT_fnon_call_exceptions:
511 case OPT_fgnu_tm:
512 case OPT_freg_struct_return:
513 case OPT_fpcc_struct_return:
514 case OPT_ffp_contract_:
515 case OPT_fmath_errno:
516 case OPT_fsigned_zeros:
517 case OPT_ftrapping_math:
518 case OPT_fwrapv:
519 case OPT_fopenmp:
520 case OPT_fopenacc:
521 case OPT_fopenacc_dim_:
522 case OPT_fcilkplus:
523 case OPT_ftrapv:
524 case OPT_foffload_abi_:
525 case OPT_O:
526 case OPT_Ofast:
527 case OPT_Og:
528 case OPT_Os:
529 case OPT_fcheck_pointer_bounds:
530 break;
532 default:
533 if (!(cl_options[option->opt_index].flags & CL_TARGET))
534 continue;
537 /* Pass the option on. */
538 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
539 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
543 /* Append diag options in OPTS with length COUNT to ARGV_OBSTACK. */
545 static void
546 append_diag_options (obstack *argv_obstack, struct cl_decoded_option *opts,
547 unsigned int count)
549 /* Append compiler driver arguments as far as they were merged. */
550 for (unsigned int j = 1; j < count; ++j)
552 struct cl_decoded_option *option = &opts[j];
554 switch (option->opt_index)
556 case OPT_fdiagnostics_color_:
557 case OPT_fdiagnostics_show_caret:
558 case OPT_fdiagnostics_show_option:
559 case OPT_fdiagnostics_show_location_:
560 case OPT_fshow_column:
561 break;
562 default:
563 continue;
566 /* Pass the option on. */
567 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
568 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
573 /* Append linker options OPTS to ARGV_OBSTACK. */
575 static void
576 append_linker_options (obstack *argv_obstack, struct cl_decoded_option *opts,
577 unsigned int count)
579 /* Append linker driver arguments. Compiler options from the linker
580 driver arguments will override / merge with those from the compiler. */
581 for (unsigned int j = 1; j < count; ++j)
583 struct cl_decoded_option *option = &opts[j];
585 /* Do not pass on frontend specific flags not suitable for lto. */
586 if (!(cl_options[option->opt_index].flags
587 & (CL_COMMON|CL_TARGET|CL_DRIVER|CL_LTO)))
588 continue;
590 switch (option->opt_index)
592 case OPT_o:
593 case OPT_flto_:
594 case OPT_flto:
595 /* We've handled these LTO options, do not pass them on. */
596 continue;
598 case OPT_freg_struct_return:
599 case OPT_fpcc_struct_return:
600 /* Ignore these, they are determined by the input files.
601 ??? We fail to diagnose a possible mismatch here. */
602 continue;
604 case OPT_fopenmp:
605 case OPT_fopenacc:
606 case OPT_fcilkplus:
607 /* Ignore -fno-XXX form of these options, as otherwise
608 corresponding builtins will not be enabled. */
609 if (option->value == 0)
610 continue;
611 break;
613 default:
614 break;
617 /* Pass the option on. */
618 for (unsigned int i = 0; i < option->canonical_option_num_elements; ++i)
619 obstack_ptr_grow (argv_obstack, option->canonical_option[i]);
623 /* Extract options for TARGET offload compiler from OPTIONS and append
624 them to ARGV_OBSTACK. */
626 static void
627 append_offload_options (obstack *argv_obstack, const char *target,
628 struct cl_decoded_option *options,
629 unsigned int options_count)
631 for (unsigned i = 0; i < options_count; i++)
633 const char *cur, *next, *opts;
634 char **argv;
635 unsigned argc;
636 struct cl_decoded_option *option = &options[i];
638 if (option->opt_index != OPT_foffload_)
639 continue;
641 /* If option argument starts with '-' then no target is specified. That
642 means offload options are specified for all targets, so we need to
643 append them. */
644 if (option->arg[0] == '-')
645 opts = option->arg;
646 else
648 opts = strchr (option->arg, '=');
649 /* If there are offload targets specified, but no actual options,
650 there is nothing to do here. */
651 if (!opts)
652 continue;
654 cur = option->arg;
656 while (cur < opts)
658 next = strchr (cur, ',');
659 if (next == NULL)
660 next = opts;
661 next = (next > opts) ? opts : next;
663 /* Are we looking for this offload target? */
664 if (strlen (target) == (size_t) (next - cur)
665 && strncmp (target, cur, next - cur) == 0)
666 break;
668 /* Skip the comma or equal sign. */
669 cur = next + 1;
672 if (cur >= opts)
673 continue;
675 opts++;
678 argv = buildargv (opts);
679 for (argc = 0; argv[argc]; argc++)
680 obstack_ptr_grow (argv_obstack, argv[argc]);
684 /* Check whether NAME can be accessed in MODE. This is like access,
685 except that it never considers directories to be executable. */
687 static int
688 access_check (const char *name, int mode)
690 if (mode == X_OK)
692 struct stat st;
694 if (stat (name, &st) < 0
695 || S_ISDIR (st.st_mode))
696 return -1;
699 return access (name, mode);
702 /* Prepare a target image for offload TARGET, using mkoffload tool from
703 COMPILER_PATH. Return the name of the resultant object file. */
705 static char *
706 compile_offload_image (const char *target, const char *compiler_path,
707 unsigned in_argc, char *in_argv[],
708 struct cl_decoded_option *compiler_opts,
709 unsigned int compiler_opt_count,
710 struct cl_decoded_option *linker_opts,
711 unsigned int linker_opt_count)
713 char *filename = NULL;
714 char **argv;
715 char *suffix
716 = XALLOCAVEC (char, sizeof ("/accel//mkoffload") + strlen (target));
717 strcpy (suffix, "/accel/");
718 strcat (suffix, target);
719 strcat (suffix, "/mkoffload");
721 char **paths = NULL;
722 unsigned n_paths = parse_env_var (compiler_path, &paths, suffix);
724 const char *compiler = NULL;
725 for (unsigned i = 0; i < n_paths; i++)
726 if (access_check (paths[i], X_OK) == 0)
728 compiler = paths[i];
729 break;
732 if (compiler)
734 /* Generate temporary output file name. */
735 filename = make_temp_file (".target.o");
737 struct obstack argv_obstack;
738 obstack_init (&argv_obstack);
739 obstack_ptr_grow (&argv_obstack, compiler);
740 if (save_temps)
741 obstack_ptr_grow (&argv_obstack, "-save-temps");
742 if (verbose)
743 obstack_ptr_grow (&argv_obstack, "-v");
744 obstack_ptr_grow (&argv_obstack, "-o");
745 obstack_ptr_grow (&argv_obstack, filename);
747 /* Append names of input object files. */
748 for (unsigned i = 0; i < in_argc; i++)
749 obstack_ptr_grow (&argv_obstack, in_argv[i]);
751 /* Append options from offload_lto sections. */
752 append_compiler_options (&argv_obstack, compiler_opts,
753 compiler_opt_count);
754 append_diag_options (&argv_obstack, linker_opts, linker_opt_count);
756 /* Append options specified by -foffload last. In case of conflicting
757 options we expect offload compiler to choose the latest. */
758 append_offload_options (&argv_obstack, target, compiler_opts,
759 compiler_opt_count);
760 append_offload_options (&argv_obstack, target, linker_opts,
761 linker_opt_count);
763 obstack_ptr_grow (&argv_obstack, NULL);
764 argv = XOBFINISH (&argv_obstack, char **);
765 fork_execute (argv[0], argv, true);
766 obstack_free (&argv_obstack, NULL);
769 free_array_of_ptrs ((void **) paths, n_paths);
770 return filename;
774 /* The main routine dealing with offloading.
775 The routine builds a target image for each offload target. IN_ARGC and
776 IN_ARGV specify options and input object files. As all of them could contain
777 target sections, we pass them all to target compilers. */
779 static void
780 compile_images_for_offload_targets (unsigned in_argc, char *in_argv[],
781 struct cl_decoded_option *compiler_opts,
782 unsigned int compiler_opt_count,
783 struct cl_decoded_option *linker_opts,
784 unsigned int linker_opt_count)
786 char **names = NULL;
787 const char *target_names = getenv (OFFLOAD_TARGET_NAMES_ENV);
788 if (!target_names)
789 return;
790 unsigned num_targets = parse_env_var (target_names, &names, NULL);
792 int next_name_entry = 0;
793 const char *compiler_path = getenv ("COMPILER_PATH");
794 if (!compiler_path)
795 goto out;
797 /* Prepare an image for each target and save the name of the resultant object
798 file to the OFFLOAD_NAMES array. It is terminated by a NULL entry. */
799 offload_names = XCNEWVEC (char *, num_targets + 1);
800 for (unsigned i = 0; i < num_targets; i++)
802 /* HSA does not use LTO-like streaming and a different compiler, skip
803 it. */
804 if (strcmp (names[i], "hsa") == 0)
805 continue;
807 offload_names[next_name_entry]
808 = compile_offload_image (names[i], compiler_path, in_argc, in_argv,
809 compiler_opts, compiler_opt_count,
810 linker_opts, linker_opt_count);
811 if (!offload_names[next_name_entry])
812 fatal_error (input_location,
813 "problem with building target image for %s\n", names[i]);
814 next_name_entry++;
817 out:
818 free_array_of_ptrs ((void **) names, num_targets);
821 /* Copy a file from SRC to DEST. */
823 static void
824 copy_file (const char *dest, const char *src)
826 FILE *d = fopen (dest, "wb");
827 FILE *s = fopen (src, "rb");
828 char buffer[512];
829 while (!feof (s))
831 size_t len = fread (buffer, 1, 512, s);
832 if (ferror (s) != 0)
833 fatal_error (input_location, "reading input file");
834 if (len > 0)
836 fwrite (buffer, 1, len, d);
837 if (ferror (d) != 0)
838 fatal_error (input_location, "writing output file");
843 /* Find the crtoffloadtable.o file in LIBRARY_PATH, make copy and pass name of
844 the copy to the linker. */
846 static void
847 find_crtoffloadtable (void)
849 char **paths = NULL;
850 const char *library_path = getenv ("LIBRARY_PATH");
851 if (!library_path)
852 return;
853 unsigned n_paths = parse_env_var (library_path, &paths, "/crtoffloadtable.o");
855 unsigned i;
856 for (i = 0; i < n_paths; i++)
857 if (access_check (paths[i], R_OK) == 0)
859 /* The linker will delete the filename we give it, so make a copy. */
860 char *crtoffloadtable = make_temp_file (".crtoffloadtable.o");
861 copy_file (crtoffloadtable, paths[i]);
862 printf ("%s\n", crtoffloadtable);
863 XDELETEVEC (crtoffloadtable);
864 break;
866 if (i == n_paths)
867 fatal_error (input_location,
868 "installation error, can't find crtoffloadtable.o");
870 free_array_of_ptrs ((void **) paths, n_paths);
873 /* A subroutine of run_gcc. Examine the open file FD for lto sections with
874 name prefix PREFIX, at FILE_OFFSET, and store any options we find in OPTS
875 and OPT_COUNT. Return true if we found a matchingn section, false
876 otherwise. COLLECT_GCC holds the value of the environment variable with
877 the same name. */
879 static bool
880 find_and_merge_options (int fd, off_t file_offset, const char *prefix,
881 struct cl_decoded_option **opts,
882 unsigned int *opt_count, const char *collect_gcc)
884 off_t offset, length;
885 char *data;
886 char *fopts;
887 const char *errmsg;
888 int err;
889 struct cl_decoded_option *fdecoded_options = *opts;
890 unsigned int fdecoded_options_count = *opt_count;
892 simple_object_read *sobj;
893 sobj = simple_object_start_read (fd, file_offset, "__GNU_LTO",
894 &errmsg, &err);
895 if (!sobj)
896 return false;
898 char *secname = XALLOCAVEC (char, strlen (prefix) + sizeof (".opts"));
899 strcpy (secname, prefix);
900 strcat (secname, ".opts");
901 if (!simple_object_find_section (sobj, secname, &offset, &length,
902 &errmsg, &err))
904 simple_object_release_read (sobj);
905 return false;
908 lseek (fd, file_offset + offset, SEEK_SET);
909 data = (char *)xmalloc (length);
910 read (fd, data, length);
911 fopts = data;
914 struct cl_decoded_option *f2decoded_options;
915 unsigned int f2decoded_options_count;
916 get_options_from_collect_gcc_options (collect_gcc,
917 fopts, CL_LANG_ALL,
918 &f2decoded_options,
919 &f2decoded_options_count);
920 if (!fdecoded_options)
922 fdecoded_options = f2decoded_options;
923 fdecoded_options_count = f2decoded_options_count;
925 else
926 merge_and_complain (&fdecoded_options,
927 &fdecoded_options_count,
928 f2decoded_options, f2decoded_options_count);
930 fopts += strlen (fopts) + 1;
932 while (fopts - data < length);
934 free (data);
935 simple_object_release_read (sobj);
936 *opts = fdecoded_options;
937 *opt_count = fdecoded_options_count;
938 return true;
941 /* Execute gcc. ARGC is the number of arguments. ARGV contains the arguments. */
943 static void
944 run_gcc (unsigned argc, char *argv[])
946 unsigned i, j;
947 const char **new_argv;
948 const char **argv_ptr;
949 char *list_option_full = NULL;
950 const char *linker_output = NULL;
951 const char *collect_gcc, *collect_gcc_options;
952 int parallel = 0;
953 int jobserver = 0;
954 bool no_partition = false;
955 struct cl_decoded_option *fdecoded_options = NULL;
956 struct cl_decoded_option *offload_fdecoded_options = NULL;
957 unsigned int fdecoded_options_count = 0;
958 unsigned int offload_fdecoded_options_count = 0;
959 struct cl_decoded_option *decoded_options;
960 unsigned int decoded_options_count;
961 struct obstack argv_obstack;
962 int new_head_argc;
963 bool have_lto = false;
964 bool have_offload = false;
965 unsigned lto_argc = 0;
966 char **lto_argv;
968 /* Get the driver and options. */
969 collect_gcc = getenv ("COLLECT_GCC");
970 if (!collect_gcc)
971 fatal_error (input_location,
972 "environment variable COLLECT_GCC must be set");
973 collect_gcc_options = getenv ("COLLECT_GCC_OPTIONS");
974 if (!collect_gcc_options)
975 fatal_error (input_location,
976 "environment variable COLLECT_GCC_OPTIONS must be set");
977 get_options_from_collect_gcc_options (collect_gcc, collect_gcc_options,
978 CL_LANG_ALL,
979 &decoded_options,
980 &decoded_options_count);
982 /* Allocate array for input object files with LTO IL,
983 and for possible preceding arguments. */
984 lto_argv = XNEWVEC (char *, argc);
986 /* Look at saved options in the IL files. */
987 for (i = 1; i < argc; ++i)
989 char *p;
990 int fd;
991 off_t file_offset = 0;
992 long loffset;
993 int consumed;
994 char *filename = argv[i];
996 if (strncmp (argv[i], "-foffload-objects=",
997 sizeof ("-foffload-objects=") - 1) == 0)
999 have_offload = true;
1000 offload_objects_file_name
1001 = argv[i] + sizeof ("-foffload-objects=") - 1;
1002 continue;
1005 if ((p = strrchr (argv[i], '@'))
1006 && p != argv[i]
1007 && sscanf (p, "@%li%n", &loffset, &consumed) >= 1
1008 && strlen (p) == (unsigned int) consumed)
1010 filename = XNEWVEC (char, p - argv[i] + 1);
1011 memcpy (filename, argv[i], p - argv[i]);
1012 filename[p - argv[i]] = '\0';
1013 file_offset = (off_t) loffset;
1015 fd = open (filename, O_RDONLY | O_BINARY);
1016 if (fd == -1)
1018 lto_argv[lto_argc++] = argv[i];
1019 continue;
1022 if (find_and_merge_options (fd, file_offset, LTO_SECTION_NAME_PREFIX,
1023 &fdecoded_options, &fdecoded_options_count,
1024 collect_gcc))
1026 have_lto = true;
1027 lto_argv[lto_argc++] = argv[i];
1029 close (fd);
1032 /* Initalize the common arguments for the driver. */
1033 obstack_init (&argv_obstack);
1034 obstack_ptr_grow (&argv_obstack, collect_gcc);
1035 obstack_ptr_grow (&argv_obstack, "-xlto");
1036 obstack_ptr_grow (&argv_obstack, "-c");
1038 append_compiler_options (&argv_obstack, fdecoded_options,
1039 fdecoded_options_count);
1040 append_linker_options (&argv_obstack, decoded_options, decoded_options_count);
1042 /* Scan linker driver arguments for things that are of relevance to us. */
1043 for (j = 1; j < decoded_options_count; ++j)
1045 struct cl_decoded_option *option = &decoded_options[j];
1046 switch (option->opt_index)
1048 case OPT_o:
1049 linker_output = option->arg;
1050 break;
1052 case OPT_save_temps:
1053 save_temps = 1;
1054 break;
1056 case OPT_v:
1057 verbose = 1;
1058 break;
1060 case OPT_flto_partition_:
1061 if (strcmp (option->arg, "none") == 0)
1062 no_partition = true;
1063 break;
1065 case OPT_flto_:
1066 if (strcmp (option->arg, "jobserver") == 0)
1068 jobserver = 1;
1069 parallel = 1;
1071 else
1073 parallel = atoi (option->arg);
1074 if (parallel <= 1)
1075 parallel = 0;
1077 /* Fallthru. */
1079 case OPT_flto:
1080 lto_mode = LTO_MODE_WHOPR;
1081 break;
1083 default:
1084 break;
1088 if (no_partition)
1090 lto_mode = LTO_MODE_LTO;
1091 jobserver = 0;
1092 parallel = 0;
1095 if (linker_output)
1097 char *output_dir, *base, *name;
1098 bool bit_bucket = strcmp (linker_output, HOST_BIT_BUCKET) == 0;
1100 output_dir = xstrdup (linker_output);
1101 base = output_dir;
1102 for (name = base; *name; name++)
1103 if (IS_DIR_SEPARATOR (*name))
1104 base = name + 1;
1105 *base = '\0';
1107 linker_output = &linker_output[base - output_dir];
1108 if (*output_dir == '\0')
1110 static char current_dir[] = { '.', DIR_SEPARATOR, '\0' };
1111 output_dir = current_dir;
1113 if (!bit_bucket)
1115 obstack_ptr_grow (&argv_obstack, "-dumpdir");
1116 obstack_ptr_grow (&argv_obstack, output_dir);
1119 obstack_ptr_grow (&argv_obstack, "-dumpbase");
1122 /* Remember at which point we can scrub args to re-use the commons. */
1123 new_head_argc = obstack_object_size (&argv_obstack) / sizeof (void *);
1125 if (have_offload)
1127 unsigned i, num_offload_files;
1128 char **offload_argv;
1129 FILE *f;
1131 f = fopen (offload_objects_file_name, "r");
1132 if (f == NULL)
1133 fatal_error (input_location, "cannot open %s: %m",
1134 offload_objects_file_name);
1135 if (fscanf (f, "%u ", &num_offload_files) != 1)
1136 fatal_error (input_location, "cannot read %s: %m",
1137 offload_objects_file_name);
1138 offload_argv = XCNEWVEC (char *, num_offload_files);
1140 /* Read names of object files with offload. */
1141 for (i = 0; i < num_offload_files; i++)
1143 const unsigned piece = 32;
1144 char *buf, *filename = XNEWVEC (char, piece);
1145 size_t len;
1147 buf = filename;
1148 cont1:
1149 if (!fgets (buf, piece, f))
1150 break;
1151 len = strlen (filename);
1152 if (filename[len - 1] != '\n')
1154 filename = XRESIZEVEC (char, filename, len + piece);
1155 buf = filename + len;
1156 goto cont1;
1158 filename[len - 1] = '\0';
1159 offload_argv[i] = filename;
1161 fclose (f);
1162 if (offload_argv[num_offload_files - 1] == NULL)
1163 fatal_error (input_location, "invalid format of %s",
1164 offload_objects_file_name);
1165 maybe_unlink (offload_objects_file_name);
1166 offload_objects_file_name = NULL;
1168 /* Look at saved offload options in files. */
1169 for (i = 0; i < num_offload_files; i++)
1171 char *p;
1172 long loffset;
1173 int fd, consumed;
1174 off_t file_offset = 0;
1175 char *filename = offload_argv[i];
1177 if ((p = strrchr (offload_argv[i], '@'))
1178 && p != offload_argv[i]
1179 && sscanf (p, "@%li%n", &loffset, &consumed) >= 1
1180 && strlen (p) == (unsigned int) consumed)
1182 filename = XNEWVEC (char, p - offload_argv[i] + 1);
1183 memcpy (filename, offload_argv[i], p - offload_argv[i]);
1184 filename[p - offload_argv[i]] = '\0';
1185 file_offset = (off_t) loffset;
1187 fd = open (filename, O_RDONLY | O_BINARY);
1188 if (fd == -1)
1189 fatal_error (input_location, "cannot open %s: %m", filename);
1190 if (!find_and_merge_options (fd, file_offset,
1191 OFFLOAD_SECTION_NAME_PREFIX,
1192 &offload_fdecoded_options,
1193 &offload_fdecoded_options_count,
1194 collect_gcc))
1195 fatal_error (input_location, "cannot read %s: %m", filename);
1196 close (fd);
1197 if (filename != offload_argv[i])
1198 XDELETEVEC (filename);
1201 compile_images_for_offload_targets (num_offload_files, offload_argv,
1202 offload_fdecoded_options,
1203 offload_fdecoded_options_count,
1204 decoded_options,
1205 decoded_options_count);
1207 free_array_of_ptrs ((void **) offload_argv, num_offload_files);
1209 if (offload_names)
1211 find_crtoffloadtable ();
1212 for (i = 0; offload_names[i]; i++)
1213 printf ("%s\n", offload_names[i]);
1214 free_array_of_ptrs ((void **) offload_names, i);
1218 /* If object files contain offload sections, but do not contain LTO sections,
1219 then there is no need to perform a link-time recompilation, i.e.
1220 lto-wrapper is used only for a compilation of offload images. */
1221 if (have_offload && !have_lto)
1222 goto finish;
1224 if (lto_mode == LTO_MODE_LTO)
1226 flto_out = make_temp_file (".lto.o");
1227 if (linker_output)
1228 obstack_ptr_grow (&argv_obstack, linker_output);
1229 obstack_ptr_grow (&argv_obstack, "-o");
1230 obstack_ptr_grow (&argv_obstack, flto_out);
1232 else
1234 const char *list_option = "-fltrans-output-list=";
1235 size_t list_option_len = strlen (list_option);
1236 char *tmp;
1238 if (linker_output)
1240 char *dumpbase = (char *) xmalloc (strlen (linker_output)
1241 + sizeof (".wpa") + 1);
1242 strcpy (dumpbase, linker_output);
1243 strcat (dumpbase, ".wpa");
1244 obstack_ptr_grow (&argv_obstack, dumpbase);
1247 if (linker_output && save_temps)
1249 ltrans_output_file = (char *) xmalloc (strlen (linker_output)
1250 + sizeof (".ltrans.out") + 1);
1251 strcpy (ltrans_output_file, linker_output);
1252 strcat (ltrans_output_file, ".ltrans.out");
1254 else
1255 ltrans_output_file = make_temp_file (".ltrans.out");
1256 list_option_full = (char *) xmalloc (sizeof (char) *
1257 (strlen (ltrans_output_file) + list_option_len + 1));
1258 tmp = list_option_full;
1260 obstack_ptr_grow (&argv_obstack, tmp);
1261 strcpy (tmp, list_option);
1262 tmp += list_option_len;
1263 strcpy (tmp, ltrans_output_file);
1265 if (jobserver)
1266 obstack_ptr_grow (&argv_obstack, xstrdup ("-fwpa=jobserver"));
1267 else if (parallel > 1)
1269 char buf[256];
1270 sprintf (buf, "-fwpa=%i", parallel);
1271 obstack_ptr_grow (&argv_obstack, xstrdup (buf));
1273 else
1274 obstack_ptr_grow (&argv_obstack, "-fwpa");
1277 /* Append the input objects and possible preceding arguments. */
1278 for (i = 0; i < lto_argc; ++i)
1279 obstack_ptr_grow (&argv_obstack, lto_argv[i]);
1280 obstack_ptr_grow (&argv_obstack, NULL);
1282 new_argv = XOBFINISH (&argv_obstack, const char **);
1283 argv_ptr = &new_argv[new_head_argc];
1284 fork_execute (new_argv[0], CONST_CAST (char **, new_argv), true);
1286 if (lto_mode == LTO_MODE_LTO)
1288 printf ("%s\n", flto_out);
1289 free (flto_out);
1290 flto_out = NULL;
1292 else
1294 FILE *stream = fopen (ltrans_output_file, "r");
1295 FILE *mstream = NULL;
1296 struct obstack env_obstack;
1298 if (!stream)
1299 fatal_error (input_location, "fopen: %s: %m", ltrans_output_file);
1301 /* Parse the list of LTRANS inputs from the WPA stage. */
1302 obstack_init (&env_obstack);
1303 nr = 0;
1304 for (;;)
1306 const unsigned piece = 32;
1307 char *output_name = NULL;
1308 char *buf, *input_name = (char *)xmalloc (piece);
1309 size_t len;
1311 buf = input_name;
1312 cont:
1313 if (!fgets (buf, piece, stream))
1314 break;
1315 len = strlen (input_name);
1316 if (input_name[len - 1] != '\n')
1318 input_name = (char *)xrealloc (input_name, len + piece);
1319 buf = input_name + len;
1320 goto cont;
1322 input_name[len - 1] = '\0';
1324 if (input_name[0] == '*')
1325 output_name = &input_name[1];
1327 nr++;
1328 input_names = (char **)xrealloc (input_names, nr * sizeof (char *));
1329 output_names = (char **)xrealloc (output_names, nr * sizeof (char *));
1330 input_names[nr-1] = input_name;
1331 output_names[nr-1] = output_name;
1333 fclose (stream);
1334 maybe_unlink (ltrans_output_file);
1335 ltrans_output_file = NULL;
1337 if (parallel)
1339 makefile = make_temp_file (".mk");
1340 mstream = fopen (makefile, "w");
1343 /* Execute the LTRANS stage for each input file (or prepare a
1344 makefile to invoke this in parallel). */
1345 for (i = 0; i < nr; ++i)
1347 char *output_name;
1348 char *input_name = input_names[i];
1349 /* If it's a pass-through file do nothing. */
1350 if (output_names[i])
1351 continue;
1353 /* Replace the .o suffix with a .ltrans.o suffix and write
1354 the resulting name to the LTRANS output list. */
1355 obstack_grow (&env_obstack, input_name, strlen (input_name) - 2);
1356 obstack_grow (&env_obstack, ".ltrans.o", sizeof (".ltrans.o"));
1357 output_name = XOBFINISH (&env_obstack, char *);
1359 /* Adjust the dumpbase if the linker output file was seen. */
1360 if (linker_output)
1362 char *dumpbase
1363 = (char *) xmalloc (strlen (linker_output)
1364 + sizeof (DUMPBASE_SUFFIX) + 1);
1365 snprintf (dumpbase,
1366 strlen (linker_output) + sizeof (DUMPBASE_SUFFIX),
1367 "%s.ltrans%u", linker_output, i);
1368 argv_ptr[0] = dumpbase;
1371 argv_ptr[1] = "-fltrans";
1372 argv_ptr[2] = "-o";
1373 argv_ptr[3] = output_name;
1374 argv_ptr[4] = input_name;
1375 argv_ptr[5] = NULL;
1376 if (parallel)
1378 fprintf (mstream, "%s:\n\t@%s ", output_name, new_argv[0]);
1379 for (j = 1; new_argv[j] != NULL; ++j)
1380 fprintf (mstream, " '%s'", new_argv[j]);
1381 fprintf (mstream, "\n");
1382 /* If we are not preserving the ltrans input files then
1383 truncate them as soon as we have processed it. This
1384 reduces temporary disk-space usage. */
1385 if (! save_temps)
1386 fprintf (mstream, "\t@-touch -r %s %s.tem > /dev/null 2>&1 "
1387 "&& mv %s.tem %s\n",
1388 input_name, input_name, input_name, input_name);
1390 else
1392 fork_execute (new_argv[0], CONST_CAST (char **, new_argv),
1393 true);
1394 maybe_unlink (input_name);
1397 output_names[i] = output_name;
1399 if (parallel)
1401 struct pex_obj *pex;
1402 char jobs[32];
1404 fprintf (mstream, "all:");
1405 for (i = 0; i < nr; ++i)
1406 fprintf (mstream, " \\\n\t%s", output_names[i]);
1407 fprintf (mstream, "\n");
1408 fclose (mstream);
1409 if (!jobserver)
1411 /* Avoid passing --jobserver-fd= and similar flags
1412 unless jobserver mode is explicitly enabled. */
1413 putenv (xstrdup ("MAKEFLAGS="));
1414 putenv (xstrdup ("MFLAGS="));
1416 new_argv[0] = getenv ("MAKE");
1417 if (!new_argv[0])
1418 new_argv[0] = "make";
1419 new_argv[1] = "-f";
1420 new_argv[2] = makefile;
1421 i = 3;
1422 if (!jobserver)
1424 snprintf (jobs, 31, "-j%d", parallel);
1425 new_argv[i++] = jobs;
1427 new_argv[i++] = "all";
1428 new_argv[i++] = NULL;
1429 pex = collect_execute (new_argv[0], CONST_CAST (char **, new_argv),
1430 NULL, NULL, PEX_SEARCH, false);
1431 do_wait (new_argv[0], pex);
1432 maybe_unlink (makefile);
1433 makefile = NULL;
1434 for (i = 0; i < nr; ++i)
1435 maybe_unlink (input_names[i]);
1437 for (i = 0; i < nr; ++i)
1439 fputs (output_names[i], stdout);
1440 putc ('\n', stdout);
1441 free (input_names[i]);
1443 nr = 0;
1444 free (output_names);
1445 free (input_names);
1446 free (list_option_full);
1447 obstack_free (&env_obstack, NULL);
1450 finish:
1451 XDELETE (lto_argv);
1452 obstack_free (&argv_obstack, NULL);
1456 /* Entry point. */
1459 main (int argc, char *argv[])
1461 const char *p;
1463 init_opts_obstack ();
1465 p = argv[0] + strlen (argv[0]);
1466 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
1467 --p;
1468 progname = p;
1470 xmalloc_set_program_name (progname);
1472 gcc_init_libintl ();
1474 diagnostic_initialize (global_dc, 0);
1476 if (atexit (lto_wrapper_cleanup) != 0)
1477 fatal_error (input_location, "atexit failed");
1479 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
1480 signal (SIGINT, fatal_signal);
1481 #ifdef SIGHUP
1482 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
1483 signal (SIGHUP, fatal_signal);
1484 #endif
1485 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
1486 signal (SIGTERM, fatal_signal);
1487 #ifdef SIGPIPE
1488 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
1489 signal (SIGPIPE, fatal_signal);
1490 #endif
1491 #ifdef SIGCHLD
1492 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
1493 receive the signal. A different setting is inheritable */
1494 signal (SIGCHLD, SIG_DFL);
1495 #endif
1497 /* We may be called with all the arguments stored in some file and
1498 passed with @file. Expand them into argv before processing. */
1499 expandargv (&argc, &argv);
1501 run_gcc (argc, argv);
1503 return 0;