[RFC] Link-Time Finalization for Separately Compiled AMDGPU Device Code

, ,

We would like to propose an architecture for supporting scalable separate
compilation of GPU device code in LLVM, with AMDGPU as the first implementation
target. Separately generated device objects can contain per-function resource
information. However, a kernel’s final requirements depend on the definitions
selected from other device objects and the resources required by those device
functions. The complete requirements therefore become known only after final
object-link resolution. This RFC first describes that general finalization
requirement and then proposes an AMDGPU implementation with a narrow interface
between ordinary ELF linking and AMDGPU-owned resource analysis.

The underlying problem can apply to other GPUs and accelerators that
pre-allocate compute resources before execution so that threads can start and
run correctly. A device program’s entry point is often a kernel function.
Launching a kernel requires the runtime and hardware to reserve resources for
its lifetime, including resources needed by other device functions reachable
from that kernel. These include register usage, shared memory usage, scratch
usage, and other device-specific resources that affect dispatch and occupancy.
Under separate compilation, those values can depend on device functions
compiled in other translation units.

We propose to integrate this finalization into the AMDGPU ELF link in a way that
does not require full LTO for correctness. At the same time, we want the
target-specific logic to be documented, owned by the AMDGPU community, and kept
behind a small lld/ELF integration surface.

Background: why GPU object linking needs a finalization step

In a conventional ELF link, the generated machine code in each input object is
normally treated as finished. Linkers perform target-specific work, but the
output ABI generally does not require a transitive resource summary for every
entry point before execution can begin.

GPU kernels add another constraint. A kernel dispatch uses explicit metadata
from the device image to reserve finite on-chip resources and determine how many
work-groups can be resident on a compute unit. These values are part of the
execution contract between the compiled image, the runtime, and the hardware.
They are not just debug information or optimization hints. They are required for
correctness and forward progress guarantees.

The complication appears when the program is compiled separately. Consider the
following illustrative pseudocode:

// a.cpp
extern device void helper();

kernel void K() {
  helper();
}

// b.cpp
device void helper() {
  use_many_registers();
  use_shared_memory_object();
}

When a.cpp is compiled, the compiler knows that K calls helper, but it
does not know the final resource usage of helper or the shared-memory objects
reachable through it. The object file for K therefore cannot contain complete
final metadata for K. The missing information is not available in any single
compiler invocation; it appears only when the separately compiled device objects
are linked together.

Full LTO is correct, but not enough as the only model

Full LTO is one correct way to avoid the separate compilation gap. It merges all
device IR into a single module before backend compilation. The backend then has
the same whole-program visibility that it has for single-file compilation, so
it can build the device call graph, propagate resource usage, lay out
compiler-managed resources, and emit final kernel metadata.

That model is correct, but as GPU programs become larger and more complex,
compiling and linking with full LTO is not scalable from a compilation and
development cost perspective.

ThinLTO can help recover parallelism by allowing backend compilation to happen
per translation unit with summary-guided optimization. However, it still
produces object files that need to be combined into a final device image. For
GPU code, that final combination still needs object linking to compute the
per-kernel metadata and resource-symbol values that depend on the resolved
cross-object program.

Information available at the final device link

The finalization described here needs two kinds of information. The first is
ordinary object-link state. For an ELF link, this includes:

  • which definitions prevailed after symbol resolution;
  • which archive members were selected;
  • how aliases and weak definitions resolve; and
  • which relocations are present in the selected input objects, including ones
    against target-defined resource symbols.

The second is GPU-specific. Once the ordinary link state is fixed, the
finalization step can gather the per-function resource summaries computed by
the compiler backend. Since a kernel function is the entry point to a GPU
program, finalization can compute each kernel’s resource requirements by
analyzing the resolved resource graph rooted at that kernel:

  • which device functions are reachable from each kernel;
  • which indirect-call targets need to be conservatively considered;
  • which compiler-managed resources are reachable from each kernel; and
  • which resource-symbol values and metadata fields need final values derived
    from that resolved graph.

Any implementation of this finalization needs access to the resolved device-link
state or an equivalent representation of it. For the AMDGPU implementation
proposed here, LLD is already the component that sees all input AMDGPU ELF
objects, performs symbol resolution, selects archive members, applies
relocations, and writes the final AMDGPU ELF output. We therefore propose to run
AMDGPU device object finalization as part of that link.

What the AMDGPU finalization step does

For AMDGPU, we propose to use .amdgpu.info as the object-file contract for
carrying the information needed by the link step. The AMDGPU backend emits
compact per-function summaries that describe local resource usage, call edges,
ABI-relevant properties, indirect-call information, and uses of
compiler-managed resources such as LDS objects and named barriers. The AMDGPU
ELF link step can then combine these summaries with the resolved symbol table
and produce final per-kernel metadata.

The current AMDGPU usage documentation
already describes the relevant ABI pieces, including .amdgpu.info. As part of
this work, we plan to reorganize the ABI-related text into a dedicated section
and expand it so that the object-file contract is easier to review without
already being deeply familiar with AMDGPU internals. The expanded documentation
would cover the summary format, SHN_AMDGPU_LDS, named-barrier symbols,
resource-symbol semantics, and the rules used by the device link finalization
step.

With that contract in place, the AMDGPU device-link finalization step consumes
those summaries and the result of ordinary ELF resolution. It then:

  • builds a resolved device-link resource graph from the selected input objects;
  • resolves direct calls, aliases, and indirect-call edges conservatively;
  • validates cross-translation-unit ABI compatibility where required;
  • propagates register, scratch, LDS, named-barrier, and other resource
    requirements through the graph;
  • computes per-kernel reachability for compiler-managed resources;
  • assigns concrete offsets or IDs for resources such as LDS objects and named
    barriers; and
  • updates AMDGPU kernel descriptors and HSA metadata with the final values.

One distinction worth making is that this is not a generic optimization call
graph. It is a target-specific device-link resource graph. Its nodes and
edges are tied to AMDGPU ABI rules, resource summaries, conservative handling
of indirect-call targets, and compiler-managed resource symbols. Existing LLVM
call-graph encodings or algorithms may still be reusable where their semantics
fit. We propose to evaluate those pieces independently while keeping
AMDGPU-specific resource state and ABI behavior in the target-owned
finalization component.

For the first implementation, we propose to keep this graph construction
target-specific and close to the AMDGPU finalization logic. This does not rule
out future factoring. If another GPU target needs a similar device-link
finalization model, we would like to revisit the boundary and extract common
pieces based on multiple real users rather than guessing the abstraction from one
target.

The finalization step does not rerun instruction selection, register allocation,
or other backend code generation passes. It computes and writes final metadata
and resource-symbol values that are only knowable once the device objects have
been resolved together. Some of those values, such as LDS offsets or
named-barrier IDs, are naturally tied to symbol resolution and relocation.
Others, such as propagated resource counts in the kernel descriptor, are part of
the final code object contract consumed at dispatch time.

Proposed LLD integration point and data flow

The proposed hook has a specific position in the lld/ELF pipeline:

  • all object files, including LTO-produced objects, have been added; archive
    extraction and ordinary input-symbol resolution are complete;
  • target information and merged ELF flags are available, and section garbage
    collection has run; and
  • output-section assignment, linker-script section discarding, ICF, and
    ordinary output-relocation scanning and application have not yet run.

This position gives finalization the prevailing definitions, selected objects,
resolved aliases, GC-live input sections, and input relocations. It is still
early enough to assign values to LDS and named-barrier pseudo-symbols before
ordinary relocation processing, and to update or resize AMDGPU metadata before
output layout.

The AMDGPU-specific finalization path reads:

  • the selected AMDGPU objects and the contents and relocations of
    .amdgpu.info, .amdgpu.strtab, kernel descriptors, and HSA metadata;
  • the mapping from input symbols to prevailing definitions, including aliases,
    weak definitions, and section-symbol references;
  • live-section information and the selected target’s merged ELF flags; and
  • a diagnostic interface.

Its permitted side effects are limited to:

  • concrete values and required final ELF attributes for LDS and named-barrier
    pseudo-symbols;
  • updated AMDGPU kernel-descriptor and HSA-metadata contents; and
  • validation failures for malformed or ABI-incompatible inputs.

It would not add input files, change which definitions prevail, or replace or
modify generic symbol resolution, archive extraction, section assignment, or
relocation processing. The relationship with ICF, which currently runs after
this proposed hook, is one ordering detail on which we would particularly
welcome feedback.

Code placement and dependency boundary

The proposed initial design follows the current implementation. It places the
.amdgpu.info parser, resource graph, and orchestration in the
AMDGPU-specific lld/ELF/AMDGPUObjectLinking.cpp path, where they directly
consume LLD’s resolved symbols, selected input objects, sections, and
relocations. Direct access avoids constructing and maintaining a second
representation of link state solely for finalization.

The surrounding LLD integration records the AMDGPU ABI section indices,
preserves SHN_AMDGPU_LDS pseudo-symbols for finalization, supports the
required AMDGPU relocation, and invokes one target-gated entry point.
Hardware-dependent resource encoding and kernel-descriptor and HSA-metadata
patching use AMDGPU-owned support APIs based on documented ABI structures and
TargetParser; they do not require AMDGPU code generation or
MCSubtargetInfo.

ABI evolution, ownership, and expected maintenance

The object-file contract is intended to make the expected location of future
changes explicit:

  • hardware-generation resource limits and descriptor encodings should change
    only in AMDGPU-specific finalization or support code and its
    target-information tables;
  • new per-function summary records should require corresponding AMDGPU ABI
    documentation, backend emission, and finalization support, but no generic LLD
    change when the linker-facing inputs are unchanged;
  • new ELF-visible semantics, such as a pseudo-symbol or relocation kind, may
    require a focused AMDGPU LLD target change; and
  • changes to the generic hook or to ordinary ELF invariants would require LLD
    review.

The .amdgpu.info encoding is tagged and length-prefixed so that optional
records can be extended without changing generic LLD code. Records required for
correctness still need explicit compatibility and validation rules; they must
not be silently ignored by a consumer that cannot implement their semantics.
AMDGPU maintainers would own the target-specific finalization code, support
helpers, ABI documentation, and tests. LLD maintainers would retain ownership
of the generic integration points and linker invariants around them.
The implementation will include focused tests for ABI decoding and validation,
resource-graph algorithms, and end-to-end ELF finalization.

Preliminary results

The initial implementation shows the expected build-time improvement over full
LTO. For one GPU target, RCCL builds take roughly 30 minutes with full LTO and
roughly 5 minutes with object linking. In the LLVM libc GPU test suite,
compile-and-link time drops from about 145 seconds to 44.5 seconds, with the
relevant tests passing.

Feedback requested

We appreciate feedback on the proposed architecture and integration boundary,
especially any correctness, ABI, layering, ownership, or maintainability
concerns not addressed above.

For implementation context, an initial AMDGPU LLD patch is available at
[RFC][AMDGPU][lld] Link-time finalization for separately compiled AMDGPU device code by shiltian · Pull Request #206787 · llvm/llvm-project · GitHub. This RFC is intended to
discuss the design and integration model rather than the details of that patch.

@arsenm @bader @Artem-B @MaskRay @jrtc27 @jhuber6


This RFC was drafted by me but refined (many times) by AI.

4 Likes

+1

Thanks for working on this. This is sorely needed to have a complete ABI for GPU programs. Once we have support for this we will be able to build full libcall support for the GPU and lean on parallel compilation without things constantly breaking.

Thanks for writing this up, and for the level of specificity in it. Naming a position in the pipeline and enumerating
permitted and prohibited side effects is what made it possible to review this as a design rather than as a patch, and I
want to acknowledge the offer to own the code — it is made in good faith and I am not questioning the intent behind it.

I do not think this belongs in lld/ELF, and I want to state that plainly rather than leave it implied across a list of
requests.

Two questions sit underneath that, and I would like both answered rather than only the second. First, how large is the
need — separate device compilation is opt-in on both toolchains and, as far as I can measure, barely used even by the
vendor that has supported it longest, so the size of the problem this solves is itself worth establishing. Second,
granting the need, whether a general-purpose ELF linker is the right place to solve it. My position is firm on the
second and genuinely open on the first, but the first has so far been argued from two build-time figures whose
beneficiaries have not been identified.

The line I think we should be drawing

Independent of this patch, because otherwise we re-litigate it per vendor:

lld/ELF operates on the object file format — sections, symbols, relocations. It does not compute target semantics
that require modelling the target’s execution resources.

That keeps everything Arch/AMDGPU.cpp does today comfortably inside: relocations, e_flags merging, code-object
output. It puts transitive VGPR/SGPR/LDS/scratch propagation, occupancy validation and compute_pgm_rsrc* re-encoding
outside.

I am proposing this as a general rule rather than a verdict on AMDGPU because the alternative is a linker whose scope is
defined by whichever vendor asked most recently. The object-file format is a stable contract that changes on a standards
cadence; a GPU’s execution resource model changes every hardware generation. Those two things have different maintenance
characteristics and I do not think one codebase should be responsible for both.

Why: the maintenance asymmetry, measured

This is the substance of the objection, so numbers rather than an impression.

Commits per year touching the AMDGPU resource/format surface that a linker-side implementation must stay bit-compatible
with — AMDGPUAsmPrinter, AMDGPUHSAMetadataStreamer, AMDGPUBaseInfo, AMDGPUMCResourceInfo,
GCNSubtarget.{h,cpp}, AMDGPUTargetParser, AMDGPUTargetStreamer:

2021 2022 2023 2024 2025 2026 (7 mo)
59 127 107 161 194 200

The years before that run 59–81. So this surface has gone from under 80 commits a year to 200 in seven months, which
annualises to roughly 340 — a ballpark, since the linker-side subset would be smaller, but it is what a surface tracking
hardware generations looks like. For contrast, the per-target relocation code lld/ELF maintains today changes on the
order of ten to twenty commits a year per architecture.

Against that, what AMDGPU costs lld/ELF right now. Counting commits since 2022 that touch exactly one Arch/*.cpp
together with generic lld/ELF files: ARM 31, AArch64 24, RISCV 20, PPC64 13, LoongArch 11 — and AMDGPU 2. So targets
do reach into the core routinely and we absorb it; RISC-V, whose relaxation also bends generic invariants by mutating
section sizes, costs about four such commits a year and that has been sustainable. The point is not that reaching into
generic code is unacceptable. It is that AMDGPU is currently among the cheapest targets we have, and this proposal moves
it to RISC-V-like or beyond while being driven by a surface that churns at a large commit count instead of by a psABI.

I want to be fair to the ownership offer here, because it addresses the cost I can most easily measure and not the ones
that actually worry me. Three channels do not show up in a commits-touching-generic-files metric at all:

  • Cross-tree breakage. 508b5be88431 moved supportsWGP() to a tablegen feature bit. It touched no lld file, needed
    no lld review, merged cleanly against this branch, and broke the build. Post-merge that is a broken main and a bisect
    landing on an AMDGPU backend commit that only makes sense to someone who understands the linker pass. No amount of
    file ownership prevents this; the coupling is semantic, not textual.
  • Triage. Failures in this code print an lld backtrace and “PLEASE submit a bug report”. They arrive as lld bugs
    regardless of which layer is at fault, and deciding which layer it is is the expensive part.
  • Review capacity. “AMD maintains the file” answers who writes the patches, not who is accountable when the seam
    breaks.

There is a fourth cost that is easy to overlook because it is not source code.
The patch adds 34 lit tests totalling 7880 lines.
For scale, all of lld/test/ELF today is 1521 files and 94067 lines, so this is an 8.4% increase in the ELF test corpus
from one patch for one target. The individual files are also unlike our existing ones: median 209 lines against a suite
median of 41. The largest, amdgpu-lds-link-time-ordering-multigroup.s at 505 lines, is 411 lines of hand-written
assembly supporting 17 CHECK lines, and the set contains five lds-link-time-ordering-* variants, five
lds-link-time-indirect-* and five further lds-link-time-*.

I raise this as a maintenance question rather than a style one. Tests at this density are hard to review, because it is
not apparent which assertions are load-bearing and which merely record what the implementation happened to do the day
they were written. That distinction only matters later, when one of them fails after an unrelated change and somebody
has to decide whether the expectation or the change is wrong — and on current staffing that somebody is often not the
person who wrote the test. You have been open that the implementation was produced with AI assistance, and I mention it
only because it bears directly on that cost: generated fixtures encode incidental behaviour as expected behaviour very
cheaply, and the expense is deferred onto whoever maintains the suite.

One resource model, several encodings

A tool may depend on the AMDGPU backend directly. llvm/tools/llvm-calc-occupancy, an occupancy calculator added in
July, links AMDGPUCodeGen/AMDGPUDesc/AMDGPUUtils and reuses GCNSubtarget’s own arithmetic, guarded by
if(NOT "AMDGPU" IN_LIST LLVM_TARGETS_TO_BUILD) return(). When the target is not built, the tool does not exist, and
there is nothing further to reason about.

lld has no such option. It must build and work in every configuration, so anything it needs must live in a library
that is always built. That is the structural reason the resource encoding has been added to llvm/lib/TargetParser
rather than reused from the backend: 190 new lines introducing ObjectLinkingTargetInfo, effectively a third subtarget
model beside GCNSubtarget and MCSubtargetInfo. All eight resource functions it adds already exist in the MC layer —
getVGPREncodingGranule, getNumExtraSGPRs, getNumSGPRBlocks, getEncodedNumVGPRBlocks,
getAddressableLocalMemorySize, getMaxWavesPerEU, supportsWGP, hasArchitectedFlatScratch — and they are not
forwarders but independent re-derivations keyed on GPUKind/IsaVersion rather than subtarget features.

supportsWGP is now encoded three times, the first being the form 508b5be88431 has just migrated GCNSubtarget to:

AMDGPU.td:244                defm SupportsWGP : AMDGPUSubtargetFeature<"supports-wgp", ...>
AMDGPUBaseInfo.cpp:2617      if (isGFX1250(STI)) return false; return isGFX10Plus(STI);
AMDGPUTargetParser.cpp:443   return !isGFX1250(Target) && Target.isGFX10Plus();

and the isGFX1250 in the latter two differs again: a feature-bit query, getFeatureBits()[FeatureGFX1250Insts] && !isGFX13(STI), against a hand-written GK_GFX1250 || GK_GFX1251 || GK_GFX12_5_GENERIC with no GFX13 clause. As far as
I can tell they agree today; nothing makes them agree tomorrow, because the MC form follows the .td tables while the
new one is a list somebody must remember to extend — as is the addressable-LDS table, hardcoding 327680 / 163840 / 65536
/ 32768 against four GK_* values. A new GPU generation now means updating the backend and separately updating a
parallel encoding. If they disagree, the symptom is a wrong kernel descriptor at runtime.

To be clear about what I am not saying: TargetParser is the right home for this, arsenm asked for it there, and moving
resource queries out of the backend is already underway independently of this work — getTotalNumSGPRs,
getAddressableNumSGPRs and getSGPRAllocGranule landed there in July, and llvm/tools/llvm-calc-occupancy carries a
TODO asking for exactly that exposure so it can drop its codegen dependency. This patch is pulling in the same
direction.

A conditionally-built tool leaves one configuration to support and test; putting this in lld leaves two, and exercises one.

How large is the need, and whose need is it?

The two headline figures — 30 min → 5 min for RCCL, 145 s → 44.5 s for the libc GPU suite — are build-time costs, paid
by whoever runs the build. RCCL ships as prebuilt ROCm packages; the ordinary user installs rocm-hip-runtime-dev and
never links it, and the libc GPU suite is built by toolchain developers. So these wins appear to accrue to AMD’s
release engineering, to people who build AMDGPU software stack from source — not to people running HIP applications
.
If that is wrong, please correct it; if it is right, I would like it said plainly, because “our builds are slow” and
“our users are blocked” are different arguments for putting complexity into shared infrastructure.

The addressable population can be measured rather than asserted. Separate compilation is opt-in on both toolchains
(nvcc documents --relocatable-device-code with Default value: false; clang’s HIP default is -fno-gpu-rdc), and
NVIDIA’s own use of it after fifteen years is countable: relocatable device objects carry __nv_relfatbin and reference
__cudaRegisterLinkedBinary, whole-program ones carry .nv_fatbin and __cudaRegisterFatBinary (verified against
locally compiled objects both ways). Across the 35 static libraries shipped in CUDA 13.3:

device-bearing objects
whole-program (__cudaRegisterFatBinary) 3408
relocatable device code (__cudaRegisterLinkedBinary_*) 2

18 archives carry whole-program device code and 2 carry RDC, the remaining 15 being host-only; libcublasLt_static.a
alone accounts for 2620 whole-program objects. The two RDC objects are libcudadevrt.a:cuda_device_runtime.o, the
device runtime required for dynamic parallelism, and libcufft_static.a:separate_callback.o, cuFFT’s separately
compiled callbacks — both cases where RDC is mandatory for the feature to exist, not chosen. That is evidence about how
the vendor treats the mode rather than a census of user code, but it points the same way as the defaults.

The RFC reports build time and lit wall time, but no runtime or occupancy comparison. CUDA users have reported
significant performance degradation from RDC. Degradation of that order is part of why the mode stayed niche, and it is
what makes the missing occupancy numbers worth having, particularly around the conservative indirect-call handling where
one address-taken function inflates every kernel that might reach it.

The alternative the RFC does not discuss

The RFC never considers a separate device linker. The case it makes for lld is availability:

LLD is already the component that sees all input AMDGPU ELF objects, performs symbol resolution, selects archive
members, applies relocations, and writes the final AMDGPU ELF output. We therefore propose to run AMDGPU device
object finalization as part of that link.

That is an argument for a device linker, not for this codebase. I measured what nvlink does with CUDA 12.0 on
sm_70 (nvcc -arch=sm_70 -rdc=true -dc, then nvlink -arch=sm_70, inspected with cuobjdump -elf):

observation result
nvcc --dryrun nvlink absent from the whole-program pipeline, present only for -rdc=true
object contract .nv.info (EIATTR_REGCOUNT, stack/frame size), .nv.info.<fn> (EIATTR_EXTERNS), .nv.callgraph, .nv.prototype
propagation kernel 24 regs pre-link → 70 post-link (its callee’s count); EIATTR_MIN_STACK_SIZE synthesised
recompilation none — callee .text byte-identical, 120 SASS words
shared memory one per-kernel .nv.shared.<kernel> NOBITS sized by reachability (0x600 = 0x400 + 0x200); second TU’s immediates shifted by exactly +0x200; shared symbols dropped
code addresses R_CUDA_ABS47_34 against the callee left unresolved for the loader
indirect calls conservative: fp initialised to a 24-register function, a 70-register function merely address-taken ⇒ kernel still 70
linker duties diagnoses undefined symbols; extracts members from a .a

Two things follow. The design here is not idiosyncratic — it is the shape the problem has, and the .amdgpu.info
records, the conservative indirect-call treatment and the resource-symbol-plus-relocation approach to LDS all have
direct counterparts; that last is the part I have said is done right. And nvlink resolves symbols and extracts archive
members itself, so every piece of link state this needs can be held by a tool that is not the host linker.

The PR discussion turned on whether the comparison applies at all — the argument that nvcc emits PTX, an IR, whereas
AMDGPU emits object code. Repeating the propagation on CUDA 13.3 / sm_120 with
-gencode arch=compute_120,code=sm_120, which embeds no PTX (cuobjdump -lelf -lptx: “No PTX file found”), a kernel
calling a __noinline__ __device__ callee in another TU — the callee holding a volatile local array it indexes
dynamically, so it needs a real frame — goes from REG:24 STACK:0 before the device link to REG:254 STACK:680 after
it, and strace -f -e trace=execve shows no child process. With the byte-identical callee .text above, nvlink is
finalising object code, not recompiling an IR. Plain -arch=sm_120 embeds both a cubin and PTX, so measurements taken
that way cannot settle it.

On “but lld already plays nvlink’s role for AMDGPU”. I have made that point myself, so to answer it: the distinction
is between codebases, not processes. nvlink is separately owned and released and drags no other consumer when its
resource model changes. Running finalization inside lld/ELF puts a GPU execution-resource model into the source tree,
review queue and release train of a general-purpose ELF linker. That is what I object to, not to finalization happening
at link time, which I agree it must. It also means a separate tool adds no build step: the device link is already its
own invocation, and this only decides which binary it runs.

clang-sycl-linker is a partial precedent — a per-vendor device linker as a separate tool in clang/tools/, resolved
via ToolChain.GetProgramPath (clang/lib/Driver/ToolChains/SPIRV.cpp:186) — but for ownership and placement only. It
links LLVM bitcode and has no relocation processing, architecturally what -fgpu-rdc does today, so it would be fair to
say SYCL sidestepped the problem rather than solving it outside the linker. nvlink remains the only existence proof for
the object-level version.

The real cost of a separate device linker is a second implementation of generic ELF linking, the trade NVIDIA accepted.
That is the strongest argument for the current approach, and I would like it weighed against the maintenance numbers
above rather than settled by “lld already sees the objects.”

The contract is prose, not an interface

The permitted side effects are a promise about behaviour, while the code reaches directly into lld’s resolved symbols,
sections and relocations:

Direct access avoids constructing and maintaining a second representation of link state solely for finalization.

The consequence is that the “Prohibited Side Effects” list — that finalization will not

add input files, change which definitions prevail, or replace or modify generic symbol resolution, archive
extraction, section assignment, or relocation processing

— is enforced entirely by review rather than by construction. Nothing in the code makes any of those five harder to do
than to do; a pass holding Symbol * and mutable InputSection contents can violate every item by accident, and the
violation looks like ordinary code.

There is already an instance. Driver.cpp has replaceCommonSymbols skip isAMDGPULDS commons unconditionally, on the
promise that finalization resolves them later. Where the pass declines to run, the surviving CommonSymbol reaches the
writer and aborts — ld.lld -r is one such path, since the info section index is recorded only when
!ctx.arg.relocatable. The fix is small and no existing test covers -r, so this is not a regression in something
promised. But an invariant that generic code could previously rely on unconditionally now holds only when a target pass
chooses to run, and that happened without anyone intending it, in the first untested path anyone walked down. That is
what “the boundary erodes silently” looks like in practice.

I want to be careful about where this leads, because “add a narrow accessor interface” would be the obvious response and
I do not think it resolves the question. The pass wants InputSection, Symbol and ObjFile. An interface narrow
enough to make the prohibited list a compile error would either expose lld’s internals as a semi-stable API — which is a
worse commitment than the current one — or abstract them behind a view of sections, symbols and relocations. If the
interface has to be that abstract anyway, the natural abstraction is ELF itself, and at that point the finalizer does
not need to be inside lld/ELF to consume it. That is smithp35’s “smart format, dumb linker” point arriving from the
other direction.

Incubation, and what would change my mind

A month ago smithp35 suggested keeping this downstream until a second GPU-like device needs it. The RFC uses the single-
target situation to argue the other way — extract common pieces later, “based on multiple real users rather than
guessing the abstraction from one target.” I think downstream first is the right order, and I want to make it a
concrete bar rather than an open-ended delay. What I would want to see before revisiting:

  • a psABI document specifying the .amdgpu.info wire format, including version negotiation and a rule for records a
    consumer must not silently ignore;
  • that format holding still — no correctness-relevant additions — across a couple of ROCm releases, which is the direct
    evidence against the churn numbers above;
  • consumers beyond AMD-internal builds, which also answers the previous section;
  • and the finalization running outside lld/ELF’s link() in your downstream tree, which is what demonstrates the
    boundary is real rather than asserted.

None of that requires my involvement to start. The first item is the piece that unblocks every other option, including
the ones I would prefer over the status quo, and I am happy to review it whenever it is ready.


Part B — comment for PR #206787

Two things from applying the branch locally.

The build is broken for any configuration without AMDGPU in LLVM_TARGETS_TO_BUILD.
llvm/include/llvm/Support/AMDGPUObjectLinkingHelper.h declares resolveObjectLinkingResources,
patchKernelDescriptor and patchHSAMetadataKernel, but they are defined in
llvm/lib/Target/AMDGPU/Utils/AMDGPUObjectLinkingHelper.cpp, which builds into LLVMAMDGPUUtils (ADD_TO_COMPONENT AMDGPU). lld/ELF links ${LLVM_TARGETS_TO_BUILD} plus generic components, so with
-DLLVM_TARGETS_TO_BUILD='AArch64;ARM;PowerPC;RISCV;X86':

ld.lld: error: undefined symbol: llvm::AMDGPU::resolveObjectLinkingResources(llvm::AMDGPU::ObjectLinkingTargetInfo const&, llvm::AMDGPU::RawLinkingResources const&)
>>> referenced by AMDGPUObjectLinking.cpp
ld.lld: error: undefined symbol: llvm::AMDGPU::patchKernelDescriptor(...)
ld.lld: error: undefined symbol: llvm::AMDGPU::patchHSAMetadataKernel(...)

A Support header whose implementation lives under lib/Target is also the layering inversion raised earlier. Moving
both files to BinaryFormat fixes it: that library is built unconditionally, its LINK_COMPONENTS are already exactly
Support and TargetParser, and it already hosts AMDGPUMetadataVerifier. The implementation needs nothing beyond
those.

Separately, the branch no longer compiles against main. 508b5be88431 removed GCNSubtarget::supportsWGP() in favour of
the tablegen feature bit:

llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp:946:30: error: no member named 'supportsWGP' in 'llvm::GCNSubtarget'
  946 |          /*UsesWgpMode=*/STM.supportsWGP() && !STM.isCuModeEnabled(),
      |                          ~~~ ^

STM.hasSupportsWGP() is the replacement — that commit converted the other two callers, including one at line 1481 of
this same file, so the fix is a one-liner consistent with its neighbour.

A data point regarding practical need for RDC compilation/linking at this point in time. In our build for NVIDIA GPUs only 3 projects use RDC compilation (NVIDIA’s own NCCL, and nvshmem, plus GitHub - mumax/plus: More versatile and extensible GPU-accelerated micromagnetic simulator · GitHub ). For comparison, there are a few thousands regular CUDA compilations.

My take on it is that at the moment RCCL/NCCL libraries are both very atypical, both in how they are built, and in their size.

There’s a lot to get through in this RFC and reply and I haven’t had a chance to understand the details. I think it will help when it is written down where the modification points are.

One high-level comment on the overall design and possible alternatives. Have you considered a flow like:

  • Compile individual object files
  • lld -r inputs -o partial-object.o
  • amd-specific-tool partial-object.o -o modified-partial-object.o
  • lld modified-partial-object.o -o output.elf

The -r output should be fairly close to what you need [1]. It has all the archive resolution, prevailing definition, comdat merging etc done, but is still relinkable. An amd-specific-tool could perform all the analysis and rewriting of the amd specific sections. That output could be relinked by lld.

[1] The current -r output probably does too much merging for you, for example merging all the .text sections into one .text section, which would impede further garbage collection, ICF, linker script placement etc. Arm’s proprietary linker used a different model in (--partial) that didn’t combine sections. The intent was to use a partial object as an optimised proxy for the inputs that could be redistributed and combined in a future link-step.

Yes this would require 2 lld invocations and 1 separate tool, which would need to understand enough ELF to be able to do the analysis and rewriting. However it could be wrapped in a single tool for build-system purposes.

This would make the interface with lld defined purely in ELF, and would reuse the boilerplate of library selection, symbol matching etc.

If this is an outcome of this RFC, I think it would be good to write this down, along with as a good a definition of we can for what modelling the target’s execution resources mean.

1 Like

Thank you all for the detailed feedback. There appears to be broad agreement that RDC compilation requires some form of link-time finalization. The remaining disagreement is about the component boundary, particularly whether that finalization belongs in lld. Given the community feedback, we will not pursue the proposed in-lld design in its current form. Before closing the RFC, however, I would like to respond to two broader points and summarize the alternatives we have considered.

First, RDC compilation is not uniformly niche across GPU languages and programming models. nvcc defaults to non-RDC compilation, but NVIDIA’s CUDA Fortran compiler generates RDC by default and has done so for many releases.

On the LLVM side, Clang HIP also defaults to non-RDC compilation today, although we are considering whether RDC should become the default. LLVM’s standard OpenMP offloading pipeline supports only RDC compilation for both C/C++ and Fortran.

As a result, many HPC applications built with OpenMP or Fortran offloading already use RDC in practice. Portable frameworks such as Kokkos and RAJA also support RDC-based cross-translation-unit device code. For example, Kokkos provides KOKKOS_RELOCATABLE_FUNCTION for cross-translation-unit device calls, while Celeritas documents RDC as a requirement for its CUDA+VecGeom configuration.

The prevalence of RDC varies across ecosystems, but the requirement is neither hypothetical nor confined to one programming model or application. Raw CUDA toolkit archive counts do not capture all of these existing uses.

Second, the underlying finalization problem is not unique to AMDGPU. @MaskRay’s native-object nvlink experiments provide direct evidence that NVIDIA performs the same class of link-time finalization. Although the targets differ in resource names, object-file records, and ABI encodings, both must account for the resolved call graph and propagate resource requirements to determine each kernel’s final values. The target-specific pieces are the resource rules, object-file contract, and ABI encoding; the whole-program graph problem is shared.

Finally, we considered three ways to keep this work outside lld.

One option is to add a GNU-style linker plugin mechanism to lld. That could provide a component boundary, but lld does not currently have a general plugin interface, and defining one would be a much broader project.

Another option is to use lld as a library. lld can be invoked in-process, but its current API runs a complete link and does not expose a supported point at which an external finalizer can inspect or modify resolved ELF state.

The most promising approach is @smithp35’s separate-device-linker flow. Thank you for this valuable suggestion. Our initial investigation suggests that this approach is feasible, but several details still need to be validated. In particular, the partial link must preserve the association between the prevailing weak or COMDAT definition and the corresponding function-specific metadata. The current in-lld implementation can recover that association from the original input objects, but a single relocatable output does not retain that provenance automatically. We therefore need to determine how to represent it explicitly in the relocatable ELF interface. We also need to validate the complete flow with ThinLTO, since supporting ThinLTO for AMDGPU remains one of our goals.

Last but not least, we value the community’s feedback and will use the requirements and concerns raised in this RFC to guide our future work, with the hope of finding an approach that works for everyone.

1 Like