[clang] f934488 - [Clang][Object][SYCL][CUDA] Add --[no-]offload-embed-virtual-arch (#242407)

via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 4 16:50:39 PST 2026


Author: Srividya Sundaram
Date: 2026-12-04T16:50:31-08:00
New Revision: f934488c1a484bdb8a6267556034b2fadf30c8a1

URL: https://github.com/llvm/llvm-project/commit/f934488c1a484bdb8a6267556034b2fadf30c8a1
DIFF: https://github.com/llvm/llvm-project/commit/f934488c1a484bdb8a6267556034b2fadf30c8a1.diff

LOG: [Clang][Object][SYCL][CUDA] Add --[no-]offload-embed-virtual-arch (#242407)

Add `--[no-]offload-embed-virtual-arch` for SYCL and CUDA.

A SYCL device image compiled ahead of time for Intel GPUs keeps the
SPIR-V by default, so it can still run on other GPUs of the same IGCA
target. `--no-offload-embed-virtual-arch` drops it. `-Xarch_<IGCA
target>`, e.g. `-Xarch_igca_40r --no-offload-embed-virtual-arch`,
applies it to one IGCA target only. If `--offload-arch` also names the
IGCA target itself, e.g. `--offload-arch=xe-mtl-u,igca_30r`, the SPIR-V
for that target is kept. If nothing is compiled ahead of time for an
Intel GPU, clang warns that the option is unused.

The driver records `embed-virtual-arch=0` on the device image.
clang-linker-wrapper passes `--no-embed-virtual-arch` to
clang-sycl-linker when every non-generic device image asks for it, and
otherwise keeps the virtual architecture code and warns.
clang-sycl-linker then passes `-exclude_ir` to ocloc.

For CUDA, it controls PTX: off by default, it works like
`--[no-]cuda-include-ptx=all`, `-Xarch_<arch>` applies it to one GPU,
and the last option that applies to a GPU wins.

Added: 
    clang/test/Driver/sycl-embed-virtual-arch.cpp

Modified: 
    clang/docs/ClangLinkerWrapper.md
    clang/docs/ClangSYCLLinker.md
    clang/docs/ReleaseNotes.md
    clang/include/clang/Driver/Compilation.h
    clang/include/clang/Options/Options.td
    clang/lib/Driver/Driver.cpp
    clang/lib/Driver/ToolChains/Clang.cpp
    clang/lib/Driver/ToolChains/Cuda.cpp
    clang/test/Driver/cuda-options.cu
    clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
    clang/test/OffloadTools/clang-sycl-linker/basic.ll
    clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
    clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
    clang/tools/clang-sycl-linker/ClangSYCLLinker.cpp
    clang/tools/clang-sycl-linker/SYCLLinkOpts.td
    llvm/include/llvm/Object/OffloadBinary.h
    llvm/unittests/Object/OffloadingTest.cpp

Removed: 
    


################################################################################
diff  --git a/clang/docs/ClangLinkerWrapper.md b/clang/docs/ClangLinkerWrapper.md
index 95067559609eb5..66d7f93c61eba0 100644
--- a/clang/docs/ClangLinkerWrapper.md
+++ b/clang/docs/ClangLinkerWrapper.md
@@ -92,6 +92,20 @@ Currently, only SYCL device code for Intel GPUs has a `code` list: the
 architecture is an IGCA target, e.g. `igca_30r`, and `code` lists its Intel
 GPUs, e.g. `xe-mtl-u`.
 
+## Virtual Architecture Images
+
+The `embed-virtual-arch` string entry in an image's offload binary metadata
+records whether to embed the virtual architecture code (e.g. SPIR-V) alongside
+the code compiled ahead of time: `1` to embed it, `0` to drop it. A missing
+entry means the default for the image's offload kind. The driver writes the
+entry only when it 
diff ers from that default.
+
+Within a link group, generic images (`arch=generic`, e.g. from objects compiled
+without `--offload-arch`) are ignored. Currently only SYCL acts on this entry:
+if all other images ask to drop the virtual architecture code, the linker
+wrapper passes `--no-embed-virtual-arch` to `clang-sycl-linker`. If only some of
+them do, it warns and does not pass the flag.
+
 ## Debugging
 
 The linker wrapper performs a lot of steps internally, such as input matching,

diff  --git a/clang/docs/ClangSYCLLinker.md b/clang/docs/ClangSYCLLinker.md
index 68f2b5dbd8cd25..5fa37eff18cf2a 100644
--- a/clang/docs/ClangSYCLLinker.md
+++ b/clang/docs/ClangSYCLLinker.md
@@ -47,6 +47,7 @@ OPTIONS:
                           - 'translation_unit' (default) emits one device image per translation unit that contains at least one entry point;
                           - 'kernel' emits one device image per kernel function;
                           - 'link_unit' emits one device image per linking unit.
+  --no-embed-virtual-arch Drop the virtual architecture code from a device image compiled ahead of time for an Intel GPU
   --no-whole-archive      Disable --whole-archive for the following inputs (default state)
   --ocloc-options=<value> Options passed to ocloc for Intel GPU AOT compilation
   --opencl-aot-options=<value>
@@ -130,6 +131,10 @@ time by the runtime:
 clang-sycl-linker --triple=spirv64 --arch=igca_30r --code=xe-mtl-u --code=xe-mtl-h input.bc -o output.bin
 ```
 
+ocloc also embeds the virtual architecture code (SPIR-V) in its output, so that
+the device image can be compiled just in time for compatible GPUs not listed in
+`--code`; `--no-embed-virtual-arch` drops it (`ocloc -exclude_ir`).
+
 ### Linking with Device Libraries
 
 To link device bitcode libraries, first package them into archive files:

diff  --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index a08b457ffcf518..67f00e57a85d39 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -450,6 +450,14 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
 
 ### New Compiler Flags
 
+- Added `--[no-]offload-embed-virtual-arch` for device offloading, which
+  controls whether the virtual architecture code is embedded alongside native
+  code compiled for a real architecture. It is on by default for SYCL. For
+  CUDA, it is off by default and works like `--[no-]cuda-include-ptx=all`, and
+  `-Xarch_<arch>` can be used to set it for one GPU, like
+  `--[no-]cuda-include-ptx=<arch>`. As with `--cuda-include-ptx=`, PTX is only
+  included without `-fgpu-rdc`.
+
 - Added `-fpch-base-dir-is-cwd` to serialize precompiled header input paths
   relative to the current working directory. Paths resolve against the
   consumer's working directory when loading the PCH, allowing a build tree
@@ -1673,6 +1681,9 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
 
 #### CUDA Support
 
+- `--[no-]offload-embed-virtual-arch` now also controls PTX, behaving like
+  `--[no-]cuda-include-ptx=all`.
+
 - Fixed argument-dependent lookup for CUDA and HIP kernel launches, including
   calls to kernels declared as hidden friends. (#GH45327)
 
@@ -2007,6 +2018,14 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
   `--offload-arch` and `--no-offload-arch` must now name an Intel GPU or CPU, an
   IGCA target or `generic`. Any other value, e.g. a misspelled `xe-pcv`, is an
   error rather than a device job for a device that does not exist.
+- Added `--[no-]offload-embed-virtual-arch`. With
+  `--no-offload-embed-virtual-arch`, a SYCL device image compiled ahead of time
+  for Intel GPUs does not keep the virtual architecture code (SPIR-V) for
+  just-in-time compilation. To apply it to one IGCA target only, use
+  `-Xarch_<IGCA target>`, e.g.
+  `-Xarch_igca_40r --no-offload-embed-virtual-arch`; it then applies to all
+  Intel GPUs of that IGCA target. Don't use `--no-offload-embed-virtual-arch`
+  if the program sets specialization constants to non-default values.
 
 #### Improvements
 

diff  --git a/clang/include/clang/Driver/Compilation.h b/clang/include/clang/Driver/Compilation.h
index 29082b533365e7..72e80cf01de71b 100644
--- a/clang/include/clang/Driver/Compilation.h
+++ b/clang/include/clang/Driver/Compilation.h
@@ -16,6 +16,7 @@
 #include "clang/Driver/Util.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Option/Option.h"
@@ -105,6 +106,10 @@ class Compilation {
                  llvm::SmallVector<StringRef, 2>>
       IGCADevices;
 
+  /// The IGCA targets given directly in --offload-arch, e.g. igca_30r, for each
+  /// device toolchain.
+  llvm::DenseSet<std::pair<const ToolChain *, StringRef>> RequestedIGCATargets;
+
   /// Temporary files which should be removed on exit.
   llvm::opt::ArgStringList TempFiles;
 
@@ -273,6 +278,18 @@ class Compilation {
   ArrayRef<StringRef> getIGCADevices(const ToolChain *TC,
                                      StringRef Target) const;
 
+  /// Store that \p Target was given directly in --offload-arch for the
+  /// device toolchain \p TC.
+  void addRequestedIGCATarget(const ToolChain *TC, StringRef Target) {
+    RequestedIGCATargets.insert({TC, Target});
+  }
+
+  /// \return true if \p Target was given directly in --offload-arch for the
+  /// device toolchain \p TC.
+  bool isRequestedIGCATarget(const ToolChain *TC, StringRef Target) const {
+    return RequestedIGCATargets.contains({TC, Target});
+  }
+
   /// addTempFile - Add a file to remove on exit, and returns its
   /// argument.
   const char *addTempFile(const char *Name) {

diff  --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index c4895b584d4067..4840853a4edd2d 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -1284,6 +1284,14 @@ def no_offload_arch_EQ : CommaJoined<["--"], "no-offload-arch=">,
   HelpText<"Remove CUDA/HIP offloading device architecture (e.g. sm_35, gfx906) from the list of devices to compile for. "
            "'all' resets the list to its default value.">;
 
+defm offload_embed_virtual_arch : BoolOptionWithoutMarshalling<"",
+  "offload-embed-virtual-arch",
+  PosFlag<SetTrue, [], [ClangOption], "Embed the virtual architecture code "
+    "alongside native code compiled for a real architecture (default on for "
+    "SYCL, off for CUDA). For CUDA, it works like --cuda-include-ptx=all">,
+  NegFlag<SetFalse, [], [ClangOption], "Do not embed the virtual architecture "
+    "code alongside native code compiled for a real architecture">,
+  BothFlags<[]>, ["--"]>;
 def offload_new_driver : Flag<["--"], "offload-new-driver">,
   Visibility<[ClangOption, CC1Option]>, Group<f_Group>,
   HelpText<"Deprecated; the new driver is always used for offloading compilation.">;

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 5857b84c875fe0..8ef3f4ac88f928 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4165,8 +4165,8 @@ Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
   Args.ClaimAllArgs(options::OPT_no_offload_arch_EQ);
 
   // For SYCL, compile once per IGCA target, e.g. once for igca_30r for both
-  // xe-mtl-u and xe-mtl-h, and record its Intel GPUs for ahead-of-time
-  // compilation.
+  // xe-mtl-u and xe-mtl-h. Record the Intel GPUs to compile for ahead of time,
+  // and the IGCA targets given directly in --offload-arch.
   // TODO: Do this for other offload kinds too. Their SPIR-V device link
   // (spirv-link or llvm-lto) doesn't run ocloc for the "code" list yet; only
   // the SYCL device link (clang-sycl-linker) does.
@@ -4181,6 +4181,8 @@ Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
       Targets.insert(Target);
       if (ID.isIntelGPU())
         C.addIGCADevice(&TC, Target, Arch);
+      else if (ID.isIntelIGCA())
+        C.addRequestedIGCATarget(&TC, Arch);
     }
     Archs = std::move(Targets);
   }

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp
index 3aed205c99831f..7fad127516ab99 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -44,6 +44,7 @@
 #include "llvm/Config/llvm-config.h"
 #include "llvm/Frontend/Debug/Options.h"
 #include "llvm/Object/ObjectFile.h"
+#include "llvm/Object/OffloadBinary.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/ProfileData/InstrProfReader.h"
 #include "llvm/Support/CodeGen.h"
@@ -9803,9 +9804,23 @@ void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
     // Add one "code=" per Intel GPU requested for this IGCA target.
     // llvm-offload-binary joins them, so the image gets
     // "code=xe-mtl-h,xe-mtl-u".
-    for (StringRef Device : C.getIGCADevices(TC, Arch.ArchName))
+    ArrayRef<StringRef> Devices = C.getIGCADevices(TC, Arch.ArchName);
+    for (StringRef Device : Devices)
       Parts.emplace_back("code=" + Device.str());
 
+    // Ask to drop the virtual architecture code only for device code that is
+    // compiled ahead of time, and keep it if the user also gave the IGCA
+    // target itself in --offload-arch. The option is read only after the
+    // other checks, so it is reported as unused where it has no effect.
+    bool DropVirtualArch =
+        !Devices.empty() && !C.isRequestedIGCATarget(TC, Arch.ArchName) &&
+        !TCArgs.hasFlag(options::OPT_offload_embed_virtual_arch,
+                        options::OPT_no_offload_embed_virtual_arch,
+                        llvm::object::embedsVirtualArchByDefault(
+                            llvm::object::getOffloadKind(Kind)));
+    if (DropVirtualArch)
+      Parts.emplace_back("embed-virtual-arch=0");
+
     if (TC->isUsingLTO(TCArgs, OffloadAction->getOffloadingDeviceKind()))
       for (StringRef Feature : FeatureArgs)
         Parts.emplace_back("feature=" + Feature.str());

diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp b/clang/lib/Driver/ToolChains/Cuda.cpp
index 3082c3ac11e93f..8bdf86e2f97b5b 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Config/llvm-config.h" // for LLVM_HOST_TRIPLE
+#include "llvm/Object/OffloadBinary.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
@@ -531,20 +532,27 @@ void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
       Exec, CmdArgs, Inputs, Output));
 }
 
-static bool shouldIncludePTX(const ArgList &Args, StringRef InputArch) {
-  bool includePTX = false;
+/// \return true if PTX for \p InputArch, compiled for offload kind \p Kind,
+/// should be included in the fat binary. --[no-]offload-embed-virtual-arch
+/// works like --[no-]cuda-include-ptx=all, and the last option that applies to
+/// \p InputArch wins.
+static bool shouldIncludePTX(const ArgList &Args, StringRef InputArch,
+                             Action::OffloadKind Kind) {
+  bool IncludePTX = llvm::object::embedsVirtualArchByDefault(
+      llvm::object::getOffloadKind(Action::GetOffloadKindName(Kind)));
   for (Arg *A : Args.filtered(options::OPT_cuda_include_ptx_EQ,
-                              options::OPT_no_cuda_include_ptx_EQ)) {
+                              options::OPT_no_cuda_include_ptx_EQ,
+                              options::OPT_offload_embed_virtual_arch,
+                              options::OPT_no_offload_embed_virtual_arch)) {
     A->claim();
-    const StringRef ArchStr = A->getValue();
-    if (A->getOption().matches(options::OPT_cuda_include_ptx_EQ) &&
-        (ArchStr == "all" || ArchStr == InputArch))
-      includePTX = true;
-    else if (A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ) &&
-             (ArchStr == "all" || ArchStr == InputArch))
-      includePTX = false;
+    // --[no-]offload-embed-virtual-arch has no value and applies to all GPUs.
+    StringRef Arch = A->getNumValues() ? A->getValue() : "all";
+    if (Arch == "all" || Arch == InputArch)
+      IncludePTX =
+          A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
+          A->getOption().matches(options::OPT_offload_embed_virtual_arch);
   }
-  return includePTX;
+  return IncludePTX;
 }
 
 // All inputs to this linker must be from CudaDeviceActions, as we need to look
@@ -578,8 +586,12 @@ void NVPTX::FatBinary::ConstructJob(Compilation &C, const JobAction &JA,
     assert(!GpuArch.empty() &&
            "Device action expected to have associated a GPU architecture!");
 
+    // Read the PTX options from this GPU's own arguments, so that
+    // -Xarch_<arch> --[no-]offload-embed-virtual-arch applies to it only.
+    Action::OffloadKind DeviceKind = A->getOffloadingDeviceKind();
     if (II.getType() == types::TY_PP_Asm &&
-        !shouldIncludePTX(Args, GpuArch.ArchName))
+        !shouldIncludePTX(C.getArgsForToolChain(&TC, GpuArch, DeviceKind),
+                          GpuArch.ArchName, DeviceKind))
       continue;
     StringRef Kind = (II.getType() == types::TY_PP_Asm) ? "ptx" : "elf";
     CmdArgs.push_back(Args.MakeArgString(

diff  --git a/clang/test/Driver/cuda-options.cu b/clang/test/Driver/cuda-options.cu
index 704d87b34eb53b..ffa4e51b261de1 100644
--- a/clang/test/Driver/cuda-options.cu
+++ b/clang/test/Driver/cuda-options.cu
@@ -186,6 +186,36 @@
 // RUN:   -c %s 2>&1 \
 // RUN: | FileCheck -check-prefixes FATBIN-COMMON,PTX-SM60,PTX-SM52 %s
 
+// f) --[no-]offload-embed-virtual-arch works like --[no-]cuda-include-ptx=all,
+// and the last option that applies to a GPU wins.
+// RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -nogpuinc \
+// RUN:   --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_52 \
+// RUN:   --offload-embed-virtual-arch -c %s 2>&1 \
+// RUN: | FileCheck -check-prefixes FATBIN-COMMON,PTX-SM60,PTX-SM52 %s
+// RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -nogpuinc \
+// RUN:   --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_52 \
+// RUN:   --offload-embed-virtual-arch --no-cuda-include-ptx=sm_52 -c %s 2>&1 \
+// RUN: | FileCheck -check-prefixes FATBIN-COMMON,PTX-SM60,NOPTX-SM52 %s
+// RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -nogpuinc \
+// RUN:   --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_52 \
+// RUN:   --no-offload-embed-virtual-arch --cuda-include-ptx=sm_60 -c %s 2>&1 \
+// RUN: | FileCheck -check-prefixes FATBIN-COMMON,PTX-SM60,NOPTX-SM52 %s
+// RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -nogpuinc \
+// RUN:   --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_52 \
+// RUN:   --cuda-include-ptx=sm_60 --no-offload-embed-virtual-arch -c %s 2>&1 \
+// RUN: | FileCheck -check-prefixes FATBIN-COMMON,NOPTX-SM60,NOPTX-SM52 %s
+
+// g) -Xarch_<arch> --[no-]offload-embed-virtual-arch applies to that GPU only.
+// RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -nogpuinc \
+// RUN:   --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_52 \
+// RUN:   -Xarch_sm_60 --offload-embed-virtual-arch -c %s 2>&1 \
+// RUN: | FileCheck -check-prefixes FATBIN-COMMON,PTX-SM60,NOPTX-SM52 %s
+// RUN: %clang -### --target=x86_64-linux-gnu -nogpulib -nogpuinc \
+// RUN:   --cuda-gpu-arch=sm_60 --cuda-gpu-arch=sm_52 \
+// RUN:   --offload-embed-virtual-arch -Xarch_sm_52 --no-offload-embed-virtual-arch \
+// RUN:   -c %s 2>&1 \
+// RUN: | FileCheck -check-prefixes FATBIN-COMMON,PTX-SM60,NOPTX-SM52 %s
+
 // Verify -flto=thin -fwhole-program-vtables handling. This should result in
 // both options being passed to the host compilation, with neither passed to
 // the device compilation.

diff  --git a/clang/test/Driver/sycl-embed-virtual-arch.cpp b/clang/test/Driver/sycl-embed-virtual-arch.cpp
new file mode 100644
index 00000000000000..83507c1c6ac97f
--- /dev/null
+++ b/clang/test/Driver/sycl-embed-virtual-arch.cpp
@@ -0,0 +1,56 @@
+/// Tests for --[no-]offload-embed-virtual-arch with SYCL.
+
+/// By default, or with --offload-embed-virtual-arch, no embed-virtual-arch
+/// entry is recorded, since keeping the virtual architecture code is the SYCL
+/// default.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --offload-arch=xe-mtl-u -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=EMBED %s
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --offload-arch=xe-mtl-u --no-offload-embed-virtual-arch \
+// RUN:   --offload-embed-virtual-arch -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=EMBED %s
+// EMBED: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=igca_30r,kind=sycl,code=xe-mtl-u"{{$}}
+
+/// --no-offload-embed-virtual-arch is recorded for a device image compiled
+/// ahead of time.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --offload-arch=xe-mtl-u --no-offload-embed-virtual-arch -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=NO-EMBED %s
+// NO-EMBED: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=igca_30r,kind=sycl,code=xe-mtl-u,embed-virtual-arch=0"{{$}}
+
+/// Where the option can't do anything, it is reported as unused.
+// UNUSED: warning: argument unused during compilation: '--no-offload-embed-virtual-arch'
+
+/// It has no effect for an IGCA target given in --offload-arch, so it is
+/// reported as unused.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --offload-arch=igca_30r --no-offload-embed-virtual-arch -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefixes=DIRECT,UNUSED %s
+// DIRECT: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=igca_30r,kind=sycl"{{$}}
+
+/// It still has no effect when one of the IGCA target's Intel GPUs is also
+/// given, so it is reported as unused.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --offload-arch=xe-mtl-u,igca_30r --no-offload-embed-virtual-arch \
+// RUN:   -c %s 2>&1 | FileCheck -check-prefixes=UNUSED,BOTH %s
+// BOTH: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=igca_30r,kind=sycl,code=xe-mtl-u"{{$}}
+
+/// With -Xarch_, it applies only to the device compile for that IGCA target.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --offload-arch=xe-mtl-u,xe-bmg-g21 \
+// RUN:   -Xarch_igca_40r --no-offload-embed-virtual-arch -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=XARCH %s
+// XARCH-DAG: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=igca_30r,kind=sycl,code=xe-mtl-u"
+// XARCH-DAG: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=igca_40r,kind=sycl,code=xe-bmg-g21,embed-virtual-arch=0"
+
+/// It has no effect without --offload-arch, so it is reported as unused.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fsycl \
+// RUN:   --no-offload-embed-virtual-arch -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefixes=GENERIC,UNUSED %s
+// GENERIC: "--image=file={{[^"]*}},triple=spirv64-unknown-unknown,arch=generic,kind=sycl"{{$}}
+
+/// It has no effect for OpenMP currently, so it is reported as unused.
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp \
+// RUN:   --offload-arch=sm_70 -nogpulib --no-offload-embed-virtual-arch -c %s \
+// RUN:   2>&1 | FileCheck -check-prefix=UNUSED %s

diff  --git a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
index d468ed4e314318..bc35fc298af453 100644
--- a/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
+++ b/clang/test/OffloadTools/clang-linker-wrapper/linker-wrapper.c
@@ -132,6 +132,18 @@ __attribute__((visibility("protected"), used)) int x;
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \
 // RUN:   --save-temps --wrapper-verbose --linker-path=/usr/bin/ld %t.sycl-mix.o \
 // RUN:   -o a.out 2>&1 | FileCheck %s --check-prefix=SYCL-REPLAY
+// RUN: llvm-offload-binary -o %t.sycl-noembed.out \
+// RUN:   --image=file=%t.spirv.bc,kind=sycl,triple=spirv64-unknown-unknown,arch=igca_30r,code=xe-mtl-u,embed-virtual-arch=0
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.sycl-noembed.o -fembed-offload-object=%t.sycl-noembed.out
+// Two images that both ask to drop the virtual architecture code, plus a
+// generic archive member that is ignored.
+// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld %t.sycl-noembed.o %t.sycl-noembed.o \
+// RUN:   %t.sycl-generic.a -o a.out 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=SYCL-NO-EMBED
+// RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \
+// RUN:   --linker-path=/usr/bin/ld %t.sycl-noembed.o %t.sycl-u.o -o a.out 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=SYCL-SOME-NO-EMBED
 // RUN: llvm-offload-binary -o %t.openmp-code.out \
 // RUN:   --image=file=%t.elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70,code=a \
 // RUN:   --image=file=%t.elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70,code=b
@@ -182,6 +194,15 @@ __attribute__((visibility("protected"), used)) int x;
 // OPENMP-CODE-COUNT-2: clang{{.*}} --target=nvptx64-nvidia-cuda -march=sm_70 {{[^ ]*}}.o{{$}}
 // OPENMP-CODE-NOT:     --target=nvptx64-nvidia-cuda
 
+// --no-embed-virtual-arch is passed only if all non-generic device images ask
+// for it. A generic archive member is ignored.
+// SYCL-NO-EMBED-NOT: warning:
+// SYCL-NO-EMBED: clang{{.*}} -march=igca_30r {{.*}} --sycl-link -Xlinker --code=xe-mtl-u -Xlinker --no-embed-virtual-arch{{$}}
+// SYCL-SOME-NO-EMBED: warning: not all device images for 'igca_30r' with code 'xe-mtl-u' were compiled with --no-offload-embed-virtual-arch; keeping the virtual architecture code
+// SYCL-SOME-NO-EMBED:      clang{{.*}} -march=igca_30r
+// SYCL-SOME-NO-EMBED-NOT:  --no-embed-virtual-arch
+// SYCL-SOME-NO-EMBED-SAME: --sycl-link -Xlinker --code=xe-mtl-u{{$}}
+
 // The replayed extraction of an image without "code" does not also match one
 // with "code" for the same "arch".
 // SYCL-REPLAY: llvm-offload-binary{{.*}} --image=kind=sycl,triple=spirv64-unknown-unknown,arch=igca_30r,code=,file={{[^ ]*}}-igca_30r.o --image=kind=sycl,triple=spirv64-unknown-unknown,arch=igca_30r,code=xe-mtl-u,file={{[^ ]*}}-igca_30r.xe-mtl-u.o

diff  --git a/clang/test/OffloadTools/clang-sycl-linker/basic.ll b/clang/test/OffloadTools/clang-sycl-linker/basic.ll
index a7dac710891fd6..68f54c43482ebb 100644
--- a/clang/test/OffloadTools/clang-sycl-linker/basic.ll
+++ b/clang/test/OffloadTools/clang-sycl-linker/basic.ll
@@ -134,6 +134,15 @@
 ; AOT-IGCA-NEXT: sycl-bundle: image kind: o, triple: spirv64-unknown-unknown, arch: igca_30r
 ; AOT-IGCA-NOT:  {{.+}}
 ;
+; Test that --no-embed-virtual-arch passes -exclude_ir to ocloc.
+; RUN: clang-sycl-linker --dry-run -v --module-split-mode=link_unit -arch=igca_30r --code=xe-mtl-u --no-embed-virtual-arch %t/input1.bc %t/input2.bc -o %t/aot-igca-noembed.out 2>&1 \
+; RUN:   | FileCheck %s --check-prefix=AOT-IGCA-NO-EMBED
+; AOT-IGCA-NO-EMBED: "{{.*}}ocloc{{.*}}" {{.*}}-device xe-mtl-u -exclude_ir -output
+;
+; Test that --no-embed-virtual-arch has no effect without --code.
+; RUN: clang-sycl-linker --dry-run -v --module-split-mode=link_unit -arch=igca_30r --no-embed-virtual-arch %t/input1.bc %t/input2.bc -o %t/jit-igca-noembed.out 2>&1 \
+; RUN:   | FileCheck %s --check-prefix=JIT-IGCA
+;
 ; Test that an IGCA target without --code is kept as SPIR-V.
 ; RUN: clang-sycl-linker --dry-run -v --module-split-mode=link_unit -arch=igca_30r %t/input1.bc %t/input2.bc -o %t/jit-igca.out 2>&1 \
 ; RUN:   | FileCheck %s --check-prefix=JIT-IGCA
@@ -142,6 +151,12 @@
 ; JIT-IGCA-NEXT: sycl-bundle: image kind: spv, triple: spirv64-unknown-unknown, arch: igca_30r
 ; JIT-IGCA-NOT:  {{.+}}
 ;
+; Test that --no-embed-virtual-arch has no effect for an Intel CPU.
+; RUN: clang-sycl-linker --dry-run -v --module-split-mode=link_unit -arch=graniterapids --no-embed-virtual-arch %t/input1.bc %t/input2.bc -o %t/aot-cpu-noembed.out 2>&1 \
+; RUN:   | FileCheck %s --check-prefix=AOT-INTEL-CPU-NO-EMBED
+; AOT-INTEL-CPU-NO-EMBED-NOT:  -exclude_ir
+; AOT-INTEL-CPU-NO-EMBED:      sycl-bundle: image kind: o, triple: spirv64-unknown-unknown, arch: graniterapids
+;
 ; Test AOT compilation for an Intel CPU.
 ; Test that IMG_Object image kind is set for AOT compilation (Intel CPU).
 ; RUN: clang-sycl-linker --dry-run -v --module-split-mode=link_unit -arch=graniterapids %t/input1.bc %t/input2.bc -o %t/aot-cpu.out 2>&1 \

diff  --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 9b360ae57d9bbe..0bec4442e89bf7 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -125,6 +125,9 @@ static std::string CudaBinaryPath;
 /// Mutex lock to protect writes to shared TempFiles in parallel.
 static std::mutex TempFilesMutex;
 
+/// Serializes warnings emitted by device links that run in parallel.
+static std::mutex WarningMutex;
+
 /// Temporary files created by the linker wrapper.
 static std::list<SmallString<128>> TempFiles;
 
@@ -597,6 +600,8 @@ Expected<StringRef> clang(ArrayRef<StringRef> InputFiles, const ArgList &Args,
     CmdArgs.push_back("--sycl-link");
     for (const std::string &Device : Devices)
       CmdArgs.append({"-Xlinker", Args.MakeArgString("--code=" + Device)});
+    if (Args.hasArg(OPT_no_embed_virtual_arch))
+      CmdArgs.append({"-Xlinker", "--no-embed-virtual-arch"});
   }
 
   for (StringRef Arg : Args.getAllArgValues(OPT_linker_arg_EQ))
@@ -1097,6 +1102,38 @@ DerivedArgList getLinkerArgs(ArrayRef<OffloadFile> Input,
     DAL.AddJoinedArg(nullptr, Tbl.getOption(OPT_code_EQ),
                      Args.MakeArgString(Device));
 
+  // Pass --no-embed-virtual-arch only if there is at least one non-generic
+  // image (generic ones, arch=generic, come from objects compiled without
+  // --offload-arch), and all of them ask to drop the virtual architecture
+  // code. A missing "embed-virtual-arch" entry means the default for the
+  // image's offload kind.
+  size_t NumNonGenericImages = 0;
+  size_t NumNonGenericAskingToDrop = 0;
+  for (const OffloadFile &File : Input) {
+    const OffloadBinary &Image = *File.getBinary();
+    if (Image.getArch() == "generic")
+      continue;
+    ++NumNonGenericImages;
+    StringRef Embed = Image.getString("embed-virtual-arch");
+    bool KeepsVirtualArch =
+        Embed.empty() ? embedsVirtualArchByDefault(Image.getOffloadKind())
+                      : Embed != "0";
+    if (!KeepsVirtualArch)
+      ++NumNonGenericAskingToDrop;
+  }
+  if (NumNonGenericImages > 0 &&
+      NumNonGenericAskingToDrop == NumNonGenericImages) {
+    DAL.AddFlagArg(nullptr, Tbl.getOption(OPT_no_embed_virtual_arch));
+  } else if (NumNonGenericAskingToDrop > 0) {
+    std::scoped_lock<std::mutex> Lock(WarningMutex);
+    raw_ostream &Warning = WithColor::warning(errs(), LinkerExecutable);
+    Warning << "not all device images for '" << Binary.getArch() << "'";
+    if (StringRef Code = Binary.getString("code"); !Code.empty())
+      Warning << " with code '" << Code << "'";
+    Warning << " were compiled with --no-offload-embed-virtual-arch; keeping "
+               "the virtual architecture code\n";
+  }
+
   // If every input file is bitcode we have whole program visibility as we
   // do only support static linking with bitcode.
   auto ContainsBitcode = [](const OffloadFile &F) {

diff  --git a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
index cfd525dad975f0..5c4e6781488c21 100644
--- a/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ b/clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -83,6 +83,10 @@ def triple_EQ : Joined<["--"], "triple=">,
 def code_EQ : Joined<["--"], "code=">,
   Flags<[DeviceOnlyOption, HelpHidden]>, MetaVarName<"<device>">,
   HelpText<"A real device to compile an image ahead of time for">;
+def no_embed_virtual_arch : Flag<["--"], "no-embed-virtual-arch">,
+  Flags<[DeviceOnlyOption, HelpHidden]>,
+  HelpText<"Drop the virtual architecture code from device code compiled "
+           "ahead of time">;
 def whole_program : Flag<["--"], "whole-program">,
   Flags<[DeviceOnlyOption, HelpHidden]>,
   HelpText<"LTO has visibility of all input files">;

diff  --git a/clang/tools/clang-sycl-linker/ClangSYCLLinker.cpp b/clang/tools/clang-sycl-linker/ClangSYCLLinker.cpp
index 6b54f215f34c12..6320f08bdddf7d 100644
--- a/clang/tools/clang-sycl-linker/ClangSYCLLinker.cpp
+++ b/clang/tools/clang-sycl-linker/ClangSYCLLinker.cpp
@@ -722,6 +722,10 @@ static Error runAOTCompileIntelGPU(StringRef InputFile, StringRef OutputFile,
   assert(!Devices.empty() && "a device must be specified for AOT compilation");
   CmdArgs.push_back("-device");
   CmdArgs.push_back(Devices);
+  // Pass -exclude_ir to ocloc to drop the SPIR-V if --no-embed-virtual-arch is
+  // given.
+  if (Args.hasArg(OPT_no_embed_virtual_arch))
+    CmdArgs.push_back("-exclude_ir");
 
   // getAllArgValues returns a temporary vector; retain it so the StringRefs
   // remain valid through the executeCommands call below.

diff  --git a/clang/tools/clang-sycl-linker/SYCLLinkOpts.td b/clang/tools/clang-sycl-linker/SYCLLinkOpts.td
index faaf3fa12fd6cc..4a0f67f451bffa 100644
--- a/clang/tools/clang-sycl-linker/SYCLLinkOpts.td
+++ b/clang/tools/clang-sycl-linker/SYCLLinkOpts.td
@@ -53,6 +53,11 @@ def code_EQ : Joined<["--", "-"], "code=">,
                        "Can be repeated. Without it, a real --arch is compiled "
                        "ahead of time and a virtual one is kept for "
                        "just-in-time compilation.">;
+def no_embed_virtual_arch : Flag<["--", "-"], "no-embed-virtual-arch">,
+                            Flags<[LinkerOnlyOption]>,
+                            HelpText<"Drop the virtual architecture code "
+                                     "from a device image compiled ahead of "
+                                     "time for an Intel GPU">;
 def triple_EQ : Joined<["--", "-"], "triple=">,
                 Flags<[LinkerOnlyOption]>,
                 MetaVarName<"<triple>">,

diff  --git a/llvm/include/llvm/Object/OffloadBinary.h b/llvm/include/llvm/Object/OffloadBinary.h
index 058432ae1a3c7e..dd8ffac5ae5117 100644
--- a/llvm/include/llvm/Object/OffloadBinary.h
+++ b/llvm/include/llvm/Object/OffloadBinary.h
@@ -283,6 +283,13 @@ LLVM_ABI OffloadKind getOffloadKind(StringRef Name);
 /// Convert an offload kind to its string representation.
 LLVM_ABI StringRef getOffloadKindName(OffloadKind Name);
 
+/// \return true if device code of offload kind \p Kind keeps the virtual
+/// architecture code by default. A missing "embed-virtual-arch" entry means
+/// this default.
+inline bool embedsVirtualArchByDefault(OffloadKind Kind) {
+  return Kind == OFK_SYCL;
+}
+
 /// Returns true if an image built for target \p Provided can provide the device
 /// code for a request for target \p Requested. This is directional: a
 /// feature-unspecified or generic image serves a more specific request (e.g. a

diff  --git a/llvm/unittests/Object/OffloadingTest.cpp b/llvm/unittests/Object/OffloadingTest.cpp
index 54c4da5257cb04..526e6237329925 100644
--- a/llvm/unittests/Object/OffloadingTest.cpp
+++ b/llvm/unittests/Object/OffloadingTest.cpp
@@ -387,3 +387,11 @@ TEST(OffloadingTest, checkTargetsWithCode) {
   // device images.
   EXPECT_TRUE(areTargetsCompatible(NoCode, Generic));
 }
+
+TEST(OffloadingTest, checkEmbedsVirtualArchByDefault) {
+  // Only SYCL keeps the virtual architecture code by default.
+  EXPECT_TRUE(embedsVirtualArchByDefault(OFK_SYCL));
+  EXPECT_FALSE(embedsVirtualArchByDefault(OFK_Cuda));
+  EXPECT_FALSE(embedsVirtualArchByDefault(OFK_HIP));
+  EXPECT_FALSE(embedsVirtualArchByDefault(OFK_OpenMP));
+}


        


More information about the cfe-commits mailing list