[llvm] b3000bf - [compiler-rt] Add AMDGPU Device UndefinedBehaviorSanitizer runtime (#219972)

via llvm-commits llvm-commits at lists.llvm.org
Mon Sep 14 11:52:19 PDT 2026


Author: Joseph Huber
Date: 2026-09-14T13:52:07-05:00
New Revision: b3000bf61b40b945c196e76bfa7cd722adf09dac

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

LOG: [compiler-rt] Add AMDGPU Device UndefinedBehaviorSanitizer runtime (#219972)

Summary:
This adds support for full UBSan on the AMDGPU target. The GPU build of
`compiler-rt` will now build `libclang_rt.ubsan_standalone.a` and the
host build will now provide `libclang_rt.ubsan_offload.a` for the
host-side formatting.

The **core** approach is to simply gather arguments from the device and
replay them on the host. The RPC interface acts as the narrow shim to
pass data between the CPU and GPU.

The changes to the core runtime are kept minimal, only exposing a few
needed hooks to re-run and symbolize reports coming from an external
caller. The device archive is a side-library which will only be present
for GPU offloading builds.

Putting this in `compiler-rt` via interceptors avoids an ABI edge
between many consumers, (OpenMP, HIP, Pytorch, etc). The runtime code is
specifically built around HSA, but as more features grow this could be
refactored into a shim layer for SPIR-V / CUDA and factored out to a
common sanitizer utility. Leaving that as future work.

```console
clang -xhip -fsanitize=undefined --offload-arch=native app.hip
clang -fopenmp -fsanitize=undefined --offload-arch=native app.cpp
```

---

Tested using the HIP suite in https://github.com/ORNL/HeCBench. Ran
against 162 programs on my gfx1030 vs an unsanitized `-O3` baseline:

| Metric            | Geomean |
| ----------------- | ------: |
| Kernel time       |   2.12x |
| Wall time         |   1.58x |
| Device image size |   3.22x |
| Host binary size  |  20.43x |
| Compile time      |   1.19x |

| Resource               | Change |
| ---------------------- | -----: |
| VGPR                   |    +19 |
| SGPR                   |    +32 |
| Scratch (B/lane)       | 52/140 |
| Occupancy (waves/SIMD) | 11/140 |

The tool identified three instances of UB on the HIP device with zero
false positives.

```
atomicAggregate (6 reports)
Device: main.cu:29 signed overflow -2147483648 - 1 (int)

background-subtract (6 reports)
Device: main.cu:75 259.48 does not fit in unsigned char

particlefilter (39 reports)
Device: kernel_likelihood.h:37 signed overflow in the LCG (1103515245 * …)
```

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

Added: 
    compiler-rt/lib/ubsan/offload/CMakeLists.txt
    compiler-rt/lib/ubsan/offload/hsa.h
    compiler-rt/lib/ubsan/offload/ubsan_offload.h
    compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.cpp
    compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.h
    compiler-rt/lib/ubsan/offload/ubsan_offload_hsa_interceptors.cpp
    compiler-rt/lib/ubsan/offload/ubsan_offload_report.cpp
    compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.cpp
    compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.h
    compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.cpp
    compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.h
    compiler-rt/lib/ubsan/ubsan_handlers_internal.h
    compiler-rt/lib/ubsan/ubsan_offload.cpp
    compiler-rt/lib/ubsan/ubsan_offload_checks.inc
    compiler-rt/lib/ubsan/ubsan_offload_packet.h
    compiler-rt/test/ubsan/AMDGPU/abort.hip
    compiler-rt/test/ubsan/AMDGPU/dedup.hip
    compiler-rt/test/ubsan/AMDGPU/host-and-device.hip
    compiler-rt/test/ubsan/AMDGPU/lit.local.cfg.py
    compiler-rt/test/ubsan/AMDGPU/openmp-overflow.cpp
    compiler-rt/test/ubsan/AMDGPU/overflow-i128.hip
    compiler-rt/test/ubsan/AMDGPU/overflow.hip
    compiler-rt/test/ubsan/AMDGPU/shift.hip
    compiler-rt/test/ubsan/Inputs/hip.h

Modified: 
    compiler-rt/cmake/caches/AMDGPU.cmake
    compiler-rt/cmake/config-ix.cmake
    compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.h
    compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
    compiler-rt/lib/ubsan/CMakeLists.txt
    compiler-rt/lib/ubsan/ubsan_diag.cpp
    compiler-rt/lib/ubsan/ubsan_diag.h
    compiler-rt/lib/ubsan/ubsan_handlers.cpp
    compiler-rt/lib/ubsan/ubsan_interface.inc
    compiler-rt/lib/ubsan/ubsan_value.h
    compiler-rt/test/CMakeLists.txt
    compiler-rt/test/ubsan/CMakeLists.txt
    compiler-rt/test/ubsan/lit.common.cfg.py
    compiler-rt/test/ubsan/lit.site.cfg.py.in
    llvm/utils/gn/secondary/compiler-rt/lib/ubsan/BUILD.gn

Removed: 
    


################################################################################
diff  --git a/compiler-rt/cmake/caches/AMDGPU.cmake b/compiler-rt/cmake/caches/AMDGPU.cmake
index f3a9510c4f311..bb5ab22edaf69 100644
--- a/compiler-rt/cmake/caches/AMDGPU.cmake
+++ b/compiler-rt/cmake/caches/AMDGPU.cmake
@@ -7,7 +7,7 @@ set(COMPILER_RT_BUILD_BUILTINS ON CACHE BOOL "")
 set(COMPILER_RT_BAREMETAL_BUILD ON CACHE BOOL "")
 set(COMPILER_RT_BUILD_CRT OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_SANITIZERS ON CACHE BOOL "")
-set(COMPILER_RT_SANITIZERS_TO_BUILD "ubsan_minimal" CACHE STRING "")
+set(COMPILER_RT_SANITIZERS_TO_BUILD "ubsan;ubsan_minimal" CACHE STRING "")
 set(COMPILER_RT_BUILD_XRAY OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_LIBFUZZER OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_PROFILE ON CACHE BOOL "")

diff  --git a/compiler-rt/cmake/config-ix.cmake b/compiler-rt/cmake/config-ix.cmake
index 34a00a13f5dc0..f87dff2b7e6a5 100644
--- a/compiler-rt/cmake/config-ix.cmake
+++ b/compiler-rt/cmake/config-ix.cmake
@@ -887,8 +887,9 @@ else()
   set(COMPILER_RT_TSAN_HAS_STATIC_RUNTIME FALSE)
 endif()
 
-if (COMPILER_RT_HAS_SANITIZER_COMMON AND UBSAN_SUPPORTED_ARCH AND
-    OS_NAME MATCHES "Darwin|Linux|FreeBSD|NetBSD|Windows|Android|Fuchsia|SunOS|Haiku")
+if ((COMPILER_RT_HAS_SANITIZER_COMMON AND UBSAN_SUPPORTED_ARCH AND
+     OS_NAME MATCHES "Darwin|Linux|FreeBSD|NetBSD|Windows|Android|Fuchsia|SunOS|Haiku")
+    OR (COMPILER_RT_GPU_BUILD AND UBSAN_SUPPORTED_ARCH))
   set(COMPILER_RT_HAS_UBSAN TRUE)
 else()
   set(COMPILER_RT_HAS_UBSAN FALSE)

diff  --git a/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.h b/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.h
index bd89dc4e302fc..d2aa2288f483c 100644
--- a/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.h
+++ b/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer.h
@@ -139,6 +139,10 @@ class Symbolizer final {
   // Returns a list of symbolized frames for a given address (containing
   // all inlined functions, if necessary).
   SymbolizedStack *SymbolizePC(uptr address);
+  // Returns a list of symbolized frames given a module separate from the
+  // current executing process, such as an offloading device.
+  SymbolizedStack* SymbolizeModuleOffset(const char* module_name,
+                                         uptr module_offset);
   bool SymbolizeData(uptr address, DataInfo *info);
   bool SymbolizeFrame(uptr address, FrameInfo *info);
 

diff  --git a/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp b/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
index a6264d8229e49..b5a85c05efde7 100644
--- a/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
+++ b/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
@@ -101,6 +101,19 @@ SymbolizedStack *Symbolizer::SymbolizePC(uptr addr) {
   return res;
 }
 
+SymbolizedStack* Symbolizer::SymbolizeModuleOffset(const char* module_name,
+                                                   uptr module_offset) {
+  Lock l(&mu_);
+  SymbolizedStack* res = SymbolizedStack::New(module_offset);
+  res->info.FillModuleInfo(module_name, module_offset, kModuleArchUnknown);
+  for (auto& tool : tools_) {
+    SymbolizerScope sym_scope(this);
+    if (tool.SymbolizePC(module_offset, res))
+      return res;
+  }
+  return res;
+}
+
 bool Symbolizer::SymbolizeData(uptr addr, DataInfo *info) {
   Lock l(&mu_);
   const char *module_name = nullptr;

diff  --git a/compiler-rt/lib/ubsan/CMakeLists.txt b/compiler-rt/lib/ubsan/CMakeLists.txt
index 75a4942debd3f..9c099ba3b7f8b 100644
--- a/compiler-rt/lib/ubsan/CMakeLists.txt
+++ b/compiler-rt/lib/ubsan/CMakeLists.txt
@@ -1,5 +1,44 @@
 # Build for the undefined behavior sanitizer runtime support library.
 
+include_directories(.)
+include_directories(..)
+include_directories(../../include)
+
+# GPU targets only need the handler shims. The host interceptor archive is
+# built in the offload/ project.
+if(COMPILER_RT_GPU_BUILD)
+  include(FindLibcCommonUtils)
+  if(NOT TARGET llvm-libc-common-utilities)
+    add_compiler_rt_component(ubsan)
+    return()
+  endif()
+
+  set(UBSAN_SOURCES ubsan_offload.cpp)
+
+  set(UBSAN_HEADERS
+    ubsan_offload_packet.h
+    ubsan_offload_checks.inc
+    )
+
+  set(UBSAN_OFFLOAD_CFLAGS
+    ${SANITIZER_COMMON_CFLAGS}
+    -DSANITIZER_COMMON_NO_REDEFINE_BUILTINS)
+  append_rtti_flag(OFF UBSAN_OFFLOAD_CFLAGS)
+
+  add_compiler_rt_component(ubsan)
+
+  add_compiler_rt_runtime(clang_rt.ubsan_standalone
+    STATIC
+    ARCHS ${UBSAN_SUPPORTED_ARCH}
+    SOURCES ${UBSAN_SOURCES}
+    ADDITIONAL_HEADERS ${UBSAN_HEADERS}
+    CFLAGS ${UBSAN_OFFLOAD_CFLAGS}
+    LINK_LIBS llvm-libc-common-utilities
+    PARENT_TARGET ubsan)
+
+  return()
+endif()
+
 set(UBSAN_SOURCES
   ubsan_diag.cpp
   ubsan_init.cpp
@@ -33,6 +72,7 @@ set(UBSAN_HEADERS
   ubsan_flags.inc
   ubsan_handlers.h
   ubsan_handlers_cxx.h
+  ubsan_handlers_internal.h
   ubsan_init.h
   ubsan_interface.inc
   ubsan_monitor.h
@@ -42,9 +82,6 @@ set(UBSAN_HEADERS
   ubsan_value.h
   )
 
-include_directories(..)
-include_directories(../../include)
-
 set(UBSAN_CFLAGS ${SANITIZER_COMMON_CFLAGS})
 append_list_if(MSVC /Zl UBSAN_CFLAGS)
 append_rtti_flag(OFF UBSAN_CFLAGS)
@@ -273,4 +310,9 @@ else()
         PARENT_TARGET ubsan)
     endif()
   endif()
+
+  # Thin host interceptors for offloading. Linked with -u to keep it separate.
+  if(OS_NAME MATCHES "Linux" AND NOT ANDROID)
+    add_subdirectory(offload)
+  endif()
 endif()

diff  --git a/compiler-rt/lib/ubsan/offload/CMakeLists.txt b/compiler-rt/lib/ubsan/offload/CMakeLists.txt
new file mode 100644
index 0000000000000..c1463d1ef5558
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/CMakeLists.txt
@@ -0,0 +1,33 @@
+include(FindLibcCommonUtils)
+if(NOT TARGET llvm-libc-common-utilities)
+  return()
+endif()
+
+set(UBSAN_OFFLOAD_SOURCES
+  ubsan_offload_hsa.cpp
+  ubsan_offload_hsa_interceptors.cpp
+  ubsan_offload_rpc.cpp
+  ubsan_offload_report.cpp
+  ubsan_offload_symbolize.cpp
+  )
+
+set(UBSAN_OFFLOAD_HEADERS
+  hsa.h
+  ubsan_offload.h
+  ubsan_offload_hsa.h
+  ubsan_offload_rpc.h
+  ubsan_offload_symbolize.h
+  ../ubsan_offload_packet.h
+  ../ubsan_offload_checks.inc
+  ../ubsan_handlers_internal.h
+  )
+
+# No OBJECT_LIBS: sanitizer_common already comes from ubsan_standalone.
+add_compiler_rt_runtime(clang_rt.ubsan_offload
+  STATIC
+  ARCHS ${UBSAN_SUPPORTED_ARCH}
+  SOURCES ${UBSAN_OFFLOAD_SOURCES}
+  ADDITIONAL_HEADERS ${UBSAN_OFFLOAD_HEADERS}
+  CFLAGS ${UBSAN_CFLAGS}
+  LINK_LIBS llvm-libc-common-utilities
+  PARENT_TARGET ubsan)

diff  --git a/compiler-rt/lib/ubsan/offload/hsa.h b/compiler-rt/lib/ubsan/offload/hsa.h
new file mode 100644
index 0000000000000..636d4bb5671e5
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/hsa.h
@@ -0,0 +1,172 @@
+//===-- hsa.h ---------------------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Minimal HSA declarations without a ROCm dependency.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_HSA_DECLS_H
+#define UBSAN_HSA_DECLS_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+extern "C" {
+
+typedef struct hsa_agent_s {
+  uint64_t handle;
+} hsa_agent_t;
+typedef struct hsa_executable_s {
+  uint64_t handle;
+} hsa_executable_t;
+typedef struct hsa_executable_symbol_s {
+  uint64_t handle;
+} hsa_executable_symbol_t;
+typedef struct hsa_amd_memory_pool_s {
+  uint64_t handle;
+} hsa_amd_memory_pool_t;
+typedef struct hsa_signal_s {
+  uint64_t handle;
+} hsa_signal_t;
+typedef struct hsa_loaded_code_object_s {
+  uint64_t handle;
+} hsa_loaded_code_object_t;
+
+typedef int64_t hsa_signal_value_t;
+
+typedef enum {
+  HSA_STATUS_SUCCESS = 0,
+  HSA_STATUS_ERROR = 0x1001,
+} hsa_status_t;
+
+typedef enum {
+  HSA_DEVICE_TYPE_CPU = 0,
+  HSA_DEVICE_TYPE_GPU = 1,
+} hsa_device_type_t;
+
+typedef enum {
+  HSA_AGENT_INFO_WAVEFRONT_SIZE = 6,
+  HSA_AGENT_INFO_DEVICE = 17,
+} hsa_agent_info_t;
+
+typedef enum { HSA_AMD_SEGMENT_GLOBAL = 0 } hsa_amd_segment_t;
+
+typedef enum {
+  HSA_AMD_MEMORY_POOL_INFO_SEGMENT = 0,
+  HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS = 1,
+} hsa_amd_memory_pool_info_t;
+
+typedef enum {
+  HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED = 2,
+} hsa_amd_memory_pool_global_flag_t;
+
+typedef enum {
+  HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT = 0xA002,
+  HSA_AMD_AGENT_INFO_MAX_WAVES_PER_CU = 0xA00A,
+} hsa_amd_agent_info_t;
+
+typedef enum {
+  HSA_SIGNAL_CONDITION_NE = 1,
+} hsa_signal_condition_t;
+
+typedef enum {
+  HSA_WAIT_STATE_BLOCKED = 0,
+} hsa_wait_state_t;
+
+typedef enum {
+  HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS = 21,
+} hsa_executable_symbol_info_t;
+
+typedef enum { HSA_EXTENSION_AMD_LOADER = 0x201 } hsa_extension_t;
+
+typedef enum {
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_KIND = 2,
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_AGENT = 3,
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_CODE_OBJECT_STORAGE_TYPE = 4,
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_CODE_OBJECT_STORAGE_MEMORY_BASE =
+      5,
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_CODE_OBJECT_STORAGE_MEMORY_SIZE =
+      6,
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_LOAD_BASE = 9,
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_LOAD_SIZE = 10,
+} hsa_ven_amd_loader_loaded_code_object_info_t;
+
+typedef enum {
+  HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_KIND_AGENT = 2,
+} hsa_ven_amd_loader_loaded_code_object_kind_t;
+
+typedef enum {
+  HSA_VEN_AMD_LOADER_CODE_OBJECT_STORAGE_TYPE_MEMORY = 2,
+} hsa_ven_amd_loader_code_object_storage_type_t;
+
+// Version 1.01 of HSA_EXTENSION_AMD_LOADER. Slot order is the extension ABI.
+struct LoaderApi {
+  hsa_status_t (*QueryHostAddress)(const void *, const void **);
+  void *UnusedQuerySegmentDescriptors;
+  void *UnusedQueryExecutable;
+  hsa_status_t (*IterateLoadedCodeObjects)(
+      hsa_executable_t,
+      hsa_status_t (*)(hsa_executable_t, hsa_loaded_code_object_t, void *),
+      void *);
+  hsa_status_t (*GetCodeObjectInfo)(
+      hsa_loaded_code_object_t, hsa_ven_amd_loader_loaded_code_object_info_t,
+      void *);
+};
+static_assert(sizeof(LoaderApi) == 5 * sizeof(void *), "layout drift");
+
+hsa_status_t hsa_init(void);
+hsa_status_t hsa_shut_down(void);
+hsa_status_t hsa_iterate_agents(hsa_status_t (*callback)(hsa_agent_t, void *),
+                                void *data);
+hsa_status_t hsa_agent_get_info(hsa_agent_t agent, hsa_agent_info_t attribute,
+                                void *value);
+hsa_status_t hsa_executable_destroy(hsa_executable_t executable);
+hsa_status_t hsa_executable_freeze(hsa_executable_t executable,
+                                   const char *options);
+hsa_status_t hsa_executable_get_symbol_by_name(hsa_executable_t executable,
+                                               const char *symbol_name,
+                                               const hsa_agent_t *agent,
+                                               hsa_executable_symbol_t *symbol);
+hsa_status_t
+hsa_executable_symbol_get_info(hsa_executable_symbol_t symbol,
+                               hsa_executable_symbol_info_t attribute,
+                               void *value);
+hsa_status_t hsa_amd_memory_pool_allocate(hsa_amd_memory_pool_t memory_pool,
+                                          size_t size, uint32_t flags,
+                                          void **ptr);
+hsa_status_t hsa_amd_memory_pool_free(void *ptr);
+hsa_status_t hsa_amd_memory_pool_get_info(hsa_amd_memory_pool_t memory_pool,
+                                          hsa_amd_memory_pool_info_t attribute,
+                                          void *value);
+hsa_status_t hsa_amd_agent_iterate_memory_pools(
+    hsa_agent_t agent, hsa_status_t (*callback)(hsa_amd_memory_pool_t, void *),
+    void *data);
+hsa_status_t hsa_amd_agents_allow_access(uint32_t num_agents,
+                                         const hsa_agent_t *agents,
+                                         const uint32_t *flags,
+                                         const void *ptr);
+hsa_status_t hsa_system_get_major_extension_table(uint16_t extension,
+                                                  uint16_t version_major,
+                                                  size_t table_length,
+                                                  void *table);
+hsa_status_t hsa_memory_copy(void *dst, const void *src, size_t size);
+hsa_status_t hsa_amd_signal_create(hsa_signal_value_t initial_value,
+                                   uint32_t num_consumers,
+                                   const hsa_agent_t *consumers,
+                                   uint64_t attributes, hsa_signal_t *signal);
+hsa_status_t hsa_signal_destroy(hsa_signal_t signal);
+void hsa_signal_store_screlease(hsa_signal_t signal, hsa_signal_value_t value);
+hsa_signal_value_t hsa_signal_wait_scacquire(hsa_signal_t signal,
+                                             hsa_signal_condition_t condition,
+                                             hsa_signal_value_t compare_value,
+                                             uint64_t timeout_hint,
+                                             hsa_wait_state_t wait_state_hint);
+
+} // extern "C"
+
+#endif // UBSAN_HSA_DECLS_H

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload.h b/compiler-rt/lib/ubsan/offload/ubsan_offload.h
new file mode 100644
index 0000000000000..ec1e8a04eb0d3
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload.h
@@ -0,0 +1,34 @@
+//===-- ubsan_offload.h -----------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Host offload reporting runtime for UBSan.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_OFFLOAD_H
+#define UBSAN_OFFLOAD_H
+
+#include "sanitizer_common/sanitizer_internal_defs.h"
+#include "sanitizer_common/sanitizer_mutex.h"
+#include "ubsan_offload_packet.h"
+
+namespace __ubsan {
+
+void Initialize();
+void PrintOffloadReport(const __ubsan_offload_report &R);
+
+// Nest only after RpcMutex, the reverse deadlocks the report thread.
+extern __sanitizer::Mutex UbsanOffloadMutex;
+
+} // namespace __ubsan
+
+extern "C" {
+SANITIZER_INTERFACE_ATTRIBUTE void __ubsan_offload_init();
+}
+
+#endif // UBSAN_OFFLOAD_H

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.cpp b/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.cpp
new file mode 100644
index 0000000000000..23a18559b64d8
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.cpp
@@ -0,0 +1,368 @@
+//===-- ubsan_offload_hsa.cpp -----------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ubsan_offload_hsa.h"
+
+#include <dlfcn.h>
+
+#include "sanitizer_common/sanitizer_common.h"
+#include "sanitizer_common/sanitizer_libc.h"
+#include "ubsan_offload.h"
+#include "ubsan_offload_rpc.h"
+#include "ubsan_offload_symbolize.h"
+
+using namespace __sanitizer;
+
+namespace __ubsan {
+namespace {
+
+// Generic helpers to iterate HSA agents and pools.
+template <typename ElemTy, typename IterFuncTy, typename CallbackTy>
+hsa_status_t Iterate(IterFuncTy Func, CallbackTy Cb) {
+  auto L = [](ElemTy Elem, void *Data) -> hsa_status_t {
+    return (*static_cast<CallbackTy *>(Data))(Elem);
+  };
+  return Func(L, &Cb);
+}
+
+template <typename ElemTy, typename IterFuncTy, typename ArgTy,
+          typename CallbackTy>
+hsa_status_t Iterate(IterFuncTy Func, ArgTy Arg, CallbackTy Cb) {
+  auto L = [](ElemTy Elem, void *Data) -> hsa_status_t {
+    return (*static_cast<CallbackTy *>(Data))(Elem);
+  };
+  return Func(Arg, L, &Cb);
+}
+
+template <typename Elem1Ty, typename Elem2Ty, typename IterFuncTy,
+          typename ArgTy, typename CallbackTy>
+hsa_status_t Iterate(IterFuncTy Func, ArgTy Arg, CallbackTy Cb) {
+  auto L = [](Elem1Ty A, Elem2Ty B, void *Data) -> hsa_status_t {
+    return (*static_cast<CallbackTy *>(Data))(A, B);
+  };
+  return Func(Arg, L, &Cb);
+}
+
+void CheckHsa(hsa_status_t S) {
+  if (S == HSA_STATUS_SUCCESS)
+    return;
+  Report("ERROR: %s: HSA query failed\n", SanitizerToolName);
+  Die();
+}
+
+} // namespace
+
+template <typename Cb>
+void Hsa::ForEachAgentObject(hsa_executable_t Exec, Cb F) {
+  Iterate<hsa_executable_t, hsa_loaded_code_object_t>(
+      Loader.IterateLoadedCodeObjects, Exec,
+      [&](hsa_executable_t, hsa_loaded_code_object_t Obj) {
+        u32 Kind = 0;
+        if (Loader.GetCodeObjectInfo(
+                Obj, HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_KIND, &Kind) !=
+                HSA_STATUS_SUCCESS ||
+            Kind != HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_KIND_AGENT)
+          return HSA_STATUS_SUCCESS;
+        hsa_agent_t Agent{};
+        if (Loader.GetCodeObjectInfo(
+                Obj, HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_AGENT,
+                &Agent) != HSA_STATUS_SUCCESS ||
+            !Agent.handle)
+          return HSA_STATUS_SUCCESS;
+        F(Obj, Agent);
+        return HSA_STATUS_SUCCESS;
+      });
+}
+
+// Resolve the necessary functions to the real HSA library calls.
+bool Hsa::Resolve() {
+#define UBSAN_HSA_RESOLVE(Name)                                                \
+  Api.Name = reinterpret_cast<decltype(&::Name)>(dlsym(RTLD_NEXT, #Name));     \
+  if (!Api.Name)                                                               \
+    return false;
+  UBSAN_HSA_FUNCTIONS(UBSAN_HSA_RESOLVE)
+#undef UBSAN_HSA_RESOLVE
+  return true;
+}
+
+// Iterate the topology to discover agents. If this fails the interceptors are
+// disabled.
+bool Hsa::Discover() {
+  Agents.clear();
+  Devices.clear();
+  FineGrainedPool = {};
+  hsa_agent_t Cpu{};
+
+  CheckHsa(Iterate<hsa_agent_t>(Api.hsa_iterate_agents, [&](hsa_agent_t Agent) {
+    hsa_device_type_t Type;
+    if (hsa_status_t S =
+            Api.hsa_agent_get_info(Agent, HSA_AGENT_INFO_DEVICE, &Type))
+      return S;
+    Agents.push_back(Agent);
+    if (Type == HSA_DEVICE_TYPE_CPU && !Cpu.handle)
+      Cpu = Agent;
+    if (Type == HSA_DEVICE_TYPE_GPU)
+      Devices.push_back(Agent);
+    return HSA_STATUS_SUCCESS;
+  }));
+  if (Devices.empty())
+    return false;
+  if (!Cpu.handle) {
+    Report("ERROR: %s: no CPU HSA agent\n", SanitizerToolName);
+    Die();
+  }
+
+  CheckHsa(Iterate<hsa_amd_memory_pool_t>(
+      Api.hsa_amd_agent_iterate_memory_pools, Cpu,
+      [&](hsa_amd_memory_pool_t Pool) {
+        hsa_amd_segment_t Seg;
+        u32 Flags = 0;
+        if (hsa_status_t S = Api.hsa_amd_memory_pool_get_info(
+                Pool, HSA_AMD_MEMORY_POOL_INFO_SEGMENT, &Seg))
+          return S;
+        if (Seg != HSA_AMD_SEGMENT_GLOBAL)
+          return HSA_STATUS_SUCCESS;
+        if (hsa_status_t S = Api.hsa_amd_memory_pool_get_info(
+                Pool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &Flags))
+          return S;
+        if (Flags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED)
+          FineGrainedPool = Pool;
+        return HSA_STATUS_SUCCESS;
+      }));
+  if (!FineGrainedPool.handle) {
+    Report("ERROR: %s: no fine-grained host pool\n", SanitizerToolName);
+    Die();
+  }
+  return true;
+}
+
+// Initialize the HSA loader extension used to manage host addresses.
+bool Hsa::BindLoader() {
+  Loader = {};
+  CheckHsa(Api.hsa_system_get_major_extension_table(HSA_EXTENSION_AMD_LOADER, 1,
+                                                    sizeof(Loader), &Loader));
+  return Loader.QueryHostAddress && Loader.IterateLoadedCodeObjects &&
+         Loader.GetCodeObjectInfo;
+}
+
+bool Hsa::BindDoorbell() {
+  if (Api.hsa_amd_signal_create(0, 0, nullptr, 0, &Doorbell) !=
+      HSA_STATUS_SUCCESS)
+    return false;
+  // Mirror of the ROCr amd_signal_t, we extract the KFD interrupt slot to wake
+  // the RPC server thread.
+  struct AMDSignal {
+    int64_t Kind;
+    int64_t Value;
+    uint64_t EventMailboxPtr;
+    uint32_t EventId;
+  };
+  auto *S = reinterpret_cast<AMDSignal *>(Doorbell.handle);
+  DoorbellValue = reinterpret_cast<u64 *>(&S->Value);
+  DoorbellMailbox = reinterpret_cast<u64 *>(S->EventMailboxPtr);
+  DoorbellEvent = S->EventId;
+  return true;
+}
+
+bool Hsa::ExecutableInfo(hsa_loaded_code_object_t Obj,
+                         hsa_ven_amd_loader_loaded_code_object_info_t Attr,
+                         u64 *Out) {
+  *Out = 0;
+  return Loader.GetCodeObjectInfo(Obj, Attr, Out) == HSA_STATUS_SUCCESS;
+}
+
+bool Hsa::AddRef() { return Refs++ == 0; }
+
+bool Hsa::DropRef() {
+  if (!Refs)
+    return false;
+  if (--Refs)
+    return false;
+  atomic_store(&Active, 0, memory_order_release);
+  return true;
+}
+
+// Try to initialize all the necessary HSA state to run the sanitizer.
+bool Hsa::Init() {
+  if (atomic_load(&Active, memory_order_acquire))
+    return true;
+  if (!Resolve()) {
+    Report("ERROR: %s: cannot resolve HSA\n", SanitizerToolName);
+    Die();
+  }
+  if (!Discover())
+    return false;
+  if (!BindLoader())
+    return false;
+  if (!BindDoorbell())
+    return false;
+  VReport(1, "%s: device reporting on %zu GPU(s)\n", SanitizerToolName,
+          Devices.size());
+  atomic_store(&Active, 1, memory_order_release);
+  return true;
+}
+
+// Clear the tracked state on HSA shut down.
+void Hsa::Shutdown() {
+  atomic_store(&Active, 0, memory_order_release);
+  StopRpc();
+  Lock L(&UbsanOffloadMutex);
+  if (Refs)
+    return;
+  ForgetDeviceImages();
+  Executables.clear();
+  if (Doorbell.handle) {
+    Api.hsa_signal_destroy(Doorbell);
+    Doorbell = {};
+    DoorbellValue = nullptr;
+    DoorbellMailbox = nullptr;
+    DoorbellEvent = 0;
+  }
+  Loader = {};
+  Agents.clear();
+  Devices.clear();
+  FineGrainedPool = {};
+}
+
+// Record every executable we come accross for symbolization and address lookup.
+void Hsa::RecordExecutable(hsa_executable_t Exec) {
+  for (uptr I = 0; I < Executables.size(); ++I)
+    if (Executables[I].handle == Exec.handle)
+      return;
+  Executables.push_back(Exec);
+  ForEachAgentObject(Exec, [&](hsa_loaded_code_object_t Obj, hsa_agent_t) {
+    u64 LoadBase = 0, LoadSize = 0;
+    if (!ExecutableInfo(Obj,
+                        HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_LOAD_BASE,
+                        &LoadBase) ||
+        !ExecutableInfo(Obj,
+                        HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_LOAD_SIZE,
+                        &LoadSize) ||
+        !LoadBase || !LoadSize)
+      return;
+
+    u64 StorageType = 0, StorageBase = 0, StorageSize = 0;
+    const void *Storage = nullptr;
+    if (ExecutableInfo(
+            Obj,
+            HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_CODE_OBJECT_STORAGE_TYPE,
+            &StorageType) &&
+        StorageType == HSA_VEN_AMD_LOADER_CODE_OBJECT_STORAGE_TYPE_MEMORY &&
+        ExecutableInfo(
+            Obj,
+            HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_CODE_OBJECT_STORAGE_MEMORY_BASE,
+            &StorageBase) &&
+        ExecutableInfo(
+            Obj,
+            HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_CODE_OBJECT_STORAGE_MEMORY_SIZE,
+            &StorageSize) &&
+        StorageBase && StorageSize)
+      Storage = reinterpret_cast<const void *>(StorageBase);
+
+    TrackDeviceImage((uptr)LoadBase, (uptr)LoadSize, Storage,
+                     (uptr)StorageSize);
+  });
+}
+
+// Remove an executable on runtime unload.
+void Hsa::ForgetExecutable(hsa_executable_t Exec) {
+  ForEachAgentObject(Exec, [&](hsa_loaded_code_object_t Obj, hsa_agent_t) {
+    u64 LoadBase = 0;
+    if (ExecutableInfo(Obj,
+                       HSA_VEN_AMD_LOADER_LOADED_CODE_OBJECT_INFO_LOAD_BASE,
+                       &LoadBase) &&
+        LoadBase)
+      ForgetDeviceImage((uptr)LoadBase);
+  });
+  for (uptr I = 0; I < Executables.size(); ++I) {
+    if (Executables[I].handle != Exec.handle)
+      continue;
+    if (I + 1 != Executables.size())
+      Executables[I] = Executables.back();
+    Executables.pop_back();
+    break;
+  }
+}
+
+// Allocate coherent 'fine-grained' memory for host and device communication.
+bool Hsa::AllocFineGrained(uptr Bytes, void **Out) {
+  void *P = nullptr;
+  if (!FineGrainedPool.handle ||
+      Api.hsa_amd_memory_pool_allocate(FineGrainedPool, Bytes, 0, &P) !=
+          HSA_STATUS_SUCCESS ||
+      !P)
+    return false;
+  if (Api.hsa_amd_agents_allow_access(Agents.size(), Agents.data(), nullptr,
+                                      P) != HSA_STATUS_SUCCESS) {
+    Api.hsa_amd_memory_pool_free(P);
+    return false;
+  }
+  *Out = P;
+  return true;
+}
+
+void Hsa::Free(void *P) { Api.hsa_amd_memory_pool_free(P); }
+
+bool Hsa::Copy(void *Dst, const void *Src, uptr N) {
+  return Api.hsa_memory_copy(Dst, Src, N) == HSA_STATUS_SUCCESS;
+}
+
+// The runtime knows the original host address of a device pointer that is
+// located inside one of the loaded segments, accesses read-only data we need.
+const void *Hsa::HostAddr(uptr Dev) {
+  if (!Dev)
+    return nullptr;
+  const void *Host = nullptr;
+  if (Loader.QueryHostAddress(reinterpret_cast<const void *>(Dev), &Host) !=
+      HSA_STATUS_SUCCESS)
+    return nullptr;
+  return Host;
+}
+
+// Look up the device address of a named variables in a loaded executable.
+bool Hsa::SymbolAddr(hsa_executable_t Exec, const char *Name, hsa_agent_t Agent,
+                     u64 *Addr) {
+  hsa_executable_symbol_t Symbol;
+  if (Api.hsa_executable_get_symbol_by_name(Exec, Name, &Agent, &Symbol) !=
+      HSA_STATUS_SUCCESS)
+    return false;
+  *Addr = 0;
+  return Api.hsa_executable_symbol_get_info(
+             Symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS, Addr) ==
+             HSA_STATUS_SUCCESS &&
+         *Addr;
+}
+
+// The RPC interface is deliberately sized to the hardware parallel limits of
+// the device to make deadlock impossible.
+void Hsa::RpcInfo(hsa_agent_t Agent, u32 *Lanes, u32 *Waves) {
+  u32 CUs = 0, WavesPerCU = 0;
+  CheckHsa(Api.hsa_agent_get_info(Agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, Lanes));
+  CheckHsa(Api.hsa_agent_get_info(
+      Agent,
+      static_cast<hsa_agent_info_t>(HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT),
+      &CUs));
+  CheckHsa(Api.hsa_agent_get_info(
+      Agent, static_cast<hsa_agent_info_t>(HSA_AMD_AGENT_INFO_MAX_WAVES_PER_CU),
+      &WavesPerCU));
+  *Waves = CUs * WavesPerCU;
+}
+
+void Hsa::WaitDoorbell() {
+  Api.hsa_signal_wait_scacquire(Doorbell, HSA_SIGNAL_CONDITION_NE, 0,
+                                UINT64_MAX, HSA_WAIT_STATE_BLOCKED);
+}
+
+void Hsa::KickDoorbell() { Api.hsa_signal_store_screlease(Doorbell, 1); }
+
+Hsa &GetHsa() {
+  static Hsa H;
+  return H;
+}
+
+} // namespace __ubsan

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.h b/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.h
new file mode 100644
index 0000000000000..5db46bbc9e1d6
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa.h
@@ -0,0 +1,96 @@
+//===-- ubsan_offload_hsa.h -------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_OFFLOAD_HSA_H
+#define UBSAN_OFFLOAD_HSA_H
+
+#include "hsa.h"
+#include "sanitizer_common/sanitizer_atomic.h"
+#include "sanitizer_common/sanitizer_common.h"
+
+#define UBSAN_HSA_LIBRARY "libhsa-runtime64"
+
+namespace __ubsan {
+
+#define UBSAN_HSA_FUNCTIONS(X)                                                 \
+  X(hsa_iterate_agents)                                                        \
+  X(hsa_agent_get_info)                                                        \
+  X(hsa_executable_get_symbol_by_name)                                         \
+  X(hsa_executable_symbol_get_info)                                            \
+  X(hsa_memory_copy)                                                           \
+  X(hsa_amd_memory_pool_allocate)                                              \
+  X(hsa_amd_memory_pool_free)                                                  \
+  X(hsa_amd_agents_allow_access)                                               \
+  X(hsa_amd_memory_pool_get_info)                                              \
+  X(hsa_amd_agent_iterate_memory_pools)                                        \
+  X(hsa_system_get_major_extension_table)                                      \
+  X(hsa_amd_signal_create)                                                     \
+  X(hsa_signal_destroy)                                                        \
+  X(hsa_signal_store_screlease)                                                \
+  X(hsa_signal_wait_scacquire)
+
+class Hsa {
+public:
+  bool Ready() const { return atomic_load(&Active, memory_order_acquire) != 0; }
+  bool Init();
+  void Shutdown();
+
+  bool AddRef();
+  bool DropRef();
+
+  InternalMmapVectorNoCtor<hsa_agent_t> Devices;
+  hsa_signal_t Doorbell;
+  u64 *DoorbellValue;
+  u64 *DoorbellMailbox;
+  u32 DoorbellEvent;
+
+  bool AllocFineGrained(uptr Bytes, void **Out);
+  void Free(void *P);
+  bool Copy(void *Dst, const void *Src, uptr N);
+  const void *HostAddr(uptr Dev);
+  bool SymbolAddr(hsa_executable_t Exec, const char *Name, hsa_agent_t Agent,
+                  u64 *Addr);
+  void RpcInfo(hsa_agent_t Agent, u32 *Lanes, u32 *Waves);
+
+  void WaitDoorbell();
+  void KickDoorbell();
+
+  void RecordExecutable(hsa_executable_t Exec);
+  void ForgetExecutable(hsa_executable_t Exec);
+
+private:
+  struct Api {
+#define UBSAN_HSA_DECLARE(Name) decltype(&::Name) Name;
+    UBSAN_HSA_FUNCTIONS(UBSAN_HSA_DECLARE)
+#undef UBSAN_HSA_DECLARE
+  } Api;
+
+  InternalMmapVectorNoCtor<hsa_agent_t> Agents;
+  InternalMmapVectorNoCtor<hsa_executable_t> Executables;
+  hsa_amd_memory_pool_t FineGrainedPool;
+  uptr Refs;
+  atomic_uint8_t Active;
+
+  LoaderApi Loader;
+
+  bool Resolve();
+  bool Discover();
+  bool BindLoader();
+  bool BindDoorbell();
+  bool ExecutableInfo(hsa_loaded_code_object_t Obj,
+                      hsa_ven_amd_loader_loaded_code_object_info_t Attr,
+                      u64 *Out);
+
+  template <typename Cb> void ForEachAgentObject(hsa_executable_t Exec, Cb F);
+};
+
+Hsa &GetHsa();
+
+} // namespace __ubsan
+
+#endif // UBSAN_OFFLOAD_HSA_H

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa_interceptors.cpp b/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa_interceptors.cpp
new file mode 100644
index 0000000000000..eca02530d9f61
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_hsa_interceptors.cpp
@@ -0,0 +1,199 @@
+//===-- ubsan_offload_hsa_interceptors.cpp ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include <dlfcn.h>
+
+#include "interception/interception.h"
+#include "sanitizer_common/sanitizer_atomic.h"
+#include "sanitizer_common/sanitizer_common.h"
+#include "sanitizer_common/sanitizer_libc.h"
+#include "sanitizer_common/sanitizer_mutex.h"
+#include "sanitizer_common/sanitizer_platform.h"
+#include "ubsan_diag.h"
+#include "ubsan_offload.h"
+#include "ubsan_offload_hsa.h"
+#include "ubsan_offload_rpc.h"
+#include "ubsan_offload_symbolize.h"
+
+#if !SANITIZER_LINUX
+#error "Offload UBSan reporting is supported on Linux only"
+#endif
+
+#if SANITIZER_GLIBC
+#pragma weak dlvsym
+#endif
+
+using namespace __sanitizer;
+using namespace __ubsan;
+
+namespace __ubsan {
+
+Mutex UbsanOffloadMutex;
+
+static StaticSpinMutex InitMutex;
+static atomic_uint8_t Initialized;
+
+void Initialize() {
+  if (LIKELY(atomic_load(&Initialized, memory_order_acquire)))
+    return;
+  SpinMutexLock L(&InitMutex);
+  if (atomic_load(&Initialized, memory_order_relaxed))
+    return;
+  SanitizerToolName = "UndefinedBehaviorSanitizer";
+  __ubsan_set_offload_symbolize(SymbolizeOffloadPc);
+  Atexit(ForgetDeviceImages);
+  AddDieCallback(ForgetDeviceImages);
+  atomic_store(&Initialized, 1, memory_order_release);
+}
+
+} // namespace __ubsan
+
+#define UBSAN_HSA_ENTER(name)                                                  \
+  Initialize();                                                                \
+  if (UNLIKELY(!REAL(name))) {                                                 \
+    INTERCEPT_FUNCTION(name);                                                  \
+    if (UNLIKELY(!REAL(name))) {                                               \
+      Report("ERROR: %s: cannot find %s in this process\n", SanitizerToolName, \
+             #name);                                                           \
+      Die();                                                                   \
+    }                                                                          \
+  }
+
+#define UBSAN_HSA_FORWARD(name, ...)                                           \
+  UBSAN_HSA_ENTER(name);                                                       \
+  if (UNLIKELY(!GetHsa().Ready()))                                             \
+    return REAL(name)(__VA_ARGS__);
+
+#define UBSAN_HSA_WRAPS(X)                                                     \
+  X(hsa_init)                                                                  \
+  X(hsa_shut_down)                                                             \
+  X(hsa_executable_freeze)                                                     \
+  X(hsa_executable_destroy)
+
+static void *WrapperFor(const char *Name) {
+#define UBSAN_HSA_WRAP(Fn)                                                     \
+  if (!internal_strcmp(Name, #Fn))                                             \
+    return reinterpret_cast<void *>(Fn);
+  UBSAN_HSA_WRAPS(UBSAN_HSA_WRAP)
+#undef UBSAN_HSA_WRAP
+  return nullptr;
+}
+
+static bool FromHsa(void *P) {
+  Dl_info Info = {};
+  if (!dladdr(P, &Info) || !Info.dli_fname)
+    return false;
+  return internal_strstr(Info.dli_fname, UBSAN_HSA_LIBRARY);
+}
+
+static void BindRealDlsym();
+
+// OpenMP and sometimes HIP access HSA through 'dlsym' so we need to intercept
+// it here if we want to reliably override its definitions.
+INTERCEPTOR(void *, dlsym, void *Handle, const char *Name) {
+  Initialize();
+  BindRealDlsym();
+
+  // This interceptor interferes with the order of 'RTLD_NEXT'. Force a tail
+  // call to bypass this process in the stack.
+  if (Handle == RTLD_NEXT) [[clang::musttail]]
+    return REAL(dlsym)(Handle, Name);
+
+  void *Sym = REAL(dlsym)(Handle, Name);
+  if (!Sym || !Name)
+    return Sym;
+
+  void *Wrapper = WrapperFor(Name);
+  if (!Wrapper || !FromHsa(Sym))
+    return Sym;
+  return Wrapper;
+}
+
+static void BindRealDlsym() {
+  if (LIKELY(REAL(dlsym)))
+    return;
+#if SANITIZER_GLIBC
+  // Need to intercept through 'dlvsym' instead on some platforms.
+  static const char *kVers[] = {"GLIBC_2.34", "GLIBC_2.17", "GLIBC_2.2.5",
+                                "GLIBC_2.0"};
+  if (dlvsym) {
+    for (const char *Ver : kVers) {
+      if (void *P = dlvsym(RTLD_NEXT, "dlsym", Ver)) {
+        REAL(dlsym) = reinterpret_cast<decltype(REAL(dlsym))>(P);
+        return;
+      }
+    }
+  }
+#endif
+  Report("ERROR: %s: cannot bind dlsym\n", SanitizerToolName);
+  Die();
+}
+
+INTERCEPTOR(hsa_status_t, hsa_init, void) {
+  UBSAN_HSA_ENTER(hsa_init);
+
+  hsa_status_t Status = REAL(hsa_init)();
+  if (Status != HSA_STATUS_SUCCESS)
+    return Status;
+
+  Lock L(&UbsanOffloadMutex);
+  if (GetHsa().AddRef())
+    GetHsa().Init();
+  return Status;
+}
+
+INTERCEPTOR(hsa_status_t, hsa_shut_down, void) {
+  UBSAN_HSA_ENTER(hsa_shut_down);
+
+  bool Last;
+  {
+    Lock L(&UbsanOffloadMutex);
+    Last = GetHsa().DropRef();
+  }
+  if (Last)
+    GetHsa().Shutdown();
+  return REAL(hsa_shut_down)();
+}
+
+INTERCEPTOR(hsa_status_t, hsa_executable_freeze, hsa_executable_t Executable,
+            const char *Options) {
+  UBSAN_HSA_FORWARD(hsa_executable_freeze, Executable, Options);
+
+  hsa_status_t Status = REAL(hsa_executable_freeze)(Executable, Options);
+  if (Status == HSA_STATUS_SUCCESS) {
+    {
+      Lock L(&UbsanOffloadMutex);
+      if (GetHsa().Ready())
+        GetHsa().RecordExecutable(Executable);
+    }
+    StartRpc(Executable);
+  }
+  return Status;
+}
+
+INTERCEPTOR(hsa_status_t, hsa_executable_destroy, hsa_executable_t Executable) {
+  UBSAN_HSA_FORWARD(hsa_executable_destroy, Executable);
+
+  FlushRpc();
+  {
+    Lock L(&UbsanOffloadMutex);
+    GetHsa().ForgetExecutable(Executable);
+  }
+  return REAL(hsa_executable_destroy)(Executable);
+}
+
+extern "C" void __ubsan_offload_init() { __ubsan::Initialize(); }
+
+#if SANITIZER_CAN_USE_PREINIT_ARRAY
+__attribute__((section(".preinit_array"), used)) static void (
+    *ubsan_offload_preinit)(void) = __ubsan_offload_init;
+#endif
+
+__attribute__((constructor(0))) static void UbsanOffloadDynInit() {
+  __ubsan_offload_init();
+}

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_report.cpp b/compiler-rt/lib/ubsan/offload/ubsan_offload_report.cpp
new file mode 100644
index 0000000000000..7aba59e1a6c9a
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_report.cpp
@@ -0,0 +1,343 @@
+//===-- ubsan_offload_report.cpp --------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Relocate device pointers in the loaded image and replay the existing
+// handlers.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ubsan_offload.h"
+
+#include "ubsan_diag.h"
+#include "ubsan_handlers_internal.h"
+#include "ubsan_offload_hsa.h"
+#include "ubsan_value.h"
+
+#include "sanitizer_common/sanitizer_common.h"
+#include "sanitizer_common/sanitizer_libc.h"
+
+using namespace __sanitizer;
+
+namespace __ubsan {
+namespace {
+
+enum : u8 {
+  KL_None = 0,
+  KL_NoData = 1 << 0,
+  KL_ExtraLoc = 1 << 1,
+  KL_FloatCast = 1 << 2,
+};
+
+struct KindLayout {
+  u16 Size;
+  u8 LocOff;
+  u8 NLoc;
+  u8 NType;
+  u8 Flags;
+};
+
+// SourceLocation is pointer-sized; CFICheckKind is a byte before it.
+// offsetof(CFICheckFailData, Loc) is invalid: Type is a reference.
+struct CFICheckFailLocPrefix {
+  CFITypeCheckKind CheckKind;
+  SourceLocation Loc;
+};
+
+constexpr u8 kCFILocOff =
+    static_cast<u8>(__builtin_offsetof(CFICheckFailLocPrefix, Loc));
+
+#define UBSAN_OFFLOAD_HANDLER(kind, name, reason, size, locoff, nloc, ntype,   \
+                              flags, ...)                                      \
+  {size, locoff, nloc, ntype, flags},
+constexpr KindLayout kLayout[] = {
+#include "ubsan_offload_checks.inc"
+};
+
+static_assert(ARRAY_SIZE(kLayout) == UBSAN_OFFLOAD_KIND_COUNT,
+              "kLayout must match ubsan_offload_checks.inc");
+static_assert(sizeof(CFICheckFailLocPrefix) <= sizeof(CFICheckFailData),
+              "CFI Loc prefix cannot exceed CFICheckFailData");
+
+// The HSA loader knows the host-side address of any device pointer contained in
+// a loaded segment. We can read them directly without copying or VRAM access.
+const void *Host(uptr Dev) { return GetHsa().HostAddr(Dev); }
+
+// The associated SourceLocation is a C-string located in the device executable.
+bool PatchLoc(void *S, uptr Off) {
+  SourceLocation Loc;
+  internal_memcpy(&Loc, static_cast<char *>(S) + Off, sizeof(Loc));
+  if (Loc.isInvalid())
+    return true;
+  const void *Filename = Host(reinterpret_cast<uptr>(Loc.getFilename()));
+  if (!Filename)
+    return false;
+  SourceLocation R(static_cast<const char *>(Filename), Loc.getLine(),
+                   Loc.getColumn());
+  internal_memcpy(static_cast<char *>(S) + Off, &R, sizeof(R));
+  return true;
+}
+
+// TypeDescriptor lives in the device image.
+bool PatchType(void *S, uptr Off) {
+  uptr P = 0;
+  internal_memcpy(&P, static_cast<char *>(S) + Off, sizeof(P));
+  const void *H = Host(P);
+  if (!H)
+    return false;
+  P = reinterpret_cast<uptr>(H);
+  internal_memcpy(static_cast<char *>(S) + Off, &P, sizeof(P));
+  return true;
+}
+
+// Report data contains type and source location information, try to extract it.
+bool Relocate(void *S, uptr LocOff, unsigned NLoc, unsigned NType) {
+  for (unsigned I = 0; I < NLoc; ++I)
+    if (!PatchLoc(S, LocOff + I * sizeof(SourceLocation)))
+      return false;
+  for (unsigned I = 0; I < NType; ++I) {
+    uptr Off = LocOff + NLoc * sizeof(SourceLocation) + I * sizeof(uptr);
+    if (!PatchType(S, Off))
+      return false;
+  }
+  return true;
+}
+
+// Values wider than a register are passed by pointer into device memory.
+bool ByPointer(const TypeDescriptor *T) {
+  if (!T)
+    return false;
+  if (T->isIntegerTy())
+    return T->getIntegerBitWidth() > sizeof(ValueHandle) * 8;
+  if (T->isFloatTy())
+    return T->getFloatBitWidth() > sizeof(ValueHandle) * 8;
+  return false;
+}
+
+const TypeDescriptor *TypeAt(void *S, uptr LocOff, unsigned NLoc,
+                             unsigned TypeIdx) {
+  uptr Off = LocOff + NLoc * sizeof(SourceLocation) + TypeIdx * sizeof(uptr);
+  uptr P = 0;
+  internal_memcpy(&P, static_cast<char *>(S) + Off, sizeof(P));
+  return reinterpret_cast<const TypeDescriptor *>(P);
+}
+
+// TODO: Copy wide values into the report packet instead of dropping the report.
+bool InlineValues(unsigned Kind, void *S, uptr LocOff, unsigned NLoc) {
+  auto Ok = [&](unsigned TypeIdx) {
+    return !ByPointer(TypeAt(S, LocOff, NLoc, TypeIdx));
+  };
+  switch (Kind) {
+  case UBSAN_OFFLOAD_add_overflow:
+  case UBSAN_OFFLOAD_sub_overflow:
+  case UBSAN_OFFLOAD_mul_overflow:
+  case UBSAN_OFFLOAD_divrem_overflow:
+  case UBSAN_OFFLOAD_negate_overflow:
+  case UBSAN_OFFLOAD_vla_bound_not_positive:
+  case UBSAN_OFFLOAD_load_invalid_value:
+  case UBSAN_OFFLOAD_float_cast_overflow:
+    return Ok(0);
+  case UBSAN_OFFLOAD_shift_out_of_bounds:
+  case UBSAN_OFFLOAD_implicit_conversion:
+    return Ok(0) && Ok(1);
+  case UBSAN_OFFLOAD_out_of_bounds:
+    return Ok(1);
+  default:
+    return true;
+  }
+}
+
+// Try to determine if this is a float V1 format emitted by the instrumentation.
+bool LooksLikeFloatV1(void *S, bool *Ok) {
+  *Ok = true;
+  uptr P = 0;
+  internal_memcpy(&P, S, sizeof(P));
+  if (!P)
+    return false;
+  const u8 *B = static_cast<const u8 *>(Host(P));
+  if (!B) {
+    *Ok = false;
+    return false;
+  }
+  return looksLikeFloatCastOverflowDataV1Bytes(B);
+}
+
+// Gathers the data associated with the device report packet to recreate the
+// original report so it can be serviced by the host UBSan runtime. Uses the
+// pointers in-place so the deduplication through acquire() is re-used.
+bool Materialize(const __ubsan_offload_report &R, void **Data, ValueHandle *V0,
+                 ValueHandle *V1, ValueHandle *V2) {
+  *Data = nullptr;
+  *V0 = static_cast<ValueHandle>(R.val0);
+  *V1 = static_cast<ValueHandle>(R.val1);
+  *V2 = static_cast<ValueHandle>(R.val2);
+  if (R.kind >= UBSAN_OFFLOAD_KIND_COUNT)
+    return false;
+
+  const KindLayout &L = kLayout[R.kind];
+  if (L.Flags & KL_NoData)
+    return true;
+
+  void *Live = const_cast<void *>(Host(static_cast<uptr>(R.data)));
+  if (!Live)
+    return false;
+  *Data = Live;
+
+  // Attempt to decode the arguments, failure skips the report.
+  // TODO: Need to support by-pointer arguments for f128 / i128 arguments.
+  unsigned NLoc = L.NLoc;
+  unsigned NType = L.NType;
+  if (L.Flags & KL_FloatCast) {
+    bool Ok = false;
+    NLoc = LooksLikeFloatV1(Live, &Ok) ? 0 : 1;
+    if (!Ok)
+      return false;
+  }
+  if (!Relocate(Live, L.LocOff, NLoc, NType))
+    return false;
+  if (!InlineValues(R.kind, Live, L.LocOff, NLoc))
+    return false;
+
+  if (L.Flags & KL_ExtraLoc) {
+    void *Extra = const_cast<void *>(Host(static_cast<uptr>(R.val0)));
+    if (!Extra || !PatchLoc(Extra, 0))
+      return false;
+    *V0 = reinterpret_cast<ValueHandle>(Extra);
+  }
+  return true;
+}
+
+// Forward the newly manifested host-side report to the appropriate internal
+// handler function.
+void Replay(unsigned Kind, void *Data, ValueHandle V0, ValueHandle V1,
+            ValueHandle V2, ReportOptions Opts) {
+  switch (Kind) {
+  case UBSAN_OFFLOAD_type_mismatch:
+    handleTypeMismatchImpl(reinterpret_cast<TypeMismatchData *>(Data), V0,
+                           Opts);
+    break;
+  case UBSAN_OFFLOAD_alignment_assumption:
+    handleAlignmentAssumptionImpl(
+        reinterpret_cast<AlignmentAssumptionData *>(Data), V0, V1, V2, Opts);
+    break;
+  case UBSAN_OFFLOAD_add_overflow:
+    handleIntegerOverflowImpl(reinterpret_cast<OverflowData *>(Data), V0, "+",
+                              V1, Opts);
+    break;
+  case UBSAN_OFFLOAD_sub_overflow:
+    handleIntegerOverflowImpl(reinterpret_cast<OverflowData *>(Data), V0, "-",
+                              V1, Opts);
+    break;
+  case UBSAN_OFFLOAD_mul_overflow:
+    handleIntegerOverflowImpl(reinterpret_cast<OverflowData *>(Data), V0, "*",
+                              V1, Opts);
+    break;
+  case UBSAN_OFFLOAD_negate_overflow:
+    handleNegateOverflowImpl(reinterpret_cast<OverflowData *>(Data), V0, Opts);
+    break;
+  case UBSAN_OFFLOAD_divrem_overflow:
+    handleDivremOverflowImpl(reinterpret_cast<OverflowData *>(Data), V0, V1,
+                             Opts);
+    break;
+  case UBSAN_OFFLOAD_shift_out_of_bounds:
+    handleShiftOutOfBoundsImpl(reinterpret_cast<ShiftOutOfBoundsData *>(Data),
+                               V0, V1, Opts);
+    break;
+  case UBSAN_OFFLOAD_out_of_bounds:
+    handleOutOfBoundsImpl(reinterpret_cast<OutOfBoundsData *>(Data), V0, Opts);
+    break;
+  case UBSAN_OFFLOAD_local_out_of_bounds:
+    handleLocalOutOfBoundsImpl(Opts);
+    break;
+  case UBSAN_OFFLOAD_vla_bound_not_positive:
+    handleVLABoundNotPositive(reinterpret_cast<VLABoundData *>(Data), V0, Opts);
+    break;
+  case UBSAN_OFFLOAD_float_cast_overflow:
+    handleFloatCastOverflow(Data, V0, Opts);
+    break;
+  case UBSAN_OFFLOAD_load_invalid_value:
+    handleLoadInvalidValue(reinterpret_cast<InvalidValueData *>(Data), V0,
+                           Opts);
+    break;
+  case UBSAN_OFFLOAD_implicit_conversion:
+    handleImplicitConversion(reinterpret_cast<ImplicitConversionData *>(Data),
+                             Opts, V0, V1);
+    break;
+  case UBSAN_OFFLOAD_invalid_builtin:
+    handleInvalidBuiltin(reinterpret_cast<InvalidBuiltinData *>(Data), Opts);
+    break;
+  case UBSAN_OFFLOAD_invalid_objc_cast:
+    handleInvalidObjCCast(reinterpret_cast<InvalidObjCCast *>(Data), V0, Opts);
+    break;
+  case UBSAN_OFFLOAD_nonnull_arg:
+    handleNonNullArg(reinterpret_cast<NonNullArgData *>(Data), Opts, true);
+    break;
+  case UBSAN_OFFLOAD_nullability_arg:
+    handleNonNullArg(reinterpret_cast<NonNullArgData *>(Data), Opts, false);
+    break;
+  case UBSAN_OFFLOAD_nonnull_return:
+    handleNonNullReturn(reinterpret_cast<NonNullReturnData *>(Data),
+                        reinterpret_cast<SourceLocation *>(V0), Opts, true);
+    break;
+  case UBSAN_OFFLOAD_nullability_return:
+    handleNonNullReturn(reinterpret_cast<NonNullReturnData *>(Data),
+                        reinterpret_cast<SourceLocation *>(V0), Opts, false);
+    break;
+  case UBSAN_OFFLOAD_pointer_overflow:
+    handlePointerOverflowImpl(reinterpret_cast<PointerOverflowData *>(Data), V0,
+                              V1, Opts);
+    break;
+  case UBSAN_OFFLOAD_function_type_mismatch:
+    handleFunctionTypeMismatch(
+        reinterpret_cast<FunctionTypeMismatchData *>(Data), V0, Opts);
+    break;
+  case UBSAN_OFFLOAD_cfi_check_fail: {
+    auto *D = reinterpret_cast<CFICheckFailData *>(Data);
+    // Skip virtual CFI checks that need to walk a non-existent vtable.
+    if (D->CheckKind == CFITCK_ICall || D->CheckKind == CFITCK_NVMFCall)
+      handleCFIBadIcall(D, V0, Opts);
+    break;
+  }
+  case UBSAN_OFFLOAD_builtin_unreachable:
+    handleBuiltinUnreachableImpl(reinterpret_cast<UnreachableData *>(Data),
+                                 Opts);
+    break;
+  case UBSAN_OFFLOAD_missing_return:
+    handleMissingReturnImpl(reinterpret_cast<UnreachableData *>(Data), Opts);
+    break;
+  }
+}
+
+} // namespace
+
+void PrintOffloadReport(const __ubsan_offload_report &R) {
+  if (R.kind >= UBSAN_OFFLOAD_KIND_COUNT)
+    return;
+
+  void *Data = nullptr;
+  ValueHandle V0 = 0, V1 = 0, V2 = 0;
+  {
+    Lock L(&UbsanOffloadMutex);
+    if (!GetHsa().Ready() || !Materialize(R, &Data, &V0, &V1, &V2)) {
+      VReport(1, "%s: could not translate device UBSan data 0x%zx (kind %u)\n",
+              SanitizerToolName, (uptr)R.data, (unsigned)R.kind);
+      return;
+    }
+  }
+
+  ReportOptions Opts = {};
+  Opts.FromUnrecoverableHandler = R.fatal;
+  Opts.pc = static_cast<uptr>(R.pc);
+  Opts.bp = 0;
+  Opts.FromOffload = true;
+
+  Replay(R.kind, Data, V0, V1, V2, Opts);
+  if (R.fatal)
+    Die();
+}
+
+} // namespace __ubsan

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.cpp b/compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.cpp
new file mode 100644
index 0000000000000..62df3b59130c7
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.cpp
@@ -0,0 +1,241 @@
+//===-- ubsan_offload_rpc.cpp -----------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Handling of the RPC server, the communication channel the GPU uses to send
+// sanitizer reports to be serviced on the host.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ubsan_offload_rpc.h"
+
+#include <dlfcn.h>
+#include <pthread.h>
+
+#include "sanitizer_common/sanitizer_atomic.h"
+#include "sanitizer_common/sanitizer_common.h"
+#include "sanitizer_common/sanitizer_libc.h"
+#include "sanitizer_common/sanitizer_posix.h"
+#include "shared/rpc.h"
+#include "ubsan_offload.h"
+#include "ubsan_offload_hsa.h"
+
+using namespace __sanitizer;
+
+namespace __sanitizer {
+
+int internal_pthread_create(void *Th, void *Attr, void *(*Callback)(void *),
+                            void *Param) {
+  return pthread_create(reinterpret_cast<pthread_t *>(Th),
+                        reinterpret_cast<const pthread_attr_t *>(Attr),
+                        Callback, Param);
+}
+
+int internal_pthread_join(void *Th, void **Ret) {
+  return pthread_join(reinterpret_cast<pthread_t>(Th), Ret);
+}
+
+} // namespace __sanitizer
+
+namespace __ubsan {
+namespace {
+
+struct DeviceRpc {
+  void *Buffer;
+  u32 Ports;
+  u32 Lanes;
+};
+
+Mutex RpcMutex;
+InternalMmapVectorNoCtor<DeviceRpc> Devices;
+void *ServerThread;
+bool Offload;
+atomic_uint8_t Stop;
+
+// Receives reports from the device and services them.
+uint32_t handleReport(void *PortPtr, uint32_t) {
+  auto &Port = *reinterpret_cast<rpc::Server::Port *>(PortPtr);
+  if (Port.get_opcode() != UBSAN_OFFLOAD_REPORT_OPCODE)
+    return rpc::RPC_UNHANDLED_OPCODE;
+
+  Port.recv([&](rpc::Buffer *Buffer, uint32_t) {
+    __ubsan_offload_report R;
+    internal_memcpy(&R, Buffer->data, sizeof(R));
+    PrintOffloadReport(R);
+  });
+  return rpc::RPC_SUCCESS;
+}
+
+// The OpenMP offloading runtime has its own RPC server we can use if present.
+bool tryOffload() {
+  if (Offload)
+    return true;
+  using RegisterFn = void (*)(uint32_t (*)(void *, uint32_t));
+  auto Register = reinterpret_cast<RegisterFn>(
+      dlsym(RTLD_DEFAULT, "__tgt_register_rpc_callback"));
+  if (!Register)
+    return false;
+  Register(handleReport);
+  Offload = true;
+  VReport(1, "%s: device reports through the offload runtime's server\n",
+          SanitizerToolName);
+  return true;
+}
+
+bool executableNeedsRPC(hsa_executable_t Exec, hsa_agent_t Agent, u64 *Addr) {
+  return GetHsa().SymbolAddr(Exec, "__llvm_rpc_client", Agent, Addr);
+}
+
+void drainDevice(DeviceRpc &D) {
+  if (!D.Buffer)
+    return;
+  rpc::Server Server(D.Ports, D.Buffer);
+  while (auto Port = Server.try_open(D.Lanes)) {
+    if (handleReport(&*Port, D.Lanes) == rpc::RPC_UNHANDLED_OPCODE)
+      VReport(1, "%s: unexpected opcode 0x%x on the report channel\n",
+              SanitizerToolName, Port->get_opcode());
+  }
+}
+
+void drainAll() {
+  for (uptr I = 0; I < Devices.size(); ++I)
+    drainDevice(Devices[I]);
+}
+
+void *ServerLoop(void *) {
+  Hsa &H = GetHsa();
+  for (;;) {
+    if (!atomic_load_relaxed(&Stop))
+      H.WaitDoorbell();
+    Lock L(&RpcMutex);
+    drainAll();
+    if (atomic_load_relaxed(&Stop))
+      break;
+  }
+  return nullptr;
+}
+
+void plantDoorbell(void *Buffer) {
+  Hsa &H = GetHsa();
+  auto *Bell = reinterpret_cast<rpc::Doorbell *>(
+      static_cast<u8 *>(Buffer) + rpc::Server::doorbell_offset());
+  Bell->value = reinterpret_cast<uint64_t *>(H.DoorbellValue);
+  Bell->mailbox = reinterpret_cast<uint64_t *>(H.DoorbellMailbox);
+  Bell->event_id = H.DoorbellEvent;
+}
+
+bool startThread() {
+  if (ServerThread)
+    return true;
+  if (atomic_load_relaxed(&Stop))
+    return false;
+  ServerThread = internal_start_thread(ServerLoop, nullptr);
+  return ServerThread;
+}
+
+bool initDevice(uptr Ordinal, hsa_agent_t Agent) {
+  while (Devices.size() < GetHsa().Devices.size()) {
+    DeviceRpc Empty = {};
+    Devices.push_back(Empty);
+  }
+  if (Ordinal >= Devices.size())
+    return false;
+
+  DeviceRpc &D = Devices[Ordinal];
+  if (D.Buffer)
+    return true;
+
+  GetHsa().RpcInfo(Agent, &D.Lanes, &D.Ports);
+  if (D.Ports > rpc::MAX_PORT_COUNT)
+    D.Ports = rpc::MAX_PORT_COUNT;
+
+  const uptr Bytes = rpc::Server::allocation_size(D.Lanes, D.Ports);
+  void *Buffer = nullptr;
+  if (!GetHsa().AllocFineGrained(Bytes, &Buffer) || !Buffer)
+    return false;
+  internal_memset(Buffer, 0, Bytes);
+  plantDoorbell(Buffer);
+  D.Buffer = Buffer;
+  VReport(1,
+          "%s: serving device UBSan reports on GPU %zu, %u ports, %u lanes\n",
+          SanitizerToolName, Ordinal, D.Ports, D.Lanes);
+  return true;
+}
+
+} // namespace
+
+void FlushRpc() {
+  Lock L(&RpcMutex);
+  if (Offload)
+    return;
+  drainAll();
+}
+
+// Creates a dedicated user thread to run the RPC server if needed by the
+// executable. Each device maintains a separate buffer.
+void StartRpc(hsa_executable_t Exec) {
+  Lock Rpc(&RpcMutex);
+  if (!GetHsa().Ready() || atomic_load_relaxed(&Stop))
+    return;
+  if (tryOffload())
+    return;
+
+  Lock Dev(&UbsanOffloadMutex);
+  Hsa &Runtime = GetHsa();
+  if (!Runtime.Ready() || atomic_load_relaxed(&Stop))
+    return;
+  for (uptr I = 0; I < Runtime.Devices.size(); ++I) {
+    u64 Addr = 0;
+    if (!executableNeedsRPC(Exec, Runtime.Devices[I], &Addr))
+      continue;
+    if (!initDevice(I, Runtime.Devices[I]) || !startThread()) {
+      Report("ERROR: %s: failed to start device UBSan RPC\n",
+             SanitizerToolName);
+      Die();
+    }
+
+    // Copies the RPC channel to the corresponding client symbol on the device.
+    DeviceRpc &D = Devices[I];
+    rpc::Client Client(D.Ports, D.Buffer);
+    if (!Runtime.Copy(reinterpret_cast<void *>(Addr), &Client,
+                      sizeof(Client))) {
+      Report("ERROR: %s: failed to install device UBSan RPC client\n",
+             SanitizerToolName);
+      Die();
+    }
+  }
+}
+
+// Shuts down the RPC server thread and clears any pending work.
+void StopRpc() {
+  void *Join = nullptr;
+  {
+    Lock L(&RpcMutex);
+    Offload = false;
+    atomic_store_relaxed(&Stop, 1);
+    if (ServerThread) {
+      if (GetHsa().Doorbell.handle)
+        GetHsa().KickDoorbell();
+      Join = ServerThread;
+      ServerThread = nullptr;
+    }
+  }
+  if (Join)
+    internal_join_thread(Join);
+
+  Lock L(&RpcMutex);
+  if (ServerThread)
+    return;
+  for (uptr I = 0; I < Devices.size(); ++I) {
+    if (Devices[I].Buffer)
+      GetHsa().Free(Devices[I].Buffer);
+  }
+  Devices.clear();
+  atomic_store_relaxed(&Stop, 0);
+}
+
+} // namespace __ubsan

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.h b/compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.h
new file mode 100644
index 0000000000000..40c791a034eb9
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_rpc.h
@@ -0,0 +1,22 @@
+//===-- ubsan_offload_rpc.h -------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_OFFLOAD_RPC_H
+#define UBSAN_OFFLOAD_RPC_H
+
+#include "hsa.h"
+
+namespace __ubsan {
+
+void StartRpc(hsa_executable_t Exec);
+void FlushRpc();
+void StopRpc();
+
+} // namespace __ubsan
+
+#endif // UBSAN_OFFLOAD_RPC_H

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.cpp b/compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.cpp
new file mode 100644
index 0000000000000..6807c883a959f
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.cpp
@@ -0,0 +1,148 @@
+//===-- ubsan_offload_symbolize.cpp -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ubsan_offload_symbolize.h"
+
+#include "sanitizer_common/sanitizer_common.h"
+#include "sanitizer_common/sanitizer_file.h"
+#include "sanitizer_common/sanitizer_libc.h"
+#include "sanitizer_common/sanitizer_mutex.h"
+#include "sanitizer_common/sanitizer_posix.h"
+
+using namespace __sanitizer;
+
+namespace __ubsan {
+namespace {
+
+// The symbolizer requires a file path and offset.
+struct DeviceImage {
+  uptr LoadBase;
+  uptr LoadSize;
+  void *Bytes;
+  uptr BytesSize;
+  char Path[256];
+};
+
+Mutex ImageMutex;
+InternalMmapVectorNoCtor<DeviceImage> Images;
+
+DeviceImage *ImageFor(uptr PC) {
+  for (uptr I = 0; I < Images.size(); ++I) {
+    DeviceImage &Img = Images[I];
+    if (PC >= Img.LoadBase && PC < Img.LoadBase + Img.LoadSize)
+      return &Img;
+  }
+  return nullptr;
+}
+
+void Drop(uptr I) {
+  DeviceImage &Img = Images[I];
+  if (Img.Path[0])
+    internal_unlink(Img.Path);
+  if (Img.Bytes)
+    UnmapOrDie(Img.Bytes, Img.BytesSize);
+  if (I + 1 != Images.size())
+    Images[I] = Images.back();
+  Images.pop_back();
+}
+
+// Device images are written to disk so they can be passed to 'llvm-symbolizer'.
+const char *PathFor(DeviceImage &Img) {
+  if (Img.Path[0])
+    return Img.Path;
+  if (!Img.Bytes)
+    return nullptr;
+
+  const char *Tmp = GetEnv("TMPDIR");
+  char Binary[256];
+  const char *Name = "ubsan";
+  if (ReadBinaryNameCached(Binary, sizeof(Binary)))
+    Name = StripModuleName(Binary);
+  internal_snprintf(Img.Path, sizeof(Img.Path), "%s/%s.%d.%zx.elf",
+                    Tmp ? Tmp : "/tmp", Name, (int)internal_getpid(),
+                    Img.LoadBase);
+
+  fd_t Fd = OpenFile(Img.Path, WrOnly);
+  bool Ok = Fd != kInvalidFd && WriteToFile(Fd, Img.Bytes, Img.BytesSize);
+  if (Fd != kInvalidFd)
+    CloseFile(Fd);
+  if (!Ok) {
+    VReport(1, "%s: could not write %s; device frames will not be symbolized\n",
+            SanitizerToolName, Img.Path);
+    internal_unlink(Img.Path);
+    Img.Path[0] = '\0';
+    return nullptr;
+  }
+  return Img.Path;
+}
+
+} // namespace
+
+// Make a local copy of the device image to use for future symbolization.
+void TrackDeviceImage(uptr LoadBase, uptr LoadSize, const void *Storage,
+                      uptr StorageSize) {
+  Lock L(&ImageMutex);
+  if (ImageFor(LoadBase))
+    return;
+  DeviceImage Img = {};
+  Img.LoadBase = LoadBase;
+  Img.LoadSize = LoadSize;
+  if (Storage && StorageSize) {
+    Img.Bytes = MmapOrDie(StorageSize, "ubsan device image");
+    internal_memcpy(Img.Bytes, Storage, StorageSize);
+    Img.BytesSize = StorageSize;
+  }
+  Images.push_back(Img);
+}
+
+void ForgetDeviceImage(uptr LoadBase) {
+  Lock L(&ImageMutex);
+  for (uptr I = 0; I < Images.size(); ++I) {
+    if (Images[I].LoadBase != LoadBase)
+      continue;
+    Drop(I);
+    return;
+  }
+}
+
+void ForgetDeviceImages() {
+  Lock L(&ImageMutex);
+  while (Images.size())
+    Drop(0);
+}
+
+// The custom symbolizer function we use for the device image, returns nullptr
+// if the given program counter is not owned by any known device image.
+SymbolizedStack *SymbolizeOffloadPc(uptr PC) {
+  if (!PC)
+    return nullptr;
+
+  // Get a file path for the image containing the program counter so we can pass
+  // it to the LLVM symbolizer interface.
+  char Path[256];
+  uptr Offset = 0;
+  {
+    Lock L(&ImageMutex);
+    DeviceImage *Img = ImageFor(PC);
+    if (!Img)
+      return nullptr;
+    const char *P = PathFor(*Img);
+    if (!P)
+      return SymbolizedStack::New(PC);
+    internal_strlcpy(Path, P, sizeof(Path));
+    Offset = PC - Img->LoadBase;
+  }
+
+  SymbolizedStack *Frames = Symbolizer::GetOrInit()->SymbolizeModuleOffset(
+      Path, Offset ? Offset - 1 : Offset);
+  for (SymbolizedStack *F = Frames; F; F = F->next)
+    F->info.address = PC;
+  return Frames;
+}
+
+} // namespace __ubsan

diff  --git a/compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.h b/compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.h
new file mode 100644
index 0000000000000..ceee8dd511d0d
--- /dev/null
+++ b/compiler-rt/lib/ubsan/offload/ubsan_offload_symbolize.h
@@ -0,0 +1,26 @@
+//===-- ubsan_offload_symbolize.h -------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_OFFLOAD_SYMBOLIZE_H
+#define UBSAN_OFFLOAD_SYMBOLIZE_H
+
+#include "sanitizer_common/sanitizer_internal_defs.h"
+#include "sanitizer_common/sanitizer_symbolizer.h"
+
+namespace __ubsan {
+
+void TrackDeviceImage(__sanitizer::uptr LoadBase, __sanitizer::uptr LoadSize,
+                      const void *Storage, __sanitizer::uptr StorageSize);
+void ForgetDeviceImage(__sanitizer::uptr LoadBase);
+void ForgetDeviceImages();
+
+__sanitizer::SymbolizedStack *SymbolizeOffloadPc(__sanitizer::uptr PC);
+
+} // namespace __ubsan
+
+#endif // UBSAN_OFFLOAD_SYMBOLIZE_H

diff  --git a/compiler-rt/lib/ubsan/ubsan_diag.cpp b/compiler-rt/lib/ubsan/ubsan_diag.cpp
index d06af776b54e1..6d30a602ccfe4 100644
--- a/compiler-rt/lib/ubsan/ubsan_diag.cpp
+++ b/compiler-rt/lib/ubsan/ubsan_diag.cpp
@@ -17,6 +17,7 @@
 #include "ubsan_init.h"
 #include "ubsan_monitor.h"
 
+#include "sanitizer_common/sanitizer_common.h"
 #include "sanitizer_common/sanitizer_internal_defs.h"
 #include "sanitizer_common/sanitizer_placement_new.h"
 #include "sanitizer_common/sanitizer_report_decorator.h"
@@ -49,15 +50,26 @@ void ubsan_GetStackTrace(BufferedStackTrace *stack, uptr max_depth, uptr pc,
   stack->Unwind(max_depth, pc, bp, context, top, bottom, fast);
 }
 
-static void MaybePrintStackTrace(uptr pc, uptr bp) {
+static void PrintSymbolizedFrames(SymbolizedStack *Frames);
+
+static void MaybePrintStackTrace(const ReportOptions &Opts) {
   // We assume that flags are already parsed, as UBSan runtime
   // will definitely be called when we print the first diagnostics message.
   if (!flags()->print_stacktrace)
     return;
 
+  // Reports to be symbolized from the device need to use a separate file.
+  if (Opts.FromOffload) {
+    if (!Opts.pc)
+      return;
+    SymbolizedStackHolder Frame(getReportLocation(Opts.pc, true));
+    PrintSymbolizedFrames(const_cast<SymbolizedStack *>(Frame.get()));
+    return;
+  }
+
   UNINITIALIZED BufferedStackTrace stack;
-  ubsan_GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr,
-                common_flags()->fast_unwind_on_fatal);
+  ubsan_GetStackTrace(&stack, kStackTraceMax, Opts.pc, Opts.bp, nullptr,
+                      common_flags()->fast_unwind_on_fatal);
   stack.Print();
 }
 
@@ -111,15 +123,26 @@ static void MaybeReportErrorSummary(Location Loc, ErrorType Type) {
 
 namespace {
 class Decorator : public SanitizerCommonDecorator {
- public:
+public:
   Decorator() : SanitizerCommonDecorator() {}
   const char *Highlight() const { return Green(); }
   const char *Note() const { return Black(); }
 };
+} // namespace
+
+// Symbolization hook for the remote device support. The hook returns a null
+// pointer if the given PC was not present in any of the known device images.
+static SymbolizedStack *(*OffloadSymbolize)(uptr PC);
+extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
+__ubsan_set_offload_symbolize(SymbolizedStack *(*Fn)(uptr PC)) {
+  OffloadSymbolize = Fn;
 }
 
 SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
   InitAsStandaloneIfNecessary();
+  if (OffloadSymbolize)
+    if (SymbolizedStack *S = OffloadSymbolize(PC))
+      return S;
   return Symbolizer::GetOrInit()->SymbolizePC(PC);
 }
 
@@ -294,7 +317,7 @@ static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
   // Emit data.
   InternalScopedString Buffer;
   for (uptr P = Min; P != Max; ++P) {
-    unsigned char C = *reinterpret_cast<const unsigned char*>(P);
+    unsigned char C = *reinterpret_cast<const unsigned char *>(P);
     Buffer.AppendF("%s%02x", (P % 8 == 0) ? "  " : " ", C);
   }
   Buffer.AppendF("\n");
@@ -393,6 +416,22 @@ Diag::~Diag() {
     PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);
 }
 
+static void PrintSymbolizedFrames(SymbolizedStack *Frames) {
+  InternalScopedString Out;
+  uptr N = 0;
+  for (SymbolizedStack *F = Frames; F; F = F->next) {
+    uptr Was = Out.length();
+    StackTracePrinter::GetOrInit()->RenderFrame(
+        &Out, common_flags()->stack_trace_format, N++, F->info.address,
+        &F->info, common_flags()->symbolize_vs_style,
+        common_flags()->strip_path_prefix);
+    if (Out.length() != Was)
+      Out.Append("\n");
+  }
+  Out.Append("\n");
+  Printf("%s", Out.data());
+}
+
 ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }
 
 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
@@ -400,7 +439,7 @@ ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
     : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}
 
 ScopedReport::~ScopedReport() {
-  MaybePrintStackTrace(Opts.pc, Opts.bp);
+  MaybePrintStackTrace(Opts);
   MaybeReportErrorSummary(SummaryLoc, Type);
 
   if (common_flags()->print_module_map >= 2)
@@ -465,4 +504,4 @@ bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {
          suppression_ctx->Match(AI.file, SuppType, &s);
 }
 
-#endif  // CAN_SANITIZE_UB
+#endif // CAN_SANITIZE_UB

diff  --git a/compiler-rt/lib/ubsan/ubsan_diag.h b/compiler-rt/lib/ubsan/ubsan_diag.h
index d37bc309fdd0a..2982945cd5294 100644
--- a/compiler-rt/lib/ubsan/ubsan_diag.h
+++ b/compiler-rt/lib/ubsan/ubsan_diag.h
@@ -26,6 +26,12 @@ inline SymbolizedStack *getCallerLocation(uptr CallerPC) {
   return getSymbolizedLocation(PC);
 }
 
+inline SymbolizedStack *getReportLocation(uptr PC, bool FromOffload) {
+  if (FromOffload)
+    return getSymbolizedLocation(PC);
+  return getCallerLocation(PC);
+}
+
 /// A location of some data within the program's address space.
 typedef uptr MemoryLocation;
 
@@ -207,13 +213,22 @@ struct ReportOptions {
   /// pc/bp are used to unwind the stack trace.
   uptr pc;
   uptr bp;
+  /// Device only replay options.
+  bool FromOffload;
 };
 
 bool ignoreReport(SourceLocation SLoc, ReportOptions Opts, ErrorType ET);
 
-#define GET_REPORT_OPTIONS(unrecoverable_handler) \
-    GET_CALLER_PC_BP; \
-    ReportOptions Opts = {unrecoverable_handler, pc, bp}
+#define GET_REPORT_OPTIONS(unrecoverable_handler)                              \
+  GET_CALLER_PC_BP;                                                            \
+  ReportOptions Opts = {};                                                     \
+  Opts.FromUnrecoverableHandler = unrecoverable_handler;                       \
+  Opts.pc = pc;                                                                \
+  Opts.bp = bp
+
+/// Optional hook from the offload interceptor to symbolize a device PC.
+extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
+__ubsan_set_offload_symbolize(SymbolizedStack *(*Fn)(uptr PC));
 
 /// \brief Instantiate this class before printing diagnostics in the error
 /// report. This class ensures that reports from 
diff erent threads and from

diff  --git a/compiler-rt/lib/ubsan/ubsan_handlers.cpp b/compiler-rt/lib/ubsan/ubsan_handlers.cpp
index af207ee6ccccf..cbb02892984e4 100644
--- a/compiler-rt/lib/ubsan/ubsan_handlers.cpp
+++ b/compiler-rt/lib/ubsan/ubsan_handlers.cpp
@@ -19,6 +19,7 @@
 #include "ubsan_value.h"
 
 #include "sanitizer_common/sanitizer_common.h"
+#include "ubsan_handlers_internal.h"
 
 using namespace __sanitizer;
 using namespace __ubsan;
@@ -34,6 +35,8 @@ bool ignoreReport(SourceLocation SLoc, ReportOptions Opts, ErrorType ET) {
   // thread could have acquired it, but not yet printed the report.
   if (Opts.FromUnrecoverableHandler)
     return false;
+  if (Opts.FromOffload)
+    return SLoc.isDisabled();
   return SLoc.isDisabled() || IsPCSuppressed(ET, Opts.pc, SLoc.getFilename());
 }
 
@@ -83,8 +86,8 @@ extern const char *const TypeCheckKinds[] = {
     "dynamic operation on"};
 }
 
-static void handleTypeMismatchImpl(TypeMismatchData *Data, ValueHandle Pointer,
-                                   ReportOptions Opts) {
+void __ubsan::handleTypeMismatchImpl(TypeMismatchData *Data,
+                                     ValueHandle Pointer, ReportOptions Opts) {
   Location Loc = Data->Loc.acquire();
 
   uptr Alignment = (uptr)1 << Data->LogAlignment;
@@ -105,7 +108,7 @@ static void handleTypeMismatchImpl(TypeMismatchData *Data, ValueHandle Pointer,
 
   SymbolizedStackHolder FallbackLoc;
   if (Data->Loc.isInvalid()) {
-    FallbackLoc.reset(getCallerLocation(Opts.pc));
+    FallbackLoc.reset(getReportLocation(Opts.pc, Opts.FromOffload));
     Loc = FallbackLoc;
   }
 
@@ -132,7 +135,8 @@ static void handleTypeMismatchImpl(TypeMismatchData *Data, ValueHandle Pointer,
     UNREACHABLE("unexpected error type!");
   }
 
-  if (Pointer)
+  // Device pointers are not always host-accessible.
+  if (Pointer && !Opts.FromOffload)
     Diag(Pointer, DL_Note, ET, "pointer points here");
 }
 
@@ -148,11 +152,11 @@ void __ubsan::__ubsan_handle_type_mismatch_v1_abort(TypeMismatchData *Data,
   Die();
 }
 
-static void handleAlignmentAssumptionImpl(AlignmentAssumptionData *Data,
-                                          ValueHandle Pointer,
-                                          ValueHandle Alignment,
-                                          ValueHandle Offset,
-                                          ReportOptions Opts) {
+void __ubsan::handleAlignmentAssumptionImpl(AlignmentAssumptionData *Data,
+                                            ValueHandle Pointer,
+                                            ValueHandle Alignment,
+                                            ValueHandle Offset,
+                                            ReportOptions Opts) {
   Location Loc = Data->Loc.acquire();
   SourceLocation AssumptionLoc = Data->AssumptionLoc.acquire();
 
@@ -184,7 +188,7 @@ static void handleAlignmentAssumptionImpl(AlignmentAssumptionData *Data,
   if (!AssumptionLoc.isInvalid())
     Diag(AssumptionLoc, DL_Note, ET, "alignment assumption was specified here");
 
-  Diag(RealPointer, DL_Note, ET,
+  Diag(Opts.FromOffload ? Loc : Location(RealPointer), DL_Note, ET,
        "%0address is %1 aligned, misalignment offset is %2 bytes")
       << (Offset ? "offset " : "") << ActualAlignment << MisAlignmentOffset;
 }
@@ -204,11 +208,9 @@ void __ubsan::__ubsan_handle_alignment_assumption_abort(
   Die();
 }
 
-/// \brief Common diagnostic emission for various forms of integer overflow.
-template <typename T>
-static void handleIntegerOverflowImpl(OverflowData *Data, ValueHandle LHS,
-                                      const char *Operator, T RHS,
-                                      ReportOptions Opts) {
+void __ubsan::handleIntegerOverflowImpl(OverflowData *Data, ValueHandle LHS,
+                                        const char *Operator, ValueHandle RHS,
+                                        ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   bool IsSigned = Data->Type.isSignedIntegerTy();
   ErrorType ET = IsSigned ? ErrorType::SignedIntegerOverflow
@@ -224,17 +226,18 @@ static void handleIntegerOverflowImpl(OverflowData *Data, ValueHandle LHS,
 
   ScopedReport R(Opts, Loc, ET);
 
-  Diag(Loc, DL_Error, ET, "%0 integer overflow: "
-                          "%1 %2 %3 cannot be represented in type %4")
+  Diag(Loc, DL_Error, ET,
+       "%0 integer overflow: "
+       "%1 %2 %3 cannot be represented in type %4")
       << (IsSigned ? "signed" : "unsigned") << Value(Data->Type, LHS)
-      << Operator << RHS << Data->Type;
+      << Operator << Value(Data->Type, RHS) << Data->Type;
 }
 
 #define UBSAN_OVERFLOW_HANDLER(handler_name, op, unrecoverable)                \
   void __ubsan::handler_name(OverflowData *Data, ValueHandle LHS,              \
                              ValueHandle RHS) {                                \
     GET_REPORT_OPTIONS(unrecoverable);                                         \
-    handleIntegerOverflowImpl(Data, LHS, op, Value(Data->Type, RHS), Opts);    \
+    handleIntegerOverflowImpl(Data, LHS, op, RHS, Opts);                       \
     if (unrecoverable)                                                         \
       Die();                                                                   \
   }
@@ -246,8 +249,8 @@ UBSAN_OVERFLOW_HANDLER(__ubsan_handle_sub_overflow_abort, "-", true)
 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_mul_overflow, "*", false)
 UBSAN_OVERFLOW_HANDLER(__ubsan_handle_mul_overflow_abort, "*", true)
 
-static void handleNegateOverflowImpl(OverflowData *Data, ValueHandle OldVal,
-                                     ReportOptions Opts) {
+void __ubsan::handleNegateOverflowImpl(OverflowData *Data, ValueHandle OldVal,
+                                       ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   bool IsSigned = Data->Type.isSignedIntegerTy();
   ErrorType ET = IsSigned ? ErrorType::SignedIntegerOverflow
@@ -283,8 +286,8 @@ void __ubsan::__ubsan_handle_negate_overflow_abort(OverflowData *Data,
   Die();
 }
 
-static void handleDivremOverflowImpl(OverflowData *Data, ValueHandle LHS,
-                                     ValueHandle RHS, ReportOptions Opts) {
+void __ubsan::handleDivremOverflowImpl(OverflowData *Data, ValueHandle LHS,
+                                       ValueHandle RHS, ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   Value LHSVal(Data->Type, LHS);
   Value RHSVal(Data->Type, RHS);
@@ -327,9 +330,9 @@ void __ubsan::__ubsan_handle_divrem_overflow_abort(OverflowData *Data,
   Die();
 }
 
-static void handleShiftOutOfBoundsImpl(ShiftOutOfBoundsData *Data,
-                                       ValueHandle LHS, ValueHandle RHS,
-                                       ReportOptions Opts) {
+void __ubsan::handleShiftOutOfBoundsImpl(ShiftOutOfBoundsData *Data,
+                                         ValueHandle LHS, ValueHandle RHS,
+                                         ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   Value LHSVal(Data->LHSType, LHS);
   Value RHSVal(Data->RHSType, RHS);
@@ -378,8 +381,8 @@ void __ubsan::__ubsan_handle_shift_out_of_bounds_abort(
   Die();
 }
 
-static void handleOutOfBoundsImpl(OutOfBoundsData *Data, ValueHandle Index,
-                                  ReportOptions Opts) {
+void __ubsan::handleOutOfBoundsImpl(OutOfBoundsData *Data, ValueHandle Index,
+                                    ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   ErrorType ET = ErrorType::OutOfBoundsIndex;
 
@@ -405,10 +408,10 @@ void __ubsan::__ubsan_handle_out_of_bounds_abort(OutOfBoundsData *Data,
   Die();
 }
 
-static void handleLocalOutOfBoundsImpl(ReportOptions Opts) {
+void __ubsan::handleLocalOutOfBoundsImpl(ReportOptions Opts) {
   // FIXME: Pass more diagnostic info.
   SymbolizedStackHolder CallerLoc;
-  CallerLoc.reset(getCallerLocation(Opts.pc));
+  CallerLoc.reset(getReportLocation(Opts.pc, Opts.FromOffload));
   Location Loc;
   Loc = CallerLoc;
   ErrorType ET = ErrorType::LocalOutOfBounds;
@@ -427,8 +430,8 @@ void __ubsan::__ubsan_handle_local_out_of_bounds_abort() {
   Die();
 }
 
-static void handleBuiltinUnreachableImpl(UnreachableData *Data,
-                                         ReportOptions Opts) {
+void __ubsan::handleBuiltinUnreachableImpl(UnreachableData *Data,
+                                           ReportOptions Opts) {
   ErrorType ET = ErrorType::UnreachableCall;
   ScopedReport R(Opts, Data->Loc, ET);
   Diag(Data->Loc, DL_Error, ET,
@@ -441,7 +444,8 @@ void __ubsan::__ubsan_handle_builtin_unreachable(UnreachableData *Data) {
   Die();
 }
 
-static void handleMissingReturnImpl(UnreachableData *Data, ReportOptions Opts) {
+void __ubsan::handleMissingReturnImpl(UnreachableData *Data,
+                                      ReportOptions Opts) {
   ErrorType ET = ErrorType::MissingReturn;
   ScopedReport R(Opts, Data->Loc, ET);
   Diag(Data->Loc, DL_Error, ET,
@@ -455,8 +459,8 @@ void __ubsan::__ubsan_handle_missing_return(UnreachableData *Data) {
   Die();
 }
 
-static void handleVLABoundNotPositive(VLABoundData *Data, ValueHandle Bound,
-                                      ReportOptions Opts) {
+void __ubsan::handleVLABoundNotPositive(VLABoundData *Data, ValueHandle Bound,
+                                        ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   ErrorType ET = ErrorType::NonPositiveVLAIndex;
 
@@ -494,14 +498,11 @@ static bool looksLikeFloatCastOverflowDataV1(void *Data) {
   // adding both bytes will be 0 or 1 (for BE or LE). If it were a filename,
   // adding two printable characters will not yield such a value. Otherwise,
   // if one of them is 0xff, this is most likely TK_Unknown type descriptor.
-  u16 MaybeFromTypeKind =
-      FilenameOrTypeDescriptor[0] + FilenameOrTypeDescriptor[1];
-  return MaybeFromTypeKind < 2 || FilenameOrTypeDescriptor[0] == 0xff ||
-         FilenameOrTypeDescriptor[1] == 0xff;
+  return looksLikeFloatCastOverflowDataV1Bytes(FilenameOrTypeDescriptor);
 }
 
-static void handleFloatCastOverflow(void *DataPtr, ValueHandle From,
-                                    ReportOptions Opts) {
+void __ubsan::handleFloatCastOverflow(void *DataPtr, ValueHandle From,
+                                      ReportOptions Opts) {
   SymbolizedStackHolder CallerLoc;
   Location Loc;
   const TypeDescriptor *FromType, *ToType;
@@ -509,7 +510,7 @@ static void handleFloatCastOverflow(void *DataPtr, ValueHandle From,
 
   if (looksLikeFloatCastOverflowDataV1(DataPtr)) {
     auto Data = reinterpret_cast<FloatCastOverflowData *>(DataPtr);
-    CallerLoc.reset(getCallerLocation(Opts.pc));
+    CallerLoc.reset(getReportLocation(Opts.pc, Opts.FromOffload));
     Loc = CallerLoc;
     FromType = &Data->FromType;
     ToType = &Data->ToType;
@@ -541,8 +542,8 @@ void __ubsan::__ubsan_handle_float_cast_overflow_abort(void *Data,
   Die();
 }
 
-static void handleLoadInvalidValue(InvalidValueData *Data, ValueHandle Val,
-                                   ReportOptions Opts) {
+void __ubsan::handleLoadInvalidValue(InvalidValueData *Data, ValueHandle Val,
+                                     ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   // This check could be more precise if we used 
diff erent handlers for
   // -fsanitize=bool and -fsanitize=enum.
@@ -573,9 +574,9 @@ void __ubsan::__ubsan_handle_load_invalid_value_abort(InvalidValueData *Data,
   Die();
 }
 
-static void handleImplicitConversion(ImplicitConversionData *Data,
-                                     ReportOptions Opts, ValueHandle Src,
-                                     ValueHandle Dst) {
+void __ubsan::handleImplicitConversion(ImplicitConversionData *Data,
+                                       ReportOptions Opts, ValueHandle Src,
+                                       ValueHandle Dst) {
   SourceLocation Loc = Data->Loc.acquire();
   const TypeDescriptor &SrcTy = Data->FromType;
   const TypeDescriptor &DstTy = Data->ToType;
@@ -646,7 +647,8 @@ void __ubsan::__ubsan_handle_implicit_conversion_abort(
   Die();
 }
 
-static void handleInvalidBuiltin(InvalidBuiltinData *Data, ReportOptions Opts) {
+void __ubsan::handleInvalidBuiltin(InvalidBuiltinData *Data,
+                                   ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   ErrorType ET = ErrorType::InvalidBuiltin;
 
@@ -673,8 +675,8 @@ void __ubsan::__ubsan_handle_invalid_builtin_abort(InvalidBuiltinData *Data) {
   Die();
 }
 
-static void handleInvalidObjCCast(InvalidObjCCast *Data, ValueHandle Pointer,
-                                  ReportOptions Opts) {
+void __ubsan::handleInvalidObjCCast(InvalidObjCCast *Data, ValueHandle Pointer,
+                                    ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   ErrorType ET = ErrorType::InvalidObjCCast;
 
@@ -703,8 +705,9 @@ void __ubsan::__ubsan_handle_invalid_objc_cast_abort(InvalidObjCCast *Data,
   Die();
 }
 
-static void handleNonNullReturn(NonNullReturnData *Data, SourceLocation *LocPtr,
-                                ReportOptions Opts, bool IsAttr) {
+void __ubsan::handleNonNullReturn(NonNullReturnData *Data,
+                                  SourceLocation *LocPtr, ReportOptions Opts,
+                                  bool IsAttr) {
   if (!LocPtr)
     UNREACHABLE("source location pointer is null!");
 
@@ -751,8 +754,8 @@ void __ubsan::__ubsan_handle_nullability_return_v1_abort(
   Die();
 }
 
-static void handleNonNullArg(NonNullArgData *Data, ReportOptions Opts,
-                             bool IsAttr) {
+void __ubsan::handleNonNullArg(NonNullArgData *Data, ReportOptions Opts,
+                               bool IsAttr) {
   SourceLocation Loc = Data->Loc.acquire();
   ErrorType ET = IsAttr ? ErrorType::InvalidNullArgument
                         : ErrorType::InvalidNullArgumentWithNullability;
@@ -793,10 +796,9 @@ void __ubsan::__ubsan_handle_nullability_arg_abort(NonNullArgData *Data) {
   Die();
 }
 
-static void handlePointerOverflowImpl(PointerOverflowData *Data,
-                                      ValueHandle Base,
-                                      ValueHandle Result,
-                                      ReportOptions Opts) {
+void __ubsan::handlePointerOverflowImpl(PointerOverflowData *Data,
+                                        ValueHandle Base, ValueHandle Result,
+                                        ReportOptions Opts) {
   SourceLocation Loc = Data->Loc.acquire();
   ErrorType ET;
 
@@ -881,8 +883,8 @@ static SymbolizedStack *removeArtificialFiles(SymbolizedStack *FS) {
   return FS;
 }
 
-static void handleCFIBadIcall(CFICheckFailData *Data, ValueHandle Function,
-                              ReportOptions Opts) {
+void __ubsan::handleCFIBadIcall(CFICheckFailData *Data, ValueHandle Function,
+                                ReportOptions Opts) {
   ErrorType ET;
   switch (Data->CheckKind) {
   case CFITCK_ICall:
@@ -982,9 +984,9 @@ void __ubsan::__ubsan_handle_cfi_check_fail_abort(CFICheckFailData *Data,
   Die();
 }
 
-static bool handleFunctionTypeMismatch(FunctionTypeMismatchData *Data,
-                                       ValueHandle Function,
-                                       ReportOptions Opts) {
+bool __ubsan::handleFunctionTypeMismatch(FunctionTypeMismatchData *Data,
+                                         ValueHandle Function,
+                                         ReportOptions Opts) {
   SourceLocation CallLoc = Data->Loc.acquire();
   ErrorType ET = ErrorType::FunctionTypeMismatch;
   if (ignoreReport(CallLoc, Opts, ET))

diff  --git a/compiler-rt/lib/ubsan/ubsan_handlers_internal.h b/compiler-rt/lib/ubsan/ubsan_handlers_internal.h
new file mode 100644
index 0000000000000..3639124d70132
--- /dev/null
+++ b/compiler-rt/lib/ubsan/ubsan_handlers_internal.h
@@ -0,0 +1,63 @@
+//===-- ubsan_handlers_internal.h -------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Internal handle*Impl entry points. Used by the public handlers and by
+// device report replay. Not a stable ABI.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_HANDLERS_INTERNAL_H
+#define UBSAN_HANDLERS_INTERNAL_H
+
+#include "ubsan_diag.h"
+#include "ubsan_handlers.h"
+
+namespace __ubsan {
+
+void handleTypeMismatchImpl(TypeMismatchData *Data, ValueHandle Pointer,
+                            ReportOptions Opts);
+void handleAlignmentAssumptionImpl(AlignmentAssumptionData *Data,
+                                   ValueHandle Pointer, ValueHandle Alignment,
+                                   ValueHandle Offset, ReportOptions Opts);
+void handleIntegerOverflowImpl(OverflowData *Data, ValueHandle LHS,
+                               const char *Operator, ValueHandle RHS,
+                               ReportOptions Opts);
+void handleNegateOverflowImpl(OverflowData *Data, ValueHandle OldVal,
+                              ReportOptions Opts);
+void handleDivremOverflowImpl(OverflowData *Data, ValueHandle LHS,
+                              ValueHandle RHS, ReportOptions Opts);
+void handleShiftOutOfBoundsImpl(ShiftOutOfBoundsData *Data, ValueHandle LHS,
+                                ValueHandle RHS, ReportOptions Opts);
+void handleOutOfBoundsImpl(OutOfBoundsData *Data, ValueHandle Index,
+                           ReportOptions Opts);
+void handleLocalOutOfBoundsImpl(ReportOptions Opts);
+void handleBuiltinUnreachableImpl(UnreachableData *Data, ReportOptions Opts);
+void handleMissingReturnImpl(UnreachableData *Data, ReportOptions Opts);
+void handleVLABoundNotPositive(VLABoundData *Data, ValueHandle Bound,
+                               ReportOptions Opts);
+void handleFloatCastOverflow(void *Data, ValueHandle From, ReportOptions Opts);
+void handleLoadInvalidValue(InvalidValueData *Data, ValueHandle Val,
+                            ReportOptions Opts);
+void handleImplicitConversion(ImplicitConversionData *Data, ReportOptions Opts,
+                              ValueHandle Src, ValueHandle Dst);
+void handleInvalidBuiltin(InvalidBuiltinData *Data, ReportOptions Opts);
+void handleInvalidObjCCast(InvalidObjCCast *Data, ValueHandle Pointer,
+                           ReportOptions Opts);
+void handleNonNullReturn(NonNullReturnData *Data, SourceLocation *LocPtr,
+                         ReportOptions Opts, bool IsAttr);
+void handleNonNullArg(NonNullArgData *Data, ReportOptions Opts, bool IsAttr);
+void handlePointerOverflowImpl(PointerOverflowData *Data, ValueHandle Base,
+                               ValueHandle Result, ReportOptions Opts);
+void handleCFIBadIcall(CFICheckFailData *Data, ValueHandle Function,
+                       ReportOptions Opts);
+bool handleFunctionTypeMismatch(FunctionTypeMismatchData *Data,
+                                ValueHandle Function, ReportOptions Opts);
+
+} // namespace __ubsan
+
+#endif // UBSAN_HANDLERS_INTERNAL_H

diff  --git a/compiler-rt/lib/ubsan/ubsan_interface.inc b/compiler-rt/lib/ubsan/ubsan_interface.inc
index 7a9cb9b336f6e..0d4a25daa7ab4 100644
--- a/compiler-rt/lib/ubsan/ubsan_interface.inc
+++ b/compiler-rt/lib/ubsan/ubsan_interface.inc
@@ -62,3 +62,4 @@ INTERFACE_WEAK_FUNCTION(__ubsan_default_options)
 INTERFACE_WEAK_FUNCTION(__ubsan_default_suppressions)
 INTERFACE_FUNCTION(__ubsan_on_report)
 INTERFACE_FUNCTION(__ubsan_get_current_report_data)
+INTERFACE_FUNCTION(__ubsan_set_offload_symbolize)

diff  --git a/compiler-rt/lib/ubsan/ubsan_offload.cpp b/compiler-rt/lib/ubsan/ubsan_offload.cpp
new file mode 100644
index 0000000000000..ca7566915b90e
--- /dev/null
+++ b/compiler-rt/lib/ubsan/ubsan_offload.cpp
@@ -0,0 +1,87 @@
+//===-- ubsan_offload.cpp ---------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ubsan_handlers.h"
+#include "ubsan_value.h"
+
+#include "ubsan_offload_packet.h"
+
+#include <gpuintrin.h>
+
+#include "shared/rpc.h"
+
+using namespace __ubsan;
+using namespace __sanitizer;
+
+[[gnu::visibility("protected"),
+  gnu::weak]] rpc::Client __ubsan_rpc_client asm("__llvm_rpc_client");
+
+// CHECK() has no host reporter on the device.
+namespace __sanitizer {
+void NORETURN CheckFailed(const char *, int, const char *, u64, u64) {
+  __builtin_verbose_trap("UndefinedBehaviorSanitizer", "internal check failed");
+}
+} // namespace __sanitizer
+
+namespace {
+
+// Shallow deduplication pool to avoid flooding the interface.
+bool seen(uptr Pc) {
+  static constexpr u64 Bits = 6;
+  static constexpr u64 Golden = 0x9E3779B97F4A7C15ull; // 2^64 / phi.
+  static uptr Table[1u << Bits] = {};
+  unsigned Index = (Pc * Golden) >> (sizeof(u64) * 8u - Bits);
+  uptr *Last = &Table[Index];
+  return __scoped_atomic_exchange_n(Last, Pc, __ATOMIC_RELAXED,
+                                    __MEMORY_SCOPE_DEVICE) == Pc;
+}
+
+// TODO: Handle __int128 arguments that are passed by-pointer instead.
+void report(uptr Pc, __ubsan_report_kind Kind, bool Fatal, const void *Data,
+            ValueHandle Val0 = 0, ValueHandle Val1 = 0, ValueHandle Val2 = 0) {
+  if (seen(Pc))
+    return;
+
+  rpc::Client::Port Port =
+      __ubsan_rpc_client.open<UBSAN_OFFLOAD_REPORT_OPCODE>();
+  Port.send([&](rpc::Buffer *Buf, uint32_t) {
+    auto &Rep = *reinterpret_cast<__ubsan_offload_report *>(Buf);
+    Rep.pc = static_cast<uint64_t>(Pc);
+    Rep.data = static_cast<uint64_t>(reinterpret_cast<uptr>(Data));
+    Rep.val0 = static_cast<uint64_t>(Val0);
+    Rep.val1 = static_cast<uint64_t>(Val1);
+    Rep.val2 = static_cast<uint64_t>(Val2);
+    Rep.kind = static_cast<uint8_t>(Kind);
+    Rep.fatal = Fatal;
+  });
+}
+
+} // namespace
+
+extern "C" {
+
+#define UBSAN_OFFLOAD_HANDLER(kind, name, reason, size, locoff, nloc, ntype,   \
+                              flags, params, ...)                              \
+  [[gnu::cold, gnu::noinline]] void __ubsan_handle_##name params {             \
+    report(GET_CALLER_PC(), UBSAN_OFFLOAD_##kind, false, __VA_ARGS__);         \
+  }                                                                            \
+  [[gnu::cold, gnu::noinline]] void __ubsan_handle_##name##_abort params {     \
+    report(GET_CALLER_PC(), UBSAN_OFFLOAD_##kind, true, __VA_ARGS__);          \
+    __builtin_verbose_trap("UndefinedBehaviorSanitizer", reason);              \
+  }
+
+#define UBSAN_OFFLOAD_HANDLER_NORETURN(kind, name, reason, size, locoff, nloc, \
+                                       ntype, flags, params, ...)              \
+  [[gnu::cold, gnu::noinline]] void __ubsan_handle_##name params {             \
+    report(GET_CALLER_PC(), UBSAN_OFFLOAD_##kind, true, __VA_ARGS__);          \
+    __builtin_verbose_trap("UndefinedBehaviorSanitizer", reason);              \
+  }
+
+#include "ubsan_offload_checks.inc"
+
+} // extern "C"

diff  --git a/compiler-rt/lib/ubsan/ubsan_offload_checks.inc b/compiler-rt/lib/ubsan/ubsan_offload_checks.inc
new file mode 100644
index 0000000000000..217dc46c9d5f4
--- /dev/null
+++ b/compiler-rt/lib/ubsan/ubsan_offload_checks.inc
@@ -0,0 +1,109 @@
+//===-- ubsan_offload_checks.inc --------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Supported UBSan check kinds on the target device. Defines the channel ABI.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_OFFLOAD_HANDLER
+#error "ubsan_offload_checks.inc requires UBSAN_OFFLOAD_HANDLER"
+#endif
+#ifndef UBSAN_OFFLOAD_HANDLER_NORETURN
+#define UBSAN_OFFLOAD_HANDLER_NORETURN UBSAN_OFFLOAD_HANDLER
+#endif
+
+UBSAN_OFFLOAD_HANDLER(type_mismatch, type_mismatch_v1, "type mismatch",
+                      sizeof(TypeMismatchData), 0, 1, 1, KL_None,
+                      (TypeMismatchData * D, ValueHandle P), D, P)
+UBSAN_OFFLOAD_HANDLER(alignment_assumption, alignment_assumption,
+                      "alignment assumption", sizeof(AlignmentAssumptionData),
+                      0, 2, 1, KL_None,
+                      (AlignmentAssumptionData * D, ValueHandle P,
+                       ValueHandle A, ValueHandle O),
+                      D, P, A, O)
+UBSAN_OFFLOAD_HANDLER(add_overflow, add_overflow, "integer overflow",
+                      sizeof(OverflowData), 0, 1, 1, KL_None,
+                      (OverflowData * D, ValueHandle L, ValueHandle R), D, L, R)
+UBSAN_OFFLOAD_HANDLER(sub_overflow, sub_overflow, "integer overflow",
+                      sizeof(OverflowData), 0, 1, 1, KL_None,
+                      (OverflowData * D, ValueHandle L, ValueHandle R), D, L, R)
+UBSAN_OFFLOAD_HANDLER(mul_overflow, mul_overflow, "integer overflow",
+                      sizeof(OverflowData), 0, 1, 1, KL_None,
+                      (OverflowData * D, ValueHandle L, ValueHandle R), D, L, R)
+UBSAN_OFFLOAD_HANDLER(negate_overflow, negate_overflow, "negation overflow",
+                      sizeof(OverflowData), 0, 1, 1, KL_None,
+                      (OverflowData * D, ValueHandle V), D, V)
+UBSAN_OFFLOAD_HANDLER(divrem_overflow, divrem_overflow, "division overflow",
+                      sizeof(OverflowData), 0, 1, 1, KL_None,
+                      (OverflowData * D, ValueHandle L, ValueHandle R), D, L, R)
+UBSAN_OFFLOAD_HANDLER(shift_out_of_bounds, shift_out_of_bounds,
+                      "shift out of bounds", sizeof(ShiftOutOfBoundsData), 0, 1,
+                      2, KL_None,
+                      (ShiftOutOfBoundsData * D, ValueHandle L, ValueHandle R),
+                      D, L, R)
+UBSAN_OFFLOAD_HANDLER(out_of_bounds, out_of_bounds, "array index out of bounds",
+                      sizeof(OutOfBoundsData), 0, 1, 2, KL_None,
+                      (OutOfBoundsData * D, ValueHandle I), D, I)
+UBSAN_OFFLOAD_HANDLER(local_out_of_bounds, local_out_of_bounds,
+                      "local array index out of bounds", 0, 0, 0, 0, KL_NoData,
+                      (void), nullptr)
+UBSAN_OFFLOAD_HANDLER(vla_bound_not_positive, vla_bound_not_positive,
+                      "non-positive VLA bound", sizeof(VLABoundData), 0, 1, 1,
+                      KL_None, (VLABoundData * D, ValueHandle B), D, B)
+UBSAN_OFFLOAD_HANDLER(float_cast_overflow, float_cast_overflow,
+                      "float cast overflow", sizeof(FloatCastOverflowDataV2), 0,
+                      1, 2, KL_FloatCast, (void *D, ValueHandle F), D, F)
+UBSAN_OFFLOAD_HANDLER(load_invalid_value, load_invalid_value,
+                      "invalid value load", sizeof(InvalidValueData), 0, 1, 1,
+                      KL_None, (InvalidValueData * D, ValueHandle V), D, V)
+UBSAN_OFFLOAD_HANDLER(
+    implicit_conversion, implicit_conversion, "implicit conversion",
+    sizeof(ImplicitConversionData), 0, 1, 2, KL_None,
+    (ImplicitConversionData * D, ValueHandle S, ValueHandle T), D, S, T)
+UBSAN_OFFLOAD_HANDLER(invalid_builtin, invalid_builtin, "invalid builtin",
+                      sizeof(InvalidBuiltinData), 0, 1, 0, KL_None,
+                      (InvalidBuiltinData * D), D)
+UBSAN_OFFLOAD_HANDLER(invalid_objc_cast, invalid_objc_cast, "invalid ObjC cast",
+                      sizeof(InvalidObjCCast), 0, 1, 1, KL_None,
+                      (InvalidObjCCast * D, ValueHandle P), D, P)
+UBSAN_OFFLOAD_HANDLER(nonnull_arg, nonnull_arg, "null argument",
+                      sizeof(NonNullArgData), 0, 2, 0, KL_None,
+                      (NonNullArgData * D), D)
+UBSAN_OFFLOAD_HANDLER(nullability_arg, nullability_arg, "null argument",
+                      sizeof(NonNullArgData), 0, 2, 0, KL_None,
+                      (NonNullArgData * D), D)
+UBSAN_OFFLOAD_HANDLER(nonnull_return, nonnull_return_v1, "null return",
+                      sizeof(NonNullReturnData), 0, 1, 0, KL_ExtraLoc,
+                      (NonNullReturnData * D, SourceLocation *L), D,
+                      reinterpret_cast<ValueHandle>(L))
+UBSAN_OFFLOAD_HANDLER(nullability_return, nullability_return_v1, "null return",
+                      sizeof(NonNullReturnData), 0, 1, 0, KL_ExtraLoc,
+                      (NonNullReturnData * D, SourceLocation *L), D,
+                      reinterpret_cast<ValueHandle>(L))
+UBSAN_OFFLOAD_HANDLER(pointer_overflow, pointer_overflow, "pointer overflow",
+                      sizeof(PointerOverflowData), 0, 1, 0, KL_None,
+                      (PointerOverflowData * D, ValueHandle B, ValueHandle R),
+                      D, B, R)
+UBSAN_OFFLOAD_HANDLER(function_type_mismatch, function_type_mismatch,
+                      "function type mismatch",
+                      sizeof(FunctionTypeMismatchData), 0, 1, 1, KL_None,
+                      (FunctionTypeMismatchData * D, ValueHandle V), D, V)
+UBSAN_OFFLOAD_HANDLER(cfi_check_fail, cfi_check_fail,
+                      "control flow integrity failure",
+                      sizeof(CFICheckFailData), kCFILocOff, 1, 1, KL_None,
+                      (CFICheckFailData * D, ValueHandle F, uptr V), D, F, V)
+UBSAN_OFFLOAD_HANDLER_NORETURN(builtin_unreachable, builtin_unreachable,
+                               "unreachable code reached",
+                               sizeof(UnreachableData), 0, 1, 0, KL_None,
+                               (UnreachableData * D), D)
+UBSAN_OFFLOAD_HANDLER_NORETURN(missing_return, missing_return, "missing return",
+                               sizeof(UnreachableData), 0, 1, 0, KL_None,
+                               (UnreachableData * D), D)
+
+#undef UBSAN_OFFLOAD_HANDLER
+#undef UBSAN_OFFLOAD_HANDLER_NORETURN

diff  --git a/compiler-rt/lib/ubsan/ubsan_offload_packet.h b/compiler-rt/lib/ubsan/ubsan_offload_packet.h
new file mode 100644
index 0000000000000..b447e6313506f
--- /dev/null
+++ b/compiler-rt/lib/ubsan/ubsan_offload_packet.h
@@ -0,0 +1,44 @@
+//===-- ubsan_offload_packet.h ----------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Offload/host RPC packet for UBSan reports.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_OFFLOAD_PACKET_H
+#define UBSAN_OFFLOAD_PACKET_H
+
+#include <stdint.h>
+
+#define UBSAN_OFFLOAD_REPORT_OPCODE (('s' << 24) | 0)
+
+enum __ubsan_report_kind : uint8_t {
+#define UBSAN_OFFLOAD_HANDLER(kind, ...) UBSAN_OFFLOAD_##kind,
+#define UBSAN_OFFLOAD_HANDLER_NORETURN(kind, ...) UBSAN_OFFLOAD_##kind,
+#include "ubsan_offload_checks.inc"
+  UBSAN_OFFLOAD_KIND_COUNT
+};
+
+// A single offload packet to initiate the report in the UBSan host runtime.
+struct __ubsan_offload_report {
+  uint64_t pc;
+  uint64_t data;
+  uint64_t val0;
+  uint8_t reserved0[8];
+  uint64_t val1;
+  uint8_t reserved1[8];
+  uint64_t val2;
+  uint8_t kind;
+  uint8_t fatal;
+  uint8_t reserved2[3];
+};
+
+static_assert(sizeof(__ubsan_offload_report) == 64,
+              "Offload UBSan report must fit one RPC packet");
+
+#endif // UBSAN_OFFLOAD_PACKET_H

diff  --git a/compiler-rt/lib/ubsan/ubsan_value.h b/compiler-rt/lib/ubsan/ubsan_value.h
index ee523cf5ddda5..688608cc4cb5d 100644
--- a/compiler-rt/lib/ubsan/ubsan_value.h
+++ b/compiler-rt/lib/ubsan/ubsan_value.h
@@ -166,6 +166,13 @@ class TypeDescriptor {
   }
 };
 
+/// First two bytes of a TypeDescriptor: TK_Integer (0), TK_Float (1), or
+/// TK_Unknown (0xff). Used to tell FloatCastOverflowData from V2.
+inline bool looksLikeFloatCastOverflowDataV1Bytes(const u8 *Desc) {
+  u16 Kind = u16(Desc[0]) + u16(Desc[1]);
+  return Kind < 2 || Desc[0] == 0xff || Desc[1] == 0xff;
+}
+
 /// \brief An opaque handle to a value.
 typedef uptr ValueHandle;
 

diff  --git a/compiler-rt/test/CMakeLists.txt b/compiler-rt/test/CMakeLists.txt
index fa2847c1b7dd0..ba4aa0804d319 100644
--- a/compiler-rt/test/CMakeLists.txt
+++ b/compiler-rt/test/CMakeLists.txt
@@ -136,7 +136,10 @@ if(COMPILER_RT_CAN_EXECUTE_TESTS)
     compiler_rt_test_runtime(interception)
 
     compiler_rt_test_runtime(lsan)
-    compiler_rt_test_runtime(ubsan)
+    # The GPU UBSan tests are handled by the host.
+    if(NOT COMPILER_RT_GPU_BUILD)
+      compiler_rt_test_runtime(ubsan)
+    endif()
     compiler_rt_test_runtime(sanitizer_common)
 
     # GNU/Hurd and OpenBSD not supporting asan, cannot run the tests

diff  --git a/compiler-rt/test/ubsan/AMDGPU/abort.hip b/compiler-rt/test/ubsan/AMDGPU/abort.hip
new file mode 100644
index 0000000000000..ef3b9b46df0c7
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/abort.hip
@@ -0,0 +1,20 @@
+// REQUIRES: ubsan-hip
+// RUN: %clang_ubsan_hip %s -o %t %hip_libs -fno-sanitize-recover=undefined
+// RUN: not %run %t 2>&1 | FileCheck %s
+
+__global__ void gone(int *Out) {
+  *Out = 1;
+  __builtin_unreachable();
+}
+
+int main() {
+  int *P = nullptr;
+  CHECK_HIP(hipMalloc((void **)&P, sizeof(int)));
+  gone<<<1, 1>>>(P);
+  hipDeviceSynchronize();
+  hipFree(P);
+  return 3;
+}
+
+// CHECK: runtime error: execution reached an unreachable program point
+// CHECK: SUMMARY: UndefinedBehaviorSanitizer:

diff  --git a/compiler-rt/test/ubsan/AMDGPU/dedup.hip b/compiler-rt/test/ubsan/AMDGPU/dedup.hip
new file mode 100644
index 0000000000000..d5381107d561a
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/dedup.hip
@@ -0,0 +1,23 @@
+// REQUIRES: ubsan-hip
+// RUN: %clang_ubsan_hip %s -o %t %hip_libs
+// RUN: %run %t 2>&1 | FileCheck %s
+
+__global__ void overflow(int *Out) {
+  int A = 0x7fffffff;
+  for (int I = 0; I < 8; ++I)
+    *Out = A + 1;
+}
+
+int main() {
+  int *P = nullptr;
+  CHECK_HIP(hipMalloc((void **)&P, sizeof(int)));
+  overflow<<<1, 1>>>(P);
+  hipDeviceSynchronize();
+  printf("survived\n");
+  hipFree(P);
+  return 0;
+}
+
+// CHECK: runtime error: signed integer overflow
+// CHECK-NOT: runtime error:
+// CHECK: survived

diff  --git a/compiler-rt/test/ubsan/AMDGPU/host-and-device.hip b/compiler-rt/test/ubsan/AMDGPU/host-and-device.hip
new file mode 100644
index 0000000000000..92ec215cb99b8
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/host-and-device.hip
@@ -0,0 +1,22 @@
+// REQUIRES: ubsan-hip
+// RUN: %clang_ubsan_hip %s -o %t %hip_libs
+// RUN: %run %t 2>&1 | FileCheck %s
+
+__global__ void gpu_shift(int *Out) {
+  int A = 1;
+  *Out = A << 32;
+}
+
+int main() {
+  int *P = nullptr;
+  CHECK_HIP(hipMalloc((void **)&P, sizeof(int)));
+  gpu_shift<<<1, 1>>>(P);
+  volatile int H = 0x7fffffff;
+  H = H + 1;
+  CHECK_HIP(hipDeviceSynchronize());
+  hipFree(P);
+  return 0;
+}
+
+// CHECK-DAG: runtime error: signed integer overflow
+// CHECK-DAG: runtime error: shift exponent

diff  --git a/compiler-rt/test/ubsan/AMDGPU/lit.local.cfg.py b/compiler-rt/test/ubsan/AMDGPU/lit.local.cfg.py
new file mode 100644
index 0000000000000..abc758ab82106
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/lit.local.cfg.py
@@ -0,0 +1,9 @@
+# These tests require a functioning GPU device and runtime on the system.
+if "ubsan-standalone" not in config.available_features or (
+    "ubsan-hip" not in config.available_features
+    and "ubsan-openmp-offload" not in config.available_features
+):
+    config.unsupported = True
+else:
+    config.parallelism_group = "gpu"
+    config.suffixes = [".c", ".cpp", ".hip"]

diff  --git a/compiler-rt/test/ubsan/AMDGPU/openmp-overflow.cpp b/compiler-rt/test/ubsan/AMDGPU/openmp-overflow.cpp
new file mode 100644
index 0000000000000..adaa3280df73a
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/openmp-overflow.cpp
@@ -0,0 +1,18 @@
+// REQUIRES: ubsan-openmp-offload
+// RUN: %clang_ubsan_omp %s -o %t
+// RUN: %run %t 2>&1 | FileCheck %s
+
+#include <omp.h>
+
+int main() {
+  int X = 0;
+#pragma omp target map(from : X)
+  {
+    int A = 0x7fffffff;
+    X = A + 1;
+  }
+  return 0;
+}
+
+// CHECK: runtime error: signed integer overflow
+// CHECK: SUMMARY: UndefinedBehaviorSanitizer:

diff  --git a/compiler-rt/test/ubsan/AMDGPU/overflow-i128.hip b/compiler-rt/test/ubsan/AMDGPU/overflow-i128.hip
new file mode 100644
index 0000000000000..dd60ac0dbd20e
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/overflow-i128.hip
@@ -0,0 +1,21 @@
+// REQUIRES: ubsan-hip
+// RUN: %clang_ubsan_hip %s -o %t %hip_libs
+// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not="runtime error"
+
+// TODO: Device __int128 operands are passed by pointer and dropped on the host.
+__global__ void overflow(__int128 *Out) {
+  __int128 A = (__int128)1 << 126;
+  *Out = A + A;
+}
+
+int main() {
+  __int128 *P = nullptr;
+  CHECK_HIP(hipMalloc((void **)&P, sizeof(__int128)));
+  overflow<<<1, 1>>>(P);
+  hipDeviceSynchronize();
+  printf("survived\n");
+  hipFree(P);
+  return 0;
+}
+
+// CHECK: survived

diff  --git a/compiler-rt/test/ubsan/AMDGPU/overflow.hip b/compiler-rt/test/ubsan/AMDGPU/overflow.hip
new file mode 100644
index 0000000000000..2c024e33b03b2
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/overflow.hip
@@ -0,0 +1,25 @@
+// REQUIRES: ubsan-hip
+// RUN: %clang_ubsan_hip %s -o %t %hip_libs
+// RUN: %run %t 2>&1 | FileCheck %s
+// RUN: %env_ubsan_opts=print_stacktrace=1 %run %t 2>&1 | FileCheck %s --check-prefix=STACK
+
+__global__ void overflow(int *Out) {
+  int A = 0x7fffffff;
+  *Out = A + 1;
+}
+
+int main() {
+  int *P = nullptr;
+  CHECK_HIP(hipMalloc((void **)&P, sizeof(int)));
+  overflow<<<1, 1>>>(P);
+  hipDeviceSynchronize();
+  hipFree(P);
+  return 0;
+}
+
+// CHECK: runtime error: signed integer overflow
+// CHECK: SUMMARY: UndefinedBehaviorSanitizer:
+
+// STACK: runtime error: signed integer overflow
+// STACK: #0 {{.*}}overflow{{.*}}overflow.hip
+// STACK: SUMMARY: UndefinedBehaviorSanitizer:

diff  --git a/compiler-rt/test/ubsan/AMDGPU/shift.hip b/compiler-rt/test/ubsan/AMDGPU/shift.hip
new file mode 100644
index 0000000000000..6346579badf35
--- /dev/null
+++ b/compiler-rt/test/ubsan/AMDGPU/shift.hip
@@ -0,0 +1,20 @@
+// REQUIRES: ubsan-hip
+// RUN: %clang_ubsan_hip %s -o %t %hip_libs
+// RUN: %run %t 2>&1 | FileCheck %s
+
+__global__ void bad_shift(int *Out) {
+  int A = 1;
+  *Out = A << 32;
+}
+
+int main() {
+  int *P = nullptr;
+  CHECK_HIP(hipMalloc((void **)&P, sizeof(int)));
+  bad_shift<<<1, 1>>>(P);
+  hipDeviceSynchronize();
+  hipFree(P);
+  return 0;
+}
+
+// CHECK: runtime error: shift exponent
+// CHECK: SUMMARY: UndefinedBehaviorSanitizer:

diff  --git a/compiler-rt/test/ubsan/CMakeLists.txt b/compiler-rt/test/ubsan/CMakeLists.txt
index a83215d82d57e..e8ee67087011c 100644
--- a/compiler-rt/test/ubsan/CMakeLists.txt
+++ b/compiler-rt/test/ubsan/CMakeLists.txt
@@ -3,6 +3,40 @@ set(UBSAN_LIT_TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR})
 set(UBSAN_TESTSUITES)
 set(UBSAN_TEST_DEPS ${SANITIZER_COMMON_LIT_TEST_DEPS})
 
+set(COMPILER_RT_UBSAN_CAN_RUN_HIP FALSE)
+set(COMPILER_RT_UBSAN_CAN_RUN_OPENMP_OFFLOAD FALSE)
+set(UBSAN_GPU_ARCH "")
+set(UBSAN_HIP_LIB_DIR "")
+
+# Determine if this machine can run the AMDGPU test suite.
+if(LLVM_RUNTIMES_BUILD AND COMPILER_RT_TEST_COMPILER_ID MATCHES "Clang")
+  find_program(UBSAN_OFFLOAD_ARCH offload-arch PATHS ${LLVM_TOOLS_BINARY_DIR})
+  if(UBSAN_OFFLOAD_ARCH)
+    execute_process(COMMAND ${UBSAN_OFFLOAD_ARCH} --only=amdgpu
+                    OUTPUT_VARIABLE _ubsan_amdgpu_archs
+                    OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
+    string(REPLACE "\n" ";" _ubsan_amdgpu_archs "${_ubsan_amdgpu_archs}")
+    if(_ubsan_amdgpu_archs)
+      list(GET _ubsan_amdgpu_archs 0 UBSAN_GPU_ARCH)
+    endif()
+  endif()
+
+  if(UBSAN_GPU_ARCH)
+    find_library(UBSAN_TEST_HIP_LIBRARY NAMES amdhip64
+      HINTS "$ENV{ROCM_PATH}/lib" "$ENV{HIP_PATH}/lib" /opt/rocm/lib)
+    if(UBSAN_TEST_HIP_LIBRARY)
+      set(COMPILER_RT_UBSAN_CAN_RUN_HIP TRUE)
+      get_filename_component(UBSAN_HIP_LIB_DIR "${UBSAN_TEST_HIP_LIBRARY}" DIRECTORY)
+    endif()
+    if(HAVE_OFFLOAD)
+      set(COMPILER_RT_UBSAN_CAN_RUN_OPENMP_OFFLOAD TRUE)
+    endif()
+  endif()
+endif()
+
+pythonize_bool(COMPILER_RT_UBSAN_CAN_RUN_HIP)
+pythonize_bool(COMPILER_RT_UBSAN_CAN_RUN_OPENMP_OFFLOAD)
+
 macro(add_ubsan_testsuite test_mode sanitizer arch lld thinlto)
   set(UBSAN_LIT_TEST_MODE "${test_mode}")
   set(CONFIG_NAME ${UBSAN_LIT_TEST_MODE})

diff  --git a/compiler-rt/test/ubsan/Inputs/hip.h b/compiler-rt/test/ubsan/Inputs/hip.h
new file mode 100644
index 0000000000000..5d8cad25dbbb2
--- /dev/null
+++ b/compiler-rt/test/ubsan/Inputs/hip.h
@@ -0,0 +1,48 @@
+//===-- hip.h -------------------------------------------------------------===//
+//
+// Minimal HIP headers so the tests can be compiled without a ROCm installation.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef UBSAN_TEST_HIP_H
+#define UBSAN_TEST_HIP_H
+
+#define __global__ __attribute__((global))
+#define __device__ __attribute__((device))
+#define __host__ __attribute__((host))
+#define __shared__ __attribute__((shared))
+#define __constant__ __attribute__((constant))
+
+struct dim3 {
+  unsigned x, y, z;
+  __host__ __device__ dim3(unsigned x = 1, unsigned y = 1, unsigned z = 1)
+      : x(x), y(y), z(z) {}
+};
+
+extern "C" {
+typedef struct ihipStream_t *hipStream_t;
+
+int hipMalloc(void **Ptr, unsigned long Size);
+int hipFree(void *Ptr);
+int hipDeviceSynchronize(void);
+
+int __hipPushCallConfiguration(dim3 GridDim, dim3 BlockDim,
+                               unsigned long SharedMem = 0,
+                               hipStream_t Stream = 0);
+int __hipPopCallConfiguration(dim3 *GridDim, dim3 *BlockDim,
+                              unsigned long *SharedMem, hipStream_t *Stream);
+int hipLaunchKernel(const void *Func, dim3 GridDim, dim3 BlockDim, void **Args,
+                    unsigned long SharedMem, hipStream_t Stream);
+
+int printf(const char *, ...);
+}
+
+#define CHECK_HIP(Expr)                                                        \
+  do {                                                                         \
+    if ((Expr) != 0) {                                                         \
+      printf("setup failed: %s\n", #Expr);                                     \
+      return 2;                                                                \
+    }                                                                          \
+  } while (0)
+
+#endif // UBSAN_TEST_HIP_H

diff  --git a/compiler-rt/test/ubsan/lit.common.cfg.py b/compiler-rt/test/ubsan/lit.common.cfg.py
index 314d207f94ad5..5314ee25130ad 100644
--- a/compiler-rt/test/ubsan/lit.common.cfg.py
+++ b/compiler-rt/test/ubsan/lit.common.cfg.py
@@ -95,3 +95,53 @@ def build_invocation(compile_flags):
         config.parallelism_group = "shadow-memory"
     if config.target_os == "NetBSD":
         config.substitutions.insert(0, ("%run", config.netbsd_noaslr_prefix))
+
+if ubsan_lit_test_mode == "Standalone":
+    _amdgpu_ubsan_rt = any(
+        os.path.isfile(
+            os.path.join(
+                config.compiler_rt_output_dir,
+                "lib",
+                triple,
+                "libclang_rt.ubsan_standalone.a",
+            )
+        )
+        for triple in ("amdgpu-amd-amdhsa", "amdgcn-amd-amdhsa")
+    )
+    if config.ubsan_can_run_hip and _amdgpu_ubsan_rt:
+        config.available_features.add("ubsan-hip")
+        hip_common = [
+            "-xhip",
+            "--offload-arch=" + config.ubsan_gpu_arch,
+            "-nogpuinc",
+            "-nogpulib",
+            "-g",
+            "-isystem",
+            os.path.join(config.test_source_root, "Inputs"),
+            "-include",
+            "hip.h",
+            "-fsanitize=undefined",
+        ]
+        hip_libs = [
+            "-L" + config.ubsan_hip_lib_dir,
+            "-lamdhip64",
+            "-Wl,-rpath," + config.ubsan_hip_lib_dir,
+        ]
+        config.substitutions.append(
+            ("%clang_ubsan_hip ", build_invocation(hip_common) + " ")
+        )
+        config.substitutions.append(("%hip_libs", " ".join(hip_libs)))
+    if config.ubsan_can_run_openmp_offload and _amdgpu_ubsan_rt:
+        config.available_features.add("ubsan-openmp-offload")
+        omp_common = [
+            "-fopenmp",
+            "--offload-arch=" + config.ubsan_gpu_arch,
+            "-g",
+            "-frtlib-add-rpath",
+            "-fsanitize=undefined",
+        ]
+        config.substitutions.append(
+            ("%clang_ubsan_omp ", build_invocation(omp_common) + " ")
+        )
+    if config.ubsan_can_run_hip or config.ubsan_can_run_openmp_offload:
+        lit_config.parallelism_groups["gpu"] = 1

diff  --git a/compiler-rt/test/ubsan/lit.site.cfg.py.in b/compiler-rt/test/ubsan/lit.site.cfg.py.in
index b5468b195be11..8e71cb28b0bed 100644
--- a/compiler-rt/test/ubsan/lit.site.cfg.py.in
+++ b/compiler-rt/test/ubsan/lit.site.cfg.py.in
@@ -10,6 +10,10 @@ config.use_thinlto = @UBSAN_TEST_USE_THINLTO@
 config.apple_platform = "@UBSAN_TEST_APPLE_PLATFORM@"
 config.apple_platform_min_deployment_target_flag = "@UBSAN_TEST_MIN_DEPLOYMENT_TARGET_FLAG@"
 config.apple_target_is_host = @UBSAN_TEST_APPLE_TARGET_IS_HOST_PYBOOL@
+config.ubsan_can_run_hip = @COMPILER_RT_UBSAN_CAN_RUN_HIP_PYBOOL@
+config.ubsan_can_run_openmp_offload = @COMPILER_RT_UBSAN_CAN_RUN_OPENMP_OFFLOAD_PYBOOL@
+config.ubsan_gpu_arch = "@UBSAN_GPU_ARCH@"
+config.ubsan_hip_lib_dir = "@UBSAN_HIP_LIB_DIR@"
 
 # Load common config for all compiler-rt lit tests.
 lit_config.load_config(config, "@COMPILER_RT_BINARY_DIR@/test/lit.common.configured")

diff  --git a/llvm/utils/gn/secondary/compiler-rt/lib/ubsan/BUILD.gn b/llvm/utils/gn/secondary/compiler-rt/lib/ubsan/BUILD.gn
index c6a511c3c714c..f9ba87e51e898 100644
--- a/llvm/utils/gn/secondary/compiler-rt/lib/ubsan/BUILD.gn
+++ b/llvm/utils/gn/secondary/compiler-rt/lib/ubsan/BUILD.gn
@@ -45,6 +45,7 @@ source_set("sources") {
     "ubsan_flags.h",
     "ubsan_handlers.cpp",
     "ubsan_handlers.h",
+    "ubsan_handlers_internal.h",
     "ubsan_init.cpp",
     "ubsan_init.h",
     "ubsan_monitor.cpp",


        


More information about the llvm-commits mailing list