Skip to content

Commit b1a75dd

Browse files
[SYCL] Implement coverage instrumentation for device code (#20710)
This PR reapplies the changes from #20206. It also includes the following new changes: 1. The coverage tools were moved from compiler dependencies to E2E test dependencies so that the SYCL toolchain can be be built without `compiler-rt`. 2. A definition of `__sycl_increment_profile_counters` was added to fix build errors when building with Apple Clang. --------- Signed-off-by: Michael Aziz <[email protected]> Co-authored-by: Steffen Larsen <[email protected]>
1 parent 3f39f08 commit b1a75dd

File tree

19 files changed

+386
-43
lines changed

19 files changed

+386
-43
lines changed

buildbot/configure.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def do_configure(args, passthrough_args):
2121
if not os.path.isdir(abs_obj_dir):
2222
os.makedirs(abs_obj_dir)
2323

24-
llvm_external_projects = "sycl;llvm-spirv;opencl;xpti;xptifw"
24+
llvm_external_projects = "sycl;llvm-spirv;opencl;xpti;xptifw;compiler-rt"
2525

2626
# libdevice build requires a working SYCL toolchain, which is not the case
2727
# with macOS target right now.

clang/lib/CodeGen/BackendUtil.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1213,6 +1213,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
12131213
PB.registerPipelineStartEPCallback(
12141214
[Options](ModulePassManager &MPM, OptimizationLevel Level) {
12151215
MPM.addPass(InstrProfilingLoweringPass(*Options, false));
1216+
// The profiling pass adds SYCL device globals so we need to run
1217+
// the compile-time properties pass to update the metadata.
1218+
MPM.addPass(CompileTimePropertiesPass());
12161219
});
12171220

12181221
// TODO: Consider passing the MemoryProfileOutput to the pass builder via

clang/lib/Driver/ToolChains/Clang.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5423,6 +5423,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
54235423
CmdArgs.push_back("-fsycl-is-device");
54245424
CmdArgs.push_back("-fdeclare-spirv-builtins");
54255425

5426+
// Set the atomic profile update flag to increment counters atomically.
5427+
CmdArgs.push_back("-fprofile-update=atomic");
5428+
54265429
// Set O2 optimization level by default
54275430
if (!Args.getLastArg(options::OPT_O_Group))
54285431
CmdArgs.push_back("-O2");

clang/lib/Driver/ToolChains/SYCL.cpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1371,11 +1371,7 @@ static ArrayRef<options::ID> getUnsupportedOpts() {
13711371
options::OPT_fno_profile_generate, // -f[no-]profile-generate
13721372
options::OPT_ftest_coverage,
13731373
options::OPT_fno_test_coverage, // -f[no-]test-coverage
1374-
options::OPT_fcoverage_mapping,
1375-
options::OPT_coverage, // --coverage
1376-
options::OPT_fno_coverage_mapping, // -f[no-]coverage-mapping
1377-
options::OPT_fprofile_instr_generate,
1378-
options::OPT_fprofile_instr_generate_EQ,
1374+
options::OPT_coverage, // --coverage
13791375
options::OPT_fprofile_arcs,
13801376
options::OPT_fno_profile_arcs, // -f[no-]profile-arcs
13811377
options::OPT_fno_profile_instr_generate, // -f[no-]profile-instr-generate
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Ensure that the profile update mode is set to 'atomic' when compiling SYCL code.
2+
// RUN: %clangxx -### -fsycl -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | FileCheck %s
3+
// RUN: %clang_cl -### -fsycl -fprofile-instr-generate -fcoverage-mapping %s 2>&1 | FileCheck %s
4+
// CHECK: "-fprofile-update=atomic"

clang/test/Driver/sycl-unsupported.cpp

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,6 @@
1919
// RUN: -DOPT_CC1=-debug-info-kind=line-tables-only \
2020
// RUN: -check-prefixes=UNSUPPORTED_OPT_DIAG,UNSUPPORTED_OPT
2121

22-
// RUN: %clangxx -fsycl -fprofile-instr-generate -### %s 2>&1 \
23-
// RUN: | FileCheck %s -DARCH=spir64 -DOPT=-fprofile-instr-generate \
24-
// RUN: -DOPT_CC1=-fprofile-instrument=clang \
25-
// RUN: -check-prefixes=UNSUPPORTED_OPT_DIAG,UNSUPPORTED_OPT
26-
// RUN: %clangxx -fsycl -fcoverage-mapping \
27-
// RUN: -fprofile-instr-generate -### %s 2>&1 \
28-
// RUN: | FileCheck %s -DARCH=spir64 -DOPT=-fcoverage-mapping
2922
// RUN: %clangxx -fsycl -ftest-coverage -### %s 2>&1 \
3023
// RUN: | FileCheck %s -DARCH=spir64 -DOPT=-ftest-coverage \
3124
// RUN: -DOPT_CC1=-coverage-notes-file \
@@ -49,12 +42,6 @@
4942
// RUN: | FileCheck %s -DARCH=spir64 -DOPT=--coverage \
5043
// RUN: -DOPT_CC1=-coverage-notes-file \
5144
// RUN: -check-prefixes=UNSUPPORTED_OPT_DIAG,UNSUPPORTED_OPT
52-
// Check to make sure our '-fsanitize=address' exception isn't triggered by a
53-
// different option
54-
// RUN: %clangxx -fsycl -fprofile-instr-generate=address -### %s 2>&1 \
55-
// RUN: | FileCheck %s -DARCH=spir64 -DOPT=-fprofile-instr-generate=address \
56-
// RUN: -DOPT_CC1=-fprofile-instrument=clang \
57-
// RUN: -check-prefixes=UNSUPPORTED_OPT_DIAG,UNSUPPORTED_OPT
5845

5946
// CHECK: ignoring '[[OPT]]' option as it is not currently supported for target '[[ARCH]]{{.*}}'; only supported for host compilation [-Woption-ignored]
6047
// CHECK-NOT: clang{{.*}} "-fsycl-is-device"{{.*}} "[[OPT]]{{.*}}"

compiler-rt/lib/profile/InstrProfilingRuntime.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,22 @@ extern "C" {
1010

1111
#include "InstrProfiling.h"
1212

13+
void __sycl_increment_profile_counters(uint64_t FnHash, size_t NumCounters,
14+
const uint64_t *Increments) {
15+
for (const __llvm_profile_data *DataVar = __llvm_profile_begin_data();
16+
DataVar < __llvm_profile_end_data(); DataVar++) {
17+
if (DataVar->NameRef != FnHash || DataVar->NumCounters != NumCounters)
18+
continue;
19+
20+
uint64_t *const Counters = reinterpret_cast<uint64_t *>(
21+
reinterpret_cast<uintptr_t>(DataVar) +
22+
reinterpret_cast<uintptr_t>(DataVar->CounterPtr));
23+
for (size_t i = 0; i < NumCounters; i++)
24+
Counters[i] += Increments[i];
25+
break;
26+
}
27+
}
28+
1329
static int RegisterRuntime() {
1430
__llvm_profile_initialize();
1531
#ifdef _AIX

llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -994,6 +994,9 @@ bool InstrLowerer::lower() {
994994
if (!NeedsRuntimeHook && ContainsProfiling)
995995
emitRuntimeHook();
996996

997+
if (M.getTargetTriple().isSPIR())
998+
return true;
999+
9971000
emitRegistration();
9981001
emitUses();
9991002
emitInitialization();
@@ -1108,6 +1111,18 @@ GlobalVariable *InstrLowerer::getOrCreateBiasVar(StringRef VarName) {
11081111
}
11091112

11101113
Value *InstrLowerer::getCounterAddress(InstrProfCntrInstBase *I) {
1114+
if (M.getTargetTriple().isSPIR()) {
1115+
auto *Counters = getOrCreateRegionCounters(I);
1116+
IRBuilder<> Builder(I);
1117+
auto *Addr = Builder.CreateLoad(PointerType::get(M.getContext(), 1),
1118+
Counters, "pgocount.addr");
1119+
const std::uint64_t Index = I->getIndex()->getZExtValue();
1120+
if (Index == 0)
1121+
return Addr;
1122+
auto *Offset = Builder.getInt64(Index * sizeof(std::uint64_t));
1123+
return Builder.CreatePtrAdd(Addr, Offset, "pgocount.offset");
1124+
}
1125+
11111126
auto *Counters = getOrCreateRegionCounters(I);
11121127
IRBuilder<> Builder(I);
11131128

@@ -1648,6 +1663,22 @@ InstrLowerer::getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc) {
16481663
GlobalVariable *
16491664
InstrLowerer::createRegionCounters(InstrProfCntrInstBase *Inc, StringRef Name,
16501665
GlobalValue::LinkageTypes Linkage) {
1666+
if (M.getTargetTriple().isSPIR()) {
1667+
uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1668+
auto &Ctx = M.getContext();
1669+
auto *PtrTy = PointerType::get(Ctx, 1);
1670+
auto *IntTy = Type::getInt64Ty(Ctx);
1671+
auto *StructTy = StructType::get(Ctx, {PtrTy, IntTy});
1672+
GlobalVariable *GV = new GlobalVariable(
1673+
M, StructTy, false, Linkage, Constant::getNullValue(StructTy), Name);
1674+
const std::uint64_t FnHash = IndexedInstrProf::ComputeHash(
1675+
getPGOFuncNameVarInitializer(Inc->getName()));
1676+
const std::string FnName = std::string{"__profc_"} + std::to_string(FnHash);
1677+
GV->addAttribute("sycl-unique-id", FnName);
1678+
GV->addAttribute("sycl-device-global-size", Twine(NumCounters * 8).str());
1679+
return GV;
1680+
}
1681+
16511682
uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
16521683
auto &Ctx = M.getContext();
16531684
GlobalVariable *GV;
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
; RUN: opt < %s -passes=instrprof -S | FileCheck %s
2+
3+
target triple = "spir64-unknown-unknown"
4+
5+
@__profn_foo = private constant [3 x i8] c"foo"
6+
; CHECK: @__profc_foo = private global { ptr addrspace(1), i64 } zeroinitializer, section "__llvm_prf_cnts", comdat #0
7+
; CHECK: @__profd_foo = private global { i64, i64, i64, i64, ptr, ptr, i32, [3 x i16], i32 } { i64 {{.*}}, i64 {{.*}}, i64 sub (i64 ptrtoint (ptr @__profc_foo to i64)
8+
@__profn_bar = private constant [3 x i8] c"bar"
9+
; CHECK: @__profc_bar = private global { ptr addrspace(1), i64 } zeroinitializer, section "__llvm_prf_cnts", comdat #1
10+
; CHECK: @__profd_bar = private global { i64, i64, i64, i64, ptr, ptr, i32, [3 x i16], i32 } { i64 {{.*}}, i64 {{.*}}, i64 sub (i64 ptrtoint (ptr @__profc_bar to i64)
11+
12+
; CHECK: @__llvm_prf_nm = {{.*}} section "__llvm_prf_names"
13+
14+
define void @_Z3foov() {
15+
call void @llvm.instrprof.cover(ptr @__profn_foo, i64 12345678, i32 1, i32 0)
16+
; CHECK: %pgocount.addr = load ptr addrspace(1), ptr @__profc_foo, align 8
17+
; CHECK: store i8 0, ptr addrspace(1) %pgocount.addr, align 1
18+
ret void
19+
}
20+
21+
%class.A = type { ptr }
22+
define dso_local void @_Z3barv(ptr nocapture nonnull align 8 %0) unnamed_addr #0 align 2 {
23+
call void @llvm.instrprof.cover(ptr @__profn_bar, i64 87654321, i32 1, i32 0)
24+
; CHECK: %pgocount.addr = load ptr addrspace(1), ptr @__profc_bar, align 8
25+
; CHECK: store i8 0, ptr addrspace(1) %pgocount.addr, align 1
26+
ret void
27+
}
28+
29+
declare void @llvm.instrprof.cover(ptr, i64, i32, i32)
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Design for Device-side Code Coverage
2+
3+
## Overview
4+
5+
This document describes the design and implementation of device-side code coverage for SYCL, extending Clang's source-based code coverage to support device code. The approach leverages the existing SYCL device global infrastructure, as detailed in the [DeviceGlobal.md](DeviceGlobal.md) design document, to enable collection and aggregation of coverage data from device kernels.
6+
7+
## Design Details
8+
9+
### Profiling Counter Representation
10+
11+
Profiling counters for code coverage are lowered by the compiler as device globals. Specifically, the `InstrProfilingLoweringPass` is modified so that, when targeting SPIR-V, coverage counters are represented as pointers to USM buffers, matching the representation of other SYCL device globals. This indirection allows counters to be relocatable and managed consistently with other device-side global variables.
12+
13+
Each counter is annotated with a unique identifier (`sycl-unique-id`) of the form `__profc_<fn_hash>`, where `<fn_hash>` is a 64-bit unsigned integer uniquely identifying the instrumented function. The counter's size is also recorded via the `sycl-device-global-size` attribute. These attributes ensure that counters are discoverable and manageable by the SYCL runtime and integration headers/footers.
14+
15+
The profile counter device global is represented as an array of 8-byte integers (`std::uint64_t`). The number of elements in this array corresponds to the number of regions in the function being instrumented, where a region typically represents a distinct code branch or block. The size of the device global variable is therefore determined by multiplying the number of regions by eight bytes, and this value is recorded in the `sycl-device-global-size` attribute for use by the runtime and integration logic.
16+
17+
### Integration with Device Global Infrastructure
18+
19+
The device global infrastructure, as described in [DeviceGlobal.md](DeviceGlobal.md), provides mechanisms for mapping host and device instances of global variables, managing their lifetimes, and facilitating data transfer. Device-side coverage counters are treated as a special class of device globals:
20+
21+
- They use the shared allocation type rather than the device allocation type for the underlying USM memory.
22+
- They do not have corresponding `device_global` declarations in host code.
23+
- Their lifetime and cleanup are managed via the device global map, with integration footer code ensuring registration and deregistration.
24+
25+
### Runtime Handling and Data Aggregation
26+
27+
When a device global entry corresponding to a coverage counter is released (e.g., when a device image is unloaded), the SYCL runtime aggregates the values from the device-side counter into the equivalent host-side counter. Equivalence is determined by matching both the `<fn_hash>` and the number of counter regions. If no matching host-side counter exists—typically due to differences in code between host and device caused by the `__SYCL_DEVICE_ONLY__` macro—the device-side counter values are discarded.
28+
29+
The aggregation is performed by invoking a new function in the compiler runtime, `__sycl_increment_profile_counters`, which is weakly linked to accommodate optional runtime availability. This function accepts the `<fn_hash>`, the number of regions, and the increment values, and updates the host-side counters accordingly. At program exit, the final profile data reflects the sum of host and device coverage counters.
30+
31+
### Compiler and Runtime Changes
32+
33+
#### Compiler Frontend
34+
35+
- The lowering pass for coverage counters is updated to emit device globals with the appropriate attributes and indirection.
36+
- Integration headers and footers are updated to register device global counters with the runtime, using the unique identifier and size.
37+
38+
#### SYCL Runtime
39+
40+
- Device globals with IDs matching the `__profc_<fn_hash>` pattern are recognized as coverage counters.
41+
- USM allocation and management for counters is handled as for other device globals, but without host-side declarations.
42+
- Upon cleanup, device-side counter values are aggregated into host-side counters via the runtime API.
43+
44+
#### Compiler Runtime
45+
46+
- The new function `__sycl_increment_profile_counters` is introduced to update host-side counters.
47+
- The function is weakly linked to allow for optional inclusion.
48+
49+
### Limitations and Considerations
50+
51+
- The feature is currently implemented only for SPIR-V targets; CUDA and HIP backends are not supported.
52+
- Devices lacking support for device globals cannot utilize device-side code coverage.
53+
- Differences in code between host and device (e.g., due to `__SYCL_DEVICE_ONLY__`) may prevent aggregation of coverage data for some functions.
54+
- The design relies on the robustness of the device global infrastructure for correct mapping and lifetime management.
55+
56+
## Relationship to Device Global Design
57+
58+
This feature is built upon the mechanisms described in [DeviceGlobal.md](DeviceGlobal.md), including:
59+
60+
- Use of unique string identifiers (`sycl-unique-id`) for mapping and management.
61+
- USM-based allocation and zero-initialization of device-side storage.
62+
- Integration header/footer registration for host-device correlation.
63+
- Runtime database for device global management and lookup.
64+
65+
The code coverage counters are a specialized use case of device globals, with additional logic for aggregation and profile generation.
66+
67+
## References
68+
69+
- [Implementation design for SYCL device globals](DeviceGlobal.md)
70+
- [Clang Source-based Code Coverage](https://clang.llvm.org/docs/SourceBasedCodeCoverage.html)
71+
- [SYCL Specification](https://registry.khronos.org/SYCL/specs/sycl-2020/html/sycl-2020.html)

0 commit comments

Comments
 (0)