[flang-commits] [clang] [flang] [llvm] [flang] Add -finit-local= to initialize automatic variables (PR #216164)

Daniel Chen via flang-commits flang-commits at lists.llvm.org
Tue Sep 1 17:50:22 PDT 2026


================
@@ -1250,6 +1254,236 @@ getSafeRepackAttrs(Fortran::lower::AbstractConverter &converter) {
   return attrs.empty() ? mlir::ArrayAttr{} : builder.getArrayAttr(attrs);
 }
 
+//===----------------------------------------------------------------------===//
+// -finit-local= helpers
+//===----------------------------------------------------------------------===//
+
+/// Returns true when \p var is an automatic local variable eligible for
+/// -finit-local= initialization. Excluded: variables without a symbol,
+/// globals, dummy arguments, SAVE'd vars, ALLOCATABLE/POINTER, vars in
+/// an EQUIVALENCE set, and vars with explicit or default initialization.
+static bool shouldInitLocal(const Fortran::lower::pft::Variable &var) {
+  if (!var.hasSymbol() || var.isGlobal())
+    return false;
+  const Fortran::semantics::Symbol &sym = var.getSymbol();
+  if (Fortran::semantics::IsDummy(sym))
+    return false;
+  if (Fortran::semantics::IsSaved(sym))
+    return false;
+  if (Fortran::semantics::IsAllocatableOrPointer(sym))
+    return false;
+  if (Fortran::lower::hasDefaultInitialization(sym))
+    return false;
+  if (const auto *obj =
+          sym.detailsIf<Fortran::semantics::ObjectEntityDetails>())
+    if (obj->init())
+      return false;
+  if (Fortran::semantics::FindEquivalenceSet(sym))
+    return false;
+  return true;
----------------
DanielCChen wrote:

> A procedure-scope local in an `attributes(global)` routine now initializes correctly.
> 
> The semantic context check still conflicts with the allocation decision in two cases:
> 
> * An explicit device local in an `attributes(host,device)` routine receives `cuf.alloc` and then a direct `fir.store`. The user assignment to that local uses `cuf.data_transfer`.
> * A local declared in a nested `BLOCK` of an `attributes(global)` routine receives device-side `fir.alloca` storage but no initialization.
> 
> Could the initialization check use the same region and storage classification that the allocation logic uses to select `cuf.alloc` or `fir.alloca`?
> 
> Could you add tests for `attributes(host,device)` routines and nested `BLOCK` constructs?

Both cases are fixed by removing the `Device` branch from `shouldInitLocal` and adding a single guard in `genInitLocal` using the same `cuf::isCUDADeviceContext(builder.getRegion())` call that the allocation logic uses — this naturally excludes `HostDevice` locals (which get `cuf.alloc`) and correctly admits BLOCK-construct locals inside `global` kernels (where the region walk reaches the enclosing `global` func). Tests for both cases added.

https://github.com/llvm/llvm-project/pull/216164


More information about the flang-commits mailing list