Skip to main content

cuno_toolchain/flags/
link.rs

1//! The link step's arguments, row by row from `docs/en/specs/build.md`,
2//! "Settings and flags". Linking goes through the compiler driver, so each
3//! driver adds its own C runtime libraries.
4
5use std::ffi::OsString;
6use std::path::{Path, PathBuf};
7
8use super::{BuildSettings, OptLevel, ProfileSettings, Subsystem, TARGET_SWITCH};
9use crate::Version;
10use crate::compiler::{CompilerKind, Family};
11
12/// What one link of the build is made from.
13#[derive(Clone, Copy, Debug)]
14pub struct LinkInput<'a> {
15    /// The driver.
16    pub kind: CompilerKind,
17    /// Its version: GCC links `libstdc++exp` from 14 (`build.md`, "Settings
18    /// and flags").
19    pub version: Version,
20    /// The resolved build settings (`links`, `lib-dirs`, `link-flags`).
21    pub build: &'a BuildSettings,
22    /// The resolved profile (`debug-info`, `lto`, and `opt-level` for LTO).
23    pub profile: &'a ProfileSettings,
24    /// What the link makes.
25    pub output: Linked<'a>,
26    /// Whether any of its objects is C++, which GCC links with `g++` and
27    /// its C++ runtime.
28    pub cxx: bool,
29}
30
31/// What a link makes (`docs/en/specs/build.md`, "Linking" and "Building a
32/// library").
33#[derive(Clone, Copy, Debug)]
34pub enum Linked<'a> {
35    /// An executable, started as its `[[bin]] subsystem` says.
36    Executable {
37        /// Its `[[bin]] subsystem`.
38        subsystem: Subsystem,
39        /// Whether it links the body of a shared library's package, which
40        /// exports, so that it is told to write no import library of its
41        /// own (`docs/en/specs/build.md`, "Linking").
42        of_shared: bool,
43    },
44    /// A DLL, with its import library at `import` and, with debug
45    /// information, its PDB at `pdb`: both beside the static libraries
46    /// rather than the DLL, where an executable of the same name would write
47    /// its own.
48    Shared {
49        /// The import library.
50        import: &'a Path,
51        /// The program database.
52        pdb: &'a Path,
53    },
54}
55
56/// The files the linker may take `lib` from, for a `links` entry built
57/// with `kind`, in the order it tries them in each directory: `<lib>.lib`
58/// for the compilers that build for the MSVC ABI (the MSVC and clang-cl
59/// link commands name it, clang's `-l<lib>` is found as it by lld), and
60/// the seven names MinGW's `ld` tries for `-l<lib>` (as `-Wl,--verbose`
61/// lists its attempts). The
62/// build looks for them in `lib-dirs` to relink when one changes
63/// (`docs/en/specs/build.md`, "Deciding what changed"), so a compiler
64/// naming libraries otherwise answers here.
65pub fn library_files(kind: CompilerKind, lib: &str) -> Vec<String> {
66    match kind {
67        CompilerKind::Msvc | CompilerKind::ClangCl | CompilerKind::Clang => {
68            vec![format!("{lib}.lib")]
69        }
70        CompilerKind::Gcc => vec![
71            format!("lib{lib}.dll.a"),
72            format!("{lib}.dll.a"),
73            format!("lib{lib}.a"),
74            format!("{lib}.lib"),
75            format!("lib{lib}.lib"),
76            format!("lib{lib}.dll"),
77            format!("{lib}.dll"),
78        ],
79    }
80}
81
82/// What makes GCC link its own runtime and `winpthread` statically, for
83/// either `runtime` (`docs/en/specs/build.md`, "Settings and flags"): their
84/// DLLs are not part of Windows. `-lstdc++` comes before `-lwinpthread`,
85/// which resolves what libstdc++ uses; `-Bdynamic` after them leaves the
86/// libraries the driver adds (UCRT's) as they are. From GCC 14, C++ also
87/// links `libstdc++exp`, where MinGW's libstdc++ keeps what `std::print`
88/// writes to a terminal with; before 14 there is no `<print>` to need it.
89fn gcc_runtime_args(cxx: bool, version: Version) -> Vec<&'static str> {
90    let mut args = vec!["-static-libgcc"];
91    if cxx {
92        args.push("-static-libstdc++");
93    }
94    args.push("-Wl,-Bstatic");
95    if cxx {
96        if version.major >= 14 {
97            args.push("-lstdc++exp");
98        }
99        args.push("-lstdc++");
100    }
101    args.extend(["-lwinpthread", "-Wl,-Bdynamic"]);
102    args
103}
104
105/// The arguments for the driver to link `objects` into `exe` (or the DLL,
106/// as `input.output` says): the driver's own switches, the objects and the
107/// output, then the linker's arguments (after `/link` for MSVC and
108/// clang-cl), with `link-flags` last. Arguments that carry a path go to the
109/// linker with `-Xlinker` rather than `-Wl,`, which splits at commas.
110pub fn link_args(input: &LinkInput<'_>, objects: &[PathBuf], exe: &Path) -> Vec<OsString> {
111    let build = input.build;
112    let profile = input.profile;
113    // lld optimises at level 2 when it runs LTO unless told the level.
114    let lto_level = match profile.opt_level {
115        OptLevel::O0 => "0",
116        OptLevel::O1 => "1",
117        OptLevel::O2 | OptLevel::Size => "2",
118        OptLevel::O3 => "3",
119    };
120    let mut args: Vec<OsString> = Vec::new();
121    let push = |args: &mut Vec<OsString>, flags: &[&str]| {
122        args.extend(flags.iter().map(OsString::from));
123    };
124
125    let shared = match input.output {
126        Linked::Executable { .. } => None,
127        Linked::Shared { import, pdb } => Some((import, pdb)),
128    };
129    match input.kind {
130        CompilerKind::Msvc | CompilerKind::ClangCl if shared.is_some() => {
131            push(&mut args, &["/LD"]);
132        }
133        CompilerKind::Clang | CompilerKind::Gcc if shared.is_some() => {
134            push(&mut args, &["-shared"]);
135        }
136        CompilerKind::Msvc | CompilerKind::ClangCl | CompilerKind::Clang | CompilerKind::Gcc => {}
137    }
138    match input.kind {
139        CompilerKind::Msvc => push(&mut args, &["/nologo"]),
140        CompilerKind::ClangCl => {
141            push(&mut args, &["/nologo", "-fuse-ld=lld"]);
142            if profile.lto {
143                push(&mut args, &["-flto"]);
144            }
145        }
146        CompilerKind::Clang => {
147            // `-fms-runtime-lib` is left out: the objects already say which C
148            // runtime they use, and the linker follows them.
149            push(&mut args, &[TARGET_SWITCH, "-fuse-ld=lld"]);
150            if profile.debug_info {
151                push(&mut args, &["-g"]);
152            }
153            if profile.lto {
154                push(&mut args, &["-flto"]);
155            }
156        }
157        CompilerKind::Gcc => {
158            if profile.debug_info {
159                push(&mut args, &["-g"]);
160            }
161            // At link time GCC optimises at the level the objects were
162            // compiled at, so no level is given; `auto` runs it in
163            // parallel, where plain `-flto` warns that it runs serially.
164            if profile.lto {
165                push(&mut args, &["-flto=auto"]);
166            }
167        }
168    }
169
170    args.extend(objects.iter().map(OsString::from));
171
172    match input.kind {
173        // The GNU-style drivers: clang linking with lld for the MSVC ABI,
174        // and MinGW's GCC with its own ld.
175        CompilerKind::Clang | CompilerKind::Gcc => {
176            args.extend(["-o".into(), exe.into()]);
177            for lib in &build.links {
178                args.push(format!("-l{lib}").into());
179            }
180            for dir in &build.lib_dirs {
181                let mut arg = OsString::from("-L");
182                arg.push(dir);
183                args.push(arg);
184            }
185            let gcc = input.kind == CompilerKind::Gcc;
186            match (input.output, gcc) {
187                (
188                    Linked::Executable {
189                        subsystem,
190                        of_shared,
191                    },
192                    gcc,
193                ) => {
194                    push(
195                        &mut args,
196                        match (subsystem, gcc) {
197                            (Subsystem::Console, false) => &["-Wl,/subsystem:console"][..],
198                            (Subsystem::Windows, false) => {
199                                &["-Wl,/subsystem:windows", "-Wl,/entry:mainCRTStartup"]
200                            }
201                            // MinGW's start-up code calls `main` for either.
202                            (Subsystem::Console, true) => &["-mconsole"],
203                            (Subsystem::Windows, true) => &["-mwindows"],
204                        },
205                    );
206                    // lld would write an import library of the executable's
207                    // name; `ld` writes none unless asked.
208                    if of_shared && !gcc {
209                        push(&mut args, &["-Wl,/noimplib"]);
210                    }
211                }
212                (Linked::Shared { import, .. }, true) => {
213                    args.extend(["-Xlinker".into(), "--out-implib".into()]);
214                    args.extend(["-Xlinker".into(), import.into()]);
215                }
216                (Linked::Shared { import, pdb }, false) => {
217                    let mut arg = OsString::from("/implib:");
218                    arg.push(import);
219                    args.extend(["-Xlinker".into(), arg]);
220                    if profile.debug_info {
221                        let mut arg = OsString::from("/pdb:");
222                        arg.push(pdb);
223                        args.extend(["-Xlinker".into(), arg]);
224                    }
225                }
226            }
227            if gcc {
228                push(&mut args, &gcc_runtime_args(input.cxx, input.version));
229            } else if profile.lto {
230                args.push(format!("-Wl,/opt:lldlto={lto_level}").into());
231            }
232            // `-Xlinker`, not `-Wl,`, which would split a flag at its commas.
233            for flag in &build.link_flags {
234                args.extend(["-Xlinker".into(), flag.into()]);
235            }
236            return args;
237        }
238        CompilerKind::Msvc | CompilerKind::ClangCl => {}
239    }
240
241    let mut out = OsString::from("/Fe:");
242    out.push(exe);
243    args.push(out);
244    // Everything after `/link` goes to the linker itself.
245    args.push("/link".into());
246    for lib in &build.links {
247        // The first name is the one cl and clang-cl are given.
248        args.push(library_files(input.kind, lib).remove(0).into());
249    }
250    for dir in &build.lib_dirs {
251        let mut arg = OsString::from("/LIBPATH:");
252        arg.push(dir);
253        args.push(arg);
254    }
255    match input.output {
256        Linked::Executable {
257            subsystem,
258            of_shared,
259        } => {
260            // Stated for console too: otherwise a program with `WinMain` and
261            // no `main` is silently linked as a GUI program.
262            push(
263                &mut args,
264                match subsystem {
265                    Subsystem::Console => &["/SUBSYSTEM:CONSOLE"][..],
266                    Subsystem::Windows => &["/SUBSYSTEM:WINDOWS", "/ENTRY:mainCRTStartup"],
267                },
268            );
269            // An executable of a shared library's package links the body,
270            // which exports; the linker would write, and link.exe announce,
271            // an import library (and link.exe an `.exp`) of the executable's
272            // name. Only there: elsewhere a user's `/IMPLIB` must still work,
273            // and lld lets `/NOIMPLIB` win over it (build.md, "Linking").
274            if of_shared {
275                push(
276                    &mut args,
277                    match input.kind.family() {
278                        Family::Msvc => &["/NOIMPLIB", "/NOEXP"][..],
279                        Family::Llvm | Family::Gnu => &["/NOIMPLIB"],
280                    },
281                );
282            }
283        }
284        Linked::Shared { import, pdb } => {
285            let mut arg = OsString::from("/IMPLIB:");
286            arg.push(import);
287            args.push(arg);
288            if profile.debug_info {
289                let mut arg = OsString::from("/PDB:");
290                arg.push(pdb);
291                args.push(arg);
292            }
293        }
294    }
295    if profile.debug_info {
296        push(&mut args, &["/DEBUG"]);
297        match input.kind.family() {
298            // link.exe links incrementally under /DEBUG; lld does not.
299            Family::Msvc => push(&mut args, &["/INCREMENTAL:NO"]),
300            Family::Llvm | Family::Gnu => {}
301        }
302    }
303    if profile.lto {
304        match input.kind.family() {
305            Family::Msvc => push(&mut args, &["/LTCG"]),
306            Family::Llvm | Family::Gnu => args.push(format!("/opt:lldlto={lto_level}").into()),
307        }
308    }
309
310    args.extend(build.link_flags.iter().map(OsString::from));
311    args
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    /// The compilers for the MSVC ABI name a library `<lib>.lib`; GCC's
319    /// `ld` tries seven names in each directory, in the order
320    /// `-Wl,--verbose` lists its attempts.
321    ///
322    /// Mutation: name it otherwise for one compiler, or reorder GCC's
323    /// names; this test fails.
324    #[test]
325    fn a_library_is_the_files_its_linker_tries() {
326        for kind in CompilerKind::ALL {
327            let want: Vec<&str> = match kind {
328                CompilerKind::Msvc | CompilerKind::ClangCl | CompilerKind::Clang => {
329                    vec!["foo.lib"]
330                }
331                CompilerKind::Gcc => vec![
332                    "libfoo.dll.a",
333                    "foo.dll.a",
334                    "libfoo.a",
335                    "foo.lib",
336                    "libfoo.lib",
337                    "libfoo.dll",
338                    "foo.dll",
339                ],
340            };
341            assert_eq!(library_files(kind, "foo"), want, "{kind:?}");
342        }
343    }
344    use crate::flags::Runtime;
345
346    fn build() -> BuildSettings {
347        BuildSettings {
348            warnings: crate::flags::Warnings::Default,
349            warnings_as_errors: false,
350            defines: vec![],
351            include_dirs: vec![],
352            links: vec![],
353            lib_dirs: vec![],
354            link_flags: vec![],
355            flags: vec![],
356            runtime: Runtime::Dynamic,
357            exceptions: true,
358            rtti: true,
359        }
360    }
361
362    fn profile() -> ProfileSettings {
363        ProfileSettings {
364            opt_level: OptLevel::O0,
365            debug_info: false,
366            debug_assertions: true,
367            lto: false,
368        }
369    }
370
371    fn args(
372        kind: CompilerKind,
373        build: &BuildSettings,
374        profile: &ProfileSettings,
375        subsystem: Subsystem,
376    ) -> Vec<String> {
377        args_for(kind, build, profile, subsystem, true)
378    }
379
380    fn args_for(
381        kind: CompilerKind,
382        build: &BuildSettings,
383        profile: &ProfileSettings,
384        subsystem: Subsystem,
385        cxx: bool,
386    ) -> Vec<String> {
387        args_linking(
388            kind,
389            build,
390            profile,
391            Linked::Executable {
392                subsystem,
393                of_shared: false,
394            },
395            cxx,
396        )
397    }
398
399    fn args_linking(
400        kind: CompilerKind,
401        build: &BuildSettings,
402        profile: &ProfileSettings,
403        output: Linked<'_>,
404        cxx: bool,
405    ) -> Vec<String> {
406        // A GCC from before libstdc++exp, so each case's expected arguments
407        // need not say which GCC; the version's own test is below.
408        let input = LinkInput {
409            kind,
410            version: Version {
411                major: 13,
412                minor: 2,
413                patch: 0,
414            },
415            build,
416            profile,
417            output,
418            cxx,
419        };
420        link_args(
421            &input,
422            &[PathBuf::from("a.obj"), PathBuf::from("b.obj")],
423            Path::new("app.exe"),
424        )
425        .into_iter()
426        .map(|a| a.into_string().unwrap())
427        .collect()
428    }
429
430    /// Mutation: drop or reorder any default link argument of any driver, leave
431    /// the console subsystem unstated, pass the C runtime at link time, or put
432    /// the output after `/link`; this test fails.
433    #[test]
434    fn the_defaults_give_each_drivers_link_line() {
435        let (b, p) = (build(), profile());
436        assert_eq!(
437            args(CompilerKind::Msvc, &b, &p, Subsystem::Console),
438            [
439                "/nologo",
440                "a.obj",
441                "b.obj",
442                "/Fe:app.exe",
443                "/link",
444                "/SUBSYSTEM:CONSOLE",
445            ]
446        );
447        assert_eq!(
448            args(CompilerKind::ClangCl, &b, &p, Subsystem::Console),
449            [
450                "/nologo",
451                "-fuse-ld=lld",
452                "a.obj",
453                "b.obj",
454                "/Fe:app.exe",
455                "/link",
456                "/SUBSYSTEM:CONSOLE",
457            ]
458        );
459        let static_runtime = BuildSettings {
460            runtime: Runtime::Static,
461            ..build()
462        };
463        for b in [&b, &static_runtime] {
464            assert_eq!(
465                args(CompilerKind::Clang, b, &p, Subsystem::Console),
466                [
467                    "--target=x86_64-pc-windows-msvc",
468                    "-fuse-ld=lld",
469                    "a.obj",
470                    "b.obj",
471                    "-o",
472                    "app.exe",
473                    "-Wl,/subsystem:console",
474                ]
475            );
476        }
477        // GCC links its runtime and winpthread statically under either
478        // runtime; only C++ takes libstdc++.
479        for b in [&b, &static_runtime] {
480            assert_eq!(
481                args_for(CompilerKind::Gcc, b, &p, Subsystem::Console, true),
482                [
483                    "a.obj",
484                    "b.obj",
485                    "-o",
486                    "app.exe",
487                    "-mconsole",
488                    "-static-libgcc",
489                    "-static-libstdc++",
490                    "-Wl,-Bstatic",
491                    "-lstdc++",
492                    "-lwinpthread",
493                    "-Wl,-Bdynamic"
494                ]
495            );
496            assert_eq!(
497                args_for(CompilerKind::Gcc, b, &p, Subsystem::Console, false),
498                [
499                    "a.obj",
500                    "b.obj",
501                    "-o",
502                    "app.exe",
503                    "-mconsole",
504                    "-static-libgcc",
505                    "-Wl,-Bstatic",
506                    "-lwinpthread",
507                    "-Wl,-Bdynamic"
508                ]
509            );
510        }
511    }
512
513    /// A DLL links with each driver's switch for one, its import library
514    /// named to the linker and, with debug information, its PDB beside it;
515    /// no subsystem, and no `/NOIMPLIB`. Paths go to the GNU-style drivers
516    /// with `-Xlinker`.
517    ///
518    /// Mutation: drop `/LD` or `-shared`, the import library or the PDB,
519    /// pass a path with `-Wl,`, or keep the subsystem; this test fails.
520    #[test]
521    fn a_dll_links_with_its_import_library() {
522        let b = build();
523        let debug = ProfileSettings {
524            debug_info: true,
525            ..profile()
526        };
527        let shared = Linked::Shared {
528            import: Path::new("lib/m.lib"),
529            pdb: Path::new("lib/m.pdb"),
530        };
531        let cases: [(CompilerKind, &[&str]); 4] = [
532            (
533                CompilerKind::Msvc,
534                &[
535                    "/LD",
536                    "/nologo",
537                    "a.obj",
538                    "b.obj",
539                    "/Fe:app.exe",
540                    "/link",
541                    "/IMPLIB:lib/m.lib",
542                    "/PDB:lib/m.pdb",
543                    "/DEBUG",
544                    "/INCREMENTAL:NO",
545                ],
546            ),
547            (
548                CompilerKind::ClangCl,
549                &[
550                    "/LD",
551                    "/nologo",
552                    "-fuse-ld=lld",
553                    "a.obj",
554                    "b.obj",
555                    "/Fe:app.exe",
556                    "/link",
557                    "/IMPLIB:lib/m.lib",
558                    "/PDB:lib/m.pdb",
559                    "/DEBUG",
560                ],
561            ),
562            (
563                CompilerKind::Clang,
564                &[
565                    "-shared",
566                    TARGET_SWITCH,
567                    "-fuse-ld=lld",
568                    "-g",
569                    "a.obj",
570                    "b.obj",
571                    "-o",
572                    "app.exe",
573                    "-Xlinker",
574                    "/implib:lib/m.lib",
575                    "-Xlinker",
576                    "/pdb:lib/m.pdb",
577                ],
578            ),
579            (
580                CompilerKind::Gcc,
581                &[
582                    "-shared",
583                    "-g",
584                    "a.obj",
585                    "b.obj",
586                    "-o",
587                    "app.exe",
588                    "-Xlinker",
589                    "--out-implib",
590                    "-Xlinker",
591                    "lib/m.lib",
592                    "-static-libgcc",
593                    "-Wl,-Bstatic",
594                    "-lwinpthread",
595                    "-Wl,-Bdynamic",
596                ],
597            ),
598        ];
599        for (kind, want) in cases {
600            assert_eq!(
601                args_linking(kind, &b, &debug, shared, false),
602                want,
603                "{kind:?}"
604            );
605        }
606        // Without debug information, no PDB is named.
607        for kind in CompilerKind::ALL {
608            let plain = args_linking(kind, &b, &profile(), shared, false);
609            assert!(
610                !plain
611                    .iter()
612                    .any(|a| a.to_ascii_lowercase().contains("/pdb")),
613                "{kind:?}: {plain:?}"
614            );
615        }
616    }
617
618    /// An executable of a shared library's package is told to write no
619    /// import library (link.exe no `.exp` either), right after its
620    /// subsystem; any other executable is not, so a `/IMPLIB` in
621    /// `link-flags` still makes one.
622    ///
623    /// Mutation: tell every executable, or none; this test fails.
624    #[test]
625    fn only_a_shared_packages_executable_writes_no_import_library() {
626        let (b, p) = (build(), profile());
627        let of_shared = Linked::Executable {
628            subsystem: Subsystem::Console,
629            of_shared: true,
630        };
631        let tail = |kind| {
632            let args = args_linking(kind, &b, &p, of_shared, false);
633            args[args.len() - 2..].to_vec()
634        };
635        assert_eq!(tail(CompilerKind::Msvc), ["/NOIMPLIB", "/NOEXP"]);
636        assert_eq!(
637            tail(CompilerKind::ClangCl),
638            ["/SUBSYSTEM:CONSOLE", "/NOIMPLIB"]
639        );
640        assert_eq!(
641            tail(CompilerKind::Clang),
642            ["-Wl,/subsystem:console", "-Wl,/noimplib"]
643        );
644        let gcc = args_linking(CompilerKind::Gcc, &b, &p, of_shared, false);
645        assert!(!gcc.iter().any(|a| a.contains("implib")), "{gcc:?}");
646        for kind in CompilerKind::ALL {
647            let plain = args(kind, &b, &p, Subsystem::Console);
648            assert!(
649                !plain
650                    .iter()
651                    .any(|a| a.to_ascii_lowercase().contains("noimplib")),
652                "{kind:?}: {plain:?}"
653            );
654        }
655    }
656
657    /// Mutation: change or drop any row's link arguments for one driver
658    /// (`docs/en/specs/build.md`, "Settings and flags"), reorder several
659    /// libraries, paths or flags, split a flag at its comma, or put a linker
660    /// argument before `/link`; this test fails.
661    #[test]
662    fn every_setting_gives_the_tables_link_arguments() {
663        let full_build = BuildSettings {
664            links: vec!["user32".into(), "gdi32".into()],
665            lib_dirs: vec!["libs".into(), "more".into()],
666            link_flags: vec!["/OPT:REF,ICF".into(), "/STACK:2097152".into()],
667            ..build()
668        };
669        let full_profile = ProfileSettings {
670            opt_level: OptLevel::O3,
671            debug_info: true,
672            lto: true,
673            ..profile()
674        };
675        let w = Subsystem::Windows;
676        assert_eq!(
677            args(CompilerKind::Msvc, &full_build, &full_profile, w),
678            [
679                "/nologo",
680                "a.obj",
681                "b.obj",
682                "/Fe:app.exe",
683                "/link",
684                "user32.lib",
685                "gdi32.lib",
686                "/LIBPATH:libs",
687                "/LIBPATH:more",
688                "/SUBSYSTEM:WINDOWS",
689                "/ENTRY:mainCRTStartup",
690                "/DEBUG",
691                "/INCREMENTAL:NO",
692                "/LTCG",
693                "/OPT:REF,ICF",
694                "/STACK:2097152"
695            ]
696        );
697        assert_eq!(
698            args(CompilerKind::ClangCl, &full_build, &full_profile, w),
699            [
700                "/nologo",
701                "-fuse-ld=lld",
702                "-flto",
703                "a.obj",
704                "b.obj",
705                "/Fe:app.exe",
706                "/link",
707                "user32.lib",
708                "gdi32.lib",
709                "/LIBPATH:libs",
710                "/LIBPATH:more",
711                "/SUBSYSTEM:WINDOWS",
712                "/ENTRY:mainCRTStartup",
713                "/DEBUG",
714                "/opt:lldlto=3",
715                "/OPT:REF,ICF",
716                "/STACK:2097152"
717            ]
718        );
719        assert_eq!(
720            args(CompilerKind::Clang, &full_build, &full_profile, w),
721            [
722                "--target=x86_64-pc-windows-msvc",
723                "-fuse-ld=lld",
724                "-g",
725                "-flto",
726                "a.obj",
727                "b.obj",
728                "-o",
729                "app.exe",
730                "-luser32",
731                "-lgdi32",
732                "-Llibs",
733                "-Lmore",
734                "-Wl,/subsystem:windows",
735                "-Wl,/entry:mainCRTStartup",
736                "-Wl,/opt:lldlto=3",
737                "-Xlinker",
738                "/OPT:REF,ICF",
739                "-Xlinker",
740                "/STACK:2097152"
741            ]
742        );
743        assert_eq!(
744            args(CompilerKind::Gcc, &full_build, &full_profile, w),
745            [
746                "-g",
747                "-flto=auto",
748                "a.obj",
749                "b.obj",
750                "-o",
751                "app.exe",
752                "-luser32",
753                "-lgdi32",
754                "-Llibs",
755                "-Lmore",
756                "-mwindows",
757                "-static-libgcc",
758                "-static-libstdc++",
759                "-Wl,-Bstatic",
760                "-lstdc++",
761                "-lwinpthread",
762                "-Wl,-Bdynamic",
763                "-Xlinker",
764                "/OPT:REF,ICF",
765                "-Xlinker",
766                "/STACK:2097152"
767            ]
768        );
769    }
770
771    /// Mutation: map any `opt-level` to another LTO level; this test fails.
772    #[test]
773    fn lto_optimises_at_the_profiles_level() {
774        for (level, n) in [
775            (OptLevel::O0, "0"),
776            (OptLevel::O1, "1"),
777            (OptLevel::O2, "2"),
778            (OptLevel::O3, "3"),
779            (OptLevel::Size, "2"),
780        ] {
781            let p = ProfileSettings {
782                opt_level: level,
783                lto: true,
784                ..profile()
785            };
786            let clang_cl = args(CompilerKind::ClangCl, &build(), &p, Subsystem::Console);
787            assert!(
788                clang_cl.contains(&format!("/opt:lldlto={n}")),
789                "{level:?} {clang_cl:?}"
790            );
791            let clang = args(CompilerKind::Clang, &build(), &p, Subsystem::Console);
792            assert!(
793                clang.contains(&format!("-Wl,/opt:lldlto={n}")),
794                "{level:?} {clang:?}"
795            );
796            let msvc = args(CompilerKind::Msvc, &build(), &p, Subsystem::Console);
797            assert!(!msvc.iter().any(|a| a.contains("lldlto")), "{msvc:?}");
798            let gcc = args(CompilerKind::Gcc, &build(), &p, Subsystem::Console);
799            assert!(!gcc.iter().any(|a| a.contains("lldlto")), "{gcc:?}");
800        }
801    }
802
803    /// GCC 14 and later link `libstdc++exp` for C++, right before
804    /// `libstdc++` and statically; GCC 13, which has none, and C do not.
805    ///
806    /// Mutation: give it whatever the version, after `-lstdc++`, or to C;
807    /// this test fails.
808    #[test]
809    fn gcc_14_links_libstdcxx_exp_for_cxx() {
810        let v = |major| Version {
811            major,
812            minor: 1,
813            patch: 0,
814        };
815        assert_eq!(
816            gcc_runtime_args(true, v(14)),
817            [
818                "-static-libgcc",
819                "-static-libstdc++",
820                "-Wl,-Bstatic",
821                "-lstdc++exp",
822                "-lstdc++",
823                "-lwinpthread",
824                "-Wl,-Bdynamic",
825            ]
826        );
827        assert!(!gcc_runtime_args(true, v(13)).contains(&"-lstdc++exp"));
828        assert!(!gcc_runtime_args(false, v(16)).contains(&"-lstdc++exp"));
829    }
830}