From 0794e81473d55ad0ae5c23814eb298d209ab7cce Mon Sep 17 00:00:00 2001 From: Axel Huebl Date: Mon, 7 Jul 2025 11:37:57 -0700 Subject: [PATCH] Test: Unorderded Map Access This demonstrates two issues with `std::unordered_map`: - `at()` fails to compile - `operator[]` has a memory leak --- .../test/Integration/ReverseMode/stl_umap.cpp | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 enzyme/test/Integration/ReverseMode/stl_umap.cpp diff --git a/enzyme/test/Integration/ReverseMode/stl_umap.cpp b/enzyme/test/Integration/ReverseMode/stl_umap.cpp new file mode 100644 index 000000000000..3e5c89723ced --- /dev/null +++ b/enzyme/test/Integration/ReverseMode/stl_umap.cpp @@ -0,0 +1,79 @@ +// TODO: -O0 need support for map inserts https://fwd.gymni.ch/R6Q2bQ +// RUN: %clang++ -std=c++11 -ffast-math -O1 %s -S -emit-llvm -o - | %opt - %OPloadEnzyme %enzyme -S | %lli - +// RUN: %clang++ -std=c++11 -ffast-math -O2 %s -S -emit-llvm -o - | %opt - %OPloadEnzyme %enzyme -S | %lli - +// RUN: %clang++ -std=c++11 -ffast-math -O3 %s -S -emit-llvm -o - | %opt - %OPloadEnzyme %enzyme -S | %lli - + +#include "../test_utils.h" + +#include +#include +#include + + +extern double __enzyme_autodiff(void*, double); + +std::unordered_map +fill_umap(double x, double y) { + std::unordered_map data; + + data["alpha_x"] = x*x + y; + data["alpha_y"] = y*y + 2.; + + return data; +} + +double compute_umap_op(double r) { + double x = std::sqrt(r); + double y = std::log(r); + + std::unordered_map data = fill_umap(x, y); + + // FIXME: memory leak + // https://github.com/EnzymeAD/Enzyme/issues/2367#issuecomment-3025856672 + return data["alpha_x"]; +} + +double compute_umap_at(double r) { + double x = std::sqrt(r); + double y = std::log(r); + + std::unordered_map const data = fill_umap(x, y); + + // FIXME: fails to compile + // https://fwd.gymni.ch/oGas9k + return data.at("alpha_x"); +} + +void test_umap() { + double r0 = 3.0; + + // operator[] + { + // normal + double const alpha_x = compute_umap_op(r0); + APPROX_EQ( alpha_x, 4.098612, 1e-6); + + // diff + double ddx = __enzyme_autodiff((void*) compute_umap_op, r0); + APPROX_EQ( ddx, 1.333333, 1e-6); + } + + // at() + { + // normal + double const alpha_x = compute_umap_at(r0); + APPROX_EQ( alpha_x, 4.098612, 1e-6); + + // diff + double ddx = __enzyme_autodiff((void*) compute_umap_at, r0); + APPROX_EQ( ddx, 1.333333, 1e-6); + } +} + +int main() { + test_umap(); + + return 0; +} + +