Skip to content

Commit f444525

Browse files
[SYCL] Implement coverage instrumentation for device code (#20206)
This PR extends Clang's source-based code coverage to work with SYCL device code. It includes the following changes: 1. The `InstrProfilingLoweringPass` was updated to lower profiling counters to SYCL device globals. 2. A new function was added to the compiler runtime to increment the host-side profiling counters. 3. The SYCL runtime was updated to send the contents of the device-side profiling counters to the new compiler runtime function when their device global map entries are being freed. This feature may not work correctly for functions that differ between host and device due to the use of the `__SYCL_DEVICE_ONLY__` macro. In such cases, it may not be possible to correlate the profiling counters from the device to the host. Resolves #7803. --------- Signed-off-by: Michael Aziz <[email protected]> Co-authored-by: Steffen Larsen <[email protected]>
1 parent 26e0212 commit f444525

File tree

17 files changed

+370
-43
lines changed

17 files changed

+370
-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/Driver/ToolChains/Clang.cpp

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

5483+
// Set the atomic profile update flag to increment counters atomically.
5484+
CmdArgs.push_back("-fprofile-update=atomic");
5485+
54835486
// Set O2 optimization level by default
54845487
if (!Args.getLastArg(options::OPT_O_Group))
54855488
CmdArgs.push_back("-O2");

clang/lib/Driver/ToolChains/SYCL.cpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1575,11 +1575,7 @@ static ArrayRef<options::ID> getUnsupportedOpts() {
15751575
options::OPT_fno_profile_generate, // -f[no-]profile-generate
15761576
options::OPT_ftest_coverage,
15771577
options::OPT_fno_test_coverage, // -f[no-]test-coverage
1578-
options::OPT_fcoverage_mapping,
1579-
options::OPT_coverage, // --coverage
1580-
options::OPT_fno_coverage_mapping, // -f[no-]coverage-mapping
1581-
options::OPT_fprofile_instr_generate,
1582-
options::OPT_fprofile_instr_generate_EQ,
1578+
options::OPT_coverage, // --coverage
15831579
options::OPT_fprofile_arcs,
15841580
options::OPT_fno_profile_arcs, // -f[no-]profile-arcs
15851581
options::OPT_fno_profile_instr_generate, // -f[no-]profile-instr-generate

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
@@ -1002,6 +1002,9 @@ bool InstrLowerer::lower() {
10021002
if (!NeedsRuntimeHook && ContainsProfiling)
10031003
emitRuntimeHook();
10041004

1005+
if (M.getTargetTriple().isSPIR())
1006+
return true;
1007+
10051008
emitRegistration();
10061009
emitUses();
10071010
emitInitialization();
@@ -1116,6 +1119,18 @@ GlobalVariable *InstrLowerer::getOrCreateBiasVar(StringRef VarName) {
11161119
}
11171120

11181121
Value *InstrLowerer::getCounterAddress(InstrProfCntrInstBase *I) {
1122+
if (M.getTargetTriple().isSPIR()) {
1123+
auto *Counters = getOrCreateRegionCounters(I);
1124+
IRBuilder<> Builder(I);
1125+
auto *Addr = Builder.CreateLoad(PointerType::get(M.getContext(), 1),
1126+
Counters, "pgocount.addr");
1127+
const std::uint64_t Index = I->getIndex()->getZExtValue();
1128+
if (Index == 0)
1129+
return Addr;
1130+
auto *Offset = Builder.getInt64(Index * sizeof(std::uint64_t));
1131+
return Builder.CreatePtrAdd(Addr, Offset, "pgocount.offset");
1132+
}
1133+
11191134
auto *Counters = getOrCreateRegionCounters(I);
11201135
IRBuilder<> Builder(I);
11211136

@@ -1657,6 +1672,22 @@ InstrLowerer::getOrCreateRegionBitmaps(InstrProfMCDCBitmapInstBase *Inc) {
16571672
GlobalVariable *
16581673
InstrLowerer::createRegionCounters(InstrProfCntrInstBase *Inc, StringRef Name,
16591674
GlobalValue::LinkageTypes Linkage) {
1675+
if (M.getTargetTriple().isSPIR()) {
1676+
uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
1677+
auto &Ctx = M.getContext();
1678+
auto *PtrTy = PointerType::get(Ctx, 1);
1679+
auto *IntTy = Type::getInt64Ty(Ctx);
1680+
auto *StructTy = StructType::get(Ctx, {PtrTy, IntTy});
1681+
GlobalVariable *GV = new GlobalVariable(
1682+
M, StructTy, false, Linkage, Constant::getNullValue(StructTy), Name);
1683+
const std::uint64_t FnHash = IndexedInstrProf::ComputeHash(
1684+
getPGOFuncNameVarInitializer(Inc->getName()));
1685+
const std::string FnName = std::string{"__profc_"} + std::to_string(FnHash);
1686+
GV->addAttribute("sycl-unique-id", FnName);
1687+
GV->addAttribute("sycl-device-global-size", Twine(NumCounters * 8).str());
1688+
return GV;
1689+
}
1690+
16601691
uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
16611692
auto &Ctx = M.getContext();
16621693
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)

sycl/CMakeLists.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,13 +389,16 @@ add_custom_target(sycl-compiler
389389
clang-offload-extract
390390
clang-offload-packager
391391
clang-linker-wrapper
392+
compiler-rt
392393
file-table-tform
393394
llc
394395
llvm-ar
395396
llvm-foreach
396397
llvm-spirv
397398
llvm-link
398399
llvm-objcopy
400+
llvm-profdata
401+
llvm-cov
399402
spirv-to-ir-wrapper
400403
sycl-post-link
401404
opencl-aot
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)

sycl/doc/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Design Documents for the oneAPI DPC++ Compiler
4040
design/ParallelForRangeRounding
4141
design/SYCLInstrumentationUsingXPTI
4242
design/ITTAnnotations
43+
design/DeviceCodeCoverage
4344
design/DeviceGlobal
4445
design/CompileTimeProperties
4546
design/HostPipes

0 commit comments

Comments
 (0)