llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.39k stars 11.73k forks source link

CLang OpenMP: error capturing by reference variable of double nested lambdas #58421

Open polkovnikov opened 1 year ago

polkovnikov commented 1 year ago

Following code doesn't compile in CLang:

#include <vector>

int main() {
    std::vector<int> a(10);
    auto F = [&](auto f){
        #pragma omp parallel for
        for (int i = 0; i < 10; ++i)
            [&, i]{
                auto x = a[0];
            }();
    };
    F([&](auto i){ return i + 1; });
}

with error: error: reference to local variable 'a' declared in enclosing function 'main'

See example inside GodBolt.

But it compiles in GCC.

Code starts to compile in CLang after 3 types of modifications:

1) Either change auto F = [&](auto f){ to auto F = [&a](auto f){, i.e. do explicit capture of &a.

2) Or remove argument of F, i.e. change auto F = [&](auto f){ to auto F = [&]{, here (auto f) removed (also call F just as F();).

3) Or remove #pragma omp parallel for, i.e. remove OpenMP completely.

All 1)-3) types of modifications lead to compilable code. Of course only 1) is acceptable solution.

llvmbot commented 1 year ago

@llvm/issue-subscribers-openmp

llvmbot commented 1 year ago

@llvm/issue-subscribers-clang-frontend