Repository navigation
Description
This issue is intended to track support for splitting a rustc invocation that ends up invoking a system linker (e.g. cdylib, proc-macro, bin, dylib, and even staticlib in the sense that everything is assembled) into two different rustc invocations. There are a number of reasons to do this, including:
-
This can improved pipelined compilation support. The initial pass of pipelined compilation explicitly did not pipeline linkable compilations because the linking step needs to wait for codegen of all previous steps. By literally splitting it out build systems could then synchronize with previous codegen steps and only execute the link step once everything is finished.
-
This makes more artifacts cacheable with caching solutions like
sccache. Anything involving the system linker cannot be cached bysccachebecause it pulls in too many system dependencies. The output of the first half of these linkable compilations, however, is effectively anrlibwhich can already be cached. -
This can provide build systems which desire more control over the linker step with, well, more control over the linker step. We could presumably extend the second half here with more options eventually. This is a somewhat amorphous reason to do this, the previous two are the most compelling ones so far.
This is a relatively major feature of rustc, and as such this may even require an RFC. This issue is intended to get the conversation around this feature started and see if we can drum up support and/or more use cases. To give a bit of an idea about what I'm thinking, though, a strawman for this might be:
- Add two new flags to
rustc,--only-linkand--do-not-link. - Cargo, for example, would first compile the
bincrate type by passing the--do-not-linkflag, passing all the flags it normally does today. - Cargo, afterwards, would then execute
rustcagain, only this time passing the--only-linkflag.
These two flags would indicate to rustc what's happening, notably:
-
--do-not-linkindicates that rustc should be creating a linkable artifact, such as a one of the ones mentioned above. This means that rustc should not actually perform the link phase of compilation, but rather it's skipped entirely. In lieu of this a temporary artifact is emitted in the output directory, such as*.rlink. Maybe this artifact is a folder of files? Unsure. (maybe it's just an rlib!) -
The converse of
--do-not-link,--only-link, is then passed to indicate that the compiler's normal phases should all be entirely skipped except for the link phase. Note that for performance this is crucial in that this does not rely on incremental compilation, nor does this rely on queries, or anything like that. Instead the compiler forcibly skips all this work and goes straight to linking. Anything the compiler needs as input for linking should either be in command line flags (which are reparsed and guaranteed to be the same as the--do-not-linkinvocation) or the input would be an output of the--do-not-linkinvocation. For example maybe the--do-not-linkinvocation emits an file that indicates where to find everything to link (or something like that).
The general gist is that --do-not-link says "prepare to emit the final crate type, like bin, but only do the crate-local stuff". This step can be pipelined, doesn't require upstream objects, and can be cached. This is also the longest step for most final compilations. The gist of --only-link is that it's execution time is 99% the linker. The compiler should do the absolute minimal amount of work to figure out how to invoke the linker, it then invokes the linker, and then exits. To reiterate again, this will not rely on incremental compilation because engaging all of the incremental infrastructure takes quite some time, and additionally the "inputs" to this phase are just object files, not source code.
In any case this is just a strawman, I think it'd be best to prototype this in rustc, learn some requirements, and then perhaps open an RFC asking for feedback on the implementation. This is a big enough change it'd want to get a good deal of buy-in! That being said I would believe (without data at this time, but have a strong hunch) that the improvements to both pipelining and the ability to use sccache would be quite significant and worthwhile pursuing.
Activity
alexcrichton commentedon Sep 5, 2019
cc @cramertj and @jsgf, we talked about this at the RustConf and figured y'all would want to be aware of this
jsgf commentedon Sep 6, 2019
Would the
--only-linkliterally just invoke ld? If so, it might be useful to just be able to extract whatever extra libraries/options its adding to the link line, so we can independently regenerate the link line.This would be useful for linking hybrid Rust/C++/(other) programs where the final executable is non-Rust. In other words, we could have C++ depending on Rust without needing to use staticlib/cdylib.
alexcrichton commentedon Sep 6, 2019
I don't think it'd just be a thin wrapper around
ld, no, but it would also prepare files to get passed to the linker. For example when producing adylibrustc will unpack an rlib and make a temporary*.awithout bytecode/metadata. Additionally if performing LTO this'd probably be the time we'd take out all the bytecode and process it. (maybe LTO throws a wrench in this whole thing). Overall though I don't think it's safe to assume that it'll just beld.jsgf commentedon Sep 7, 2019
Firstly, we'd want the final linker doing LTO in order to get it cross-language, regardless of whatever language the final target is in and what mix of languages went into the target.
Secondly, since Buck has full dependency information, including Rust dependencies on C/C++, it will arrange for all the right libraries to be on the final link line. As a result we never want to use or honor
#[link]directive, and our.rlibs don't contain anything to be unpacked.(Even if that weren't true, at least on Unix systems, the
.rlibis just a.aand could be used directly, except perhaps for the extension).I like this proposal because it allows us to factor out the Rust-specific details from the language-independent ones. For example there's no reason for rustc to implement LTO if we're already having to solve that for other languages - especially when that solution pretty infrastructure-specific (distributed thin LTO, for example). There's also no real reason for us to use
staticlib/cdylibif we can arrange for all the Rust linker parameters to be on the final link line, even if the final executable is C++, and it would be a significant code duplication reduction (unless LTO see it and eliminate it, but that's still a compile-time cost).Ultimately, Rust lives in the world of linkable object files, and a final artifact is generated by calling the linker with a certain set of inputs. Since Rust doesn't have unusual requirements that make it incompatible with C/C++ linkage (eg special linkage requirements or elaborate linker scripts) then the final linker stage could be broadly language agnostic.
cramertj commentedon Sep 9, 2019
+1 to wanting the ability to turn off / disable
#[link].michaelwoerister commentedon Sep 11, 2019
I'm generally in favor of this. Some thoughts:
--do-not-linkstep and store it in the.rlinkoutput.rustc? That would make things simpler forrustcbut probably has some overhead. Also, as far as I know,llvm-ardoes not support doing LTO, but for staticlibs one might want to have it (Firefox does this at least).alexcrichton commentedon Sep 11, 2019
I don't disagree that y'all's sorts of projects don't want to use the rustc-baked-in LTO, but I don't think we can remove it because many other projects do use it (and rightfully want to). Also this is still just a sort of high-level concept, but if a lot of feature requests are piled onto this it's unfortunately unlikely to happen.
0dvictor commentedon Nov 18, 2019
Hi, my name is Victor and I'm workin with @tmandry.
I am very interested in this Issue as it potentially enables many other great cool. Therefore, I plan to make a prototype and ultimately implement it. @alexcrichton , do you have any suggestions/tips to start?
alexcrichton commentedon Nov 18, 2019
Great @0dvictor! The steps I'd recommend for doing this would probably look like:
As for the actual change itself I haven't looked too much into this, so I wouldn't know where best to start there.
tmandry commentedon Nov 19, 2019
Some implementation notes:
Recommended reading
Current state of things
The main
run_compilerfunction callsCompiler::link, which ensures there is a codegen step running. It then dispatches to the trait methodCodegenBackend::join_codegen_and_link.For the LLVM backend (which is the only one right now), this method is implemented here.
join_codegen_and_linkjoins all the threads running codegen, which save their results to an object file per thread (often namedfoo.bar.<hash>-cgu.<threadno>.rcgu.oon linux). The names of these object files are saved in theCodegenResultsstruct (specifically, look inCompiledModule).Finally, it calls
link_binarywhich has the main logic for invoking the linker.Strategy
Obviously, we need to split apart all the code that assumes codegen and linking happen at the same time. This starts with the
join_codegen_and_linktrait method. Thankfully, it doesn't seem like there is too much code that assumes this, but there's still a question of what to do in the new code.For the flags, we can start with unstable options (
-Z no-linkand-Z only-link) and later stabilize them via the RFC process. When theno-linkflag is passed, we should not invokelink_binaryanymore. When theonly-linkflag is passed, we need a way of recovering the information that was in ourCodegenResultsstruct so we can calllink_binary.tmandry commentedon Nov 19, 2019
I don't much like using a directory as output, since some build systems might not support this.
Probably the best thing to do is to make an ar file (which I should note is what an
rlibis today). I don't much care what the extension is (I like.rlink, since it probably gets handled differently than rlibs or staticlibs do today).That said, the choice of extension should be up to whoever is invoking rustc, and we should use the
-oflag to decide where our output goes.I think there might be details we need to pay attention to regarding the linker's default behavior when linking object files vs archive files (like symbol visibility), but not sure what those details are. cc @petrhosek
42 remaining items
adetaylor commentedon May 1, 2020
@jsgf The project I'm working on seems to share similar properties to yours:
.rlibs scattered throughout a very deep dependency tree, which may eventually roll up into one or multiple binariesWe can't:
rustcfor final linking. C++ is the boss in our codebase; we're not ready to make the commitment to put Rust in charge of our final linking..rlibs. This works if we're using Rust in only one place. For any binary containing several Rust subsystems, there would be binary bloat and often violations of the one-definition-rule.rlibs don't know what final binaries they'll end up in; and the build directives for the final binaries don't know what.rlibs they've pulled in from deep in their dependency tree. Our build system forbids that sort of global knowledge, or it would be too slow across so many targets.rlibs. That monster static library would depend on many C++ symbols, so each binary would become huge (and in fact not actually link properly)Therefore we want to link
rlibs directly into our final linker invocation. This is, in fact, what we're doing, but we have to add some magic:.rlibs, which would be easy apart from the fact they contain the symbol metadata hash in their names.__rust_allocto__rdl_allocetc.rustc-driven linker invocation might add extra magic.Therefore one of the solutions you and @tmandry suggest would be awesome: either stabilizing
.rlink(which sounds unlikely) or having some official way to build a linker command line which is not under the control of rustc (-Zbinary-dep-depinfohelps a bit).I think, though, that this request is a little bit orthogonal to this issue. I wonder if we should submit a new issue? I think it's quite a big request.
tmandry commentedon May 1, 2020
jsgf commentedon May 15, 2020
This issue came up in a discussion about @dtolnay's cxx which wants to be able to describe callback relationships between Rust and C++ code - eg Rust calls C++, which then calls back into Rust. If you're using linker symbols to resolve these calls (vs runtime indirect function calls via pointers), then that effectively means you have a rust.o and cxx.o with mutual references.
AFAIK the only way to correctly link this is with something like
--start-group rust.o cxx.o --end-groupon the linker command line. Ifrustcis driving the linking process, then it would need to understand this concept, which I think it out of scope for it. Alternatively, if the build system understands these kinds of relationships, then it already knows how to invoke the linker this way. (Moot for Cargo, since it doesn't have a way to model C++ dependencies on Rust, and certainly not cyclic ones.)joshtriplett commentedon Jul 17, 2020
I'm interested in the outcome of this. Is it currently in a state where cargo could potentially implement a useful subset of it? Or is there further work needed on the final link step before cargo can do anything?
jsgf commentedon Jul 20, 2020
@joshtriplett Kernel?
0dvictor commentedon Aug 3, 2020
I apologize for the long delay in continuing this work. PR #75094 is created to allow generating a single object file for a crate.
Performance was measured by compiling
rustcitself:-Ccodegen-units=1-Zcombine-cgu-Ccodegen-units=1(%)-Zcombine-cgu(%)Though
-Zcombine-cguis around 3% slower than the default configuration, it is still a significant improvement comparing to the single threaded case, which would significantly improve the performance of--emit [llvm-bc|llvm-ir|asm|obj].Rollup merge of rust-lang#75094 - 0dvictor:cgu, r=oli-obk
jsgf commentedon Jun 6, 2021
I tried using the -Zno-link/-Zlink-only mechanism in earnest, and unfortunately I think its deficient in a number of ways. I have some thoughts on a simpler to use mechanism. More detail: https://internals.rust-lang.org/t/alternative-approach-to-zno-link-zlink-only-split-linking/14842
Auto merge of rust-lang#93681 - Mark-Simulacrum:rlink-binary, r=david…
cosmicexplorer commentedon Dec 29, 2025
From reading the thread at https://internals.rust-lang.org/t/alternative-approach-to-zno-link-zlink-only-split-linking/14842, I have one brief comment and several less brief ones:
@bjorn3:
Synthesizing these comments of yours from 2021 and 2022 together, I now feel1 even more like "an explicitly public format, constructed from compiler-internal data, yet designed to be abstracted from compiler internals" in the manner of "SemanticDB2 for rust" is such a tantalizing idea!
@jsgf:
Having actually shipped a highly parallel distributed build process to production for Scala builds at Twitter1 via working very closely with Eugene Burmako on co-engineering rsc3 and pants together for this purpose, caching and parallelization tend to reach their global maximum when you pay world-class researchers to build powerful systems in their field of expertise. Many people get this wrong and will only compensate engineers for constructing systems of enclosure and deskilling and then call the promotion ladder that valorizes stealing credit from people who devote their lives to constantly reinventing the state of the art a "free market".
In particular, the epiphany that we shipped to Twitter engineers occurred not just from Eugene Burmako and Stu Hood's initial epiphany to enable pipelining with parallel scalac invocations as per Eugene's Scale by the Bay 2018 talk4, but Win Wang and my extended codevelopment session which identified the relationship between the process lifetime distinction of the multithreaded local HotSpot JIT rsc invocation vs highly parallel ephemeral remote execution of graal
native-imageAOT-compiled scalac jobs, and how attempting to do pipelining with 100% remote execution was completely losing the benefit of pipelining in the first place by taking the network i/o hit both ways across the topologically sorted partial ordering of the outline compilation phase.Eugene Burmako was not an expert on I/O latencies and resource saturation. I was not an expert on parallel typechecking. Win and I did not finally crack the case until we understood how computer performance is a result of bidirectional communication protocols suited to the task at hand.
Constructing a link line and providing it to the build system to invoke reminds me of how the user provides their own
&mut [u8]buffer tostd::io::Readand submits it to the OS. Constructing a.rlinkand postprocessing it into a standardized format (the aforementioned SemanticDB for rust) reminds me of adapters likeio::Chain.The
.rlinkfile being opaque already means it can't be distributed.It is the build system's job to look normal to the compiler.
chmod -w@adetaylor #64191 (comment)
Going from
.rlink(a rustc-specific interface) directly to a linker command line (which is tied to at least your choice of linker) seems to forget the law of excluded middle! Building a linker command line sounds like it should be definitionally the job of the build system, should it not?"under the control" lmao. The build system is executing the compiler as a subprocess. The compiler is not responsible for the build system's architectural constraints or internal politics. Build systems are not a tool to neg the compiler after a contributor does the one thing the build system can't do without forking it. This is a document I created in 2018: https://docs.google.com/document/d/1iWINqg30nXaCYmBxma5h5RgWzx7sgFqWGJcQJ-RYpRE/edit?usp=drive_link
Footnotes
https://github.com/rust-lang/rust/issues/67293#issuecomment-3696345567 ↩ ↩2
https://scalameta.org/docs/semanticdb/guide.html#semanticdb-based-tools ↩
https://github.com/twitter/rsc ↩
https://www.youtube.com/watch?v=8SnIBkJXD8I ↩
cosmicexplorer commentedon Dec 29, 2025
btw I would absolutely recommend rustc devs read Eugene Burmako's incredibly fascinating research notes on parallelism in typechecking1:
[WAIT FOR IT!!!!!!]
[...]
Footnotes
https://github.com/twitter/rsc/blob/master/docs/compiler.md ↩
bjorn3 commentedon Dec 29, 2025
Not inherently. It just means that it has to be processed by the exact same rustc version as it was produced by, which is the case anyway. Rlink files could plausibly be made movable across machines. Just nobody has worked on it. Turns out something was missing when
-Zno-link/-Zlink-onlywas originally implemented, making it not support what it was intended to support (extra build pipelining). I've been slowly chipping away on getting the rustc internals ready to actually make rlink files useful.Build systems have no clue about all rust crate dependencies (even if all user dependencies are known, the build system doesn't know anything about what standard library crates need to be linked in), it doesn't know about the rustc ABI compatibility rules and rustc generates various extra input to the linker to workaround limitations in the C compilation model with those extra inputs changing between rustc versions, the build system doesn't know the list of symbols that need to be exported (those are derived from the input source code after macro expansion), how to include the crate metadata in rust dylibs and more. That is why rustc is responsible for invoking the linker when using any crate type other than staticlib. And staticlib bundles all rust crates together with most other necessary linker inputs (only the list of C libraries to link isn't included, but you can get those from the rustc output when building the staticlib if you pass
--print native-static-libs). Even if we exposed all information rustc currently uses to build a linker invocation to the build system, it will probably break in the future when we add new features or change how existing features are internally implemented. For example we used to add all objects files bundled C static libraries directly into rlibs, but changed this to instead wrap the original C static library in a non-allocated section of an object file and extract them right before linking. Not including the object files directly was necessary to support conditional linking (#[link(name = "...", cfg(...))]) and wrapping the C static library in an object file is necessary to hide it from the linker. Otherwise many linker complain about unsupported archive member types.