dace-fortran 1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. dace_fortran/CMakeLists.txt +436 -0
  2. dace_fortran/__init__.py +161 -0
  3. dace_fortran/acc_residency.py +500 -0
  4. dace_fortran/bindings/__init__.py +67 -0
  5. dace_fortran/bindings/acc_transfers.py +491 -0
  6. dace_fortran/bindings/bind_c_shim.py +864 -0
  7. dace_fortran/bindings/block_builders.py +1843 -0
  8. dace_fortran/bindings/build_fortran_library.py +318 -0
  9. dace_fortran/bindings/emit_bindings.py +88 -0
  10. dace_fortran/bindings/flatten_plan.py +256 -0
  11. dace_fortran/bindings/fortran_interface.py +185 -0
  12. dace_fortran/bindings/frozen_signature.py +413 -0
  13. dace_fortran/bindings/loop_copy.py +211 -0
  14. dace_fortran/bindings/templates/alias.f90.in +2 -0
  15. dace_fortran/bindings/templates/c_interface.f90.in +20 -0
  16. dace_fortran/bindings/templates/copy_in.f90.in +4 -0
  17. dace_fortran/bindings/templates/copy_out.f90.in +4 -0
  18. dace_fortran/bindings/templates/handle_state.f90.in +8 -0
  19. dace_fortran/bindings/templates/module.f90.in +24 -0
  20. dace_fortran/bindings/templates/symbol_populate.f90.in +2 -0
  21. dace_fortran/bindings/templates/wrapper_call.f90.in +22 -0
  22. dace_fortran/bindings/templates/wrapper_head.f90.in +13 -0
  23. dace_fortran/bridge/ast/assigns.cpp +1932 -0
  24. dace_fortran/bridge/ast/ast_helpers.h +235 -0
  25. dace_fortran/bridge/ast/ast_internal.h +83 -0
  26. dace_fortran/bridge/ast/control_flow.cpp +937 -0
  27. dace_fortran/bridge/ast/dispatch.cpp +3613 -0
  28. dace_fortran/bridge/ast/elementals.cpp +970 -0
  29. dace_fortran/bridge/ast/expressions.cpp +2129 -0
  30. dace_fortran/bridge/bridge.cpp +624 -0
  31. dace_fortran/bridge/extract_ast.cpp +24 -0
  32. dace_fortran/bridge/extract_ast.h +90 -0
  33. dace_fortran/bridge/extract_vars.cpp +4873 -0
  34. dace_fortran/bridge/extract_vars.h +212 -0
  35. dace_fortran/bridge/trace_utils.cpp +952 -0
  36. dace_fortran/bridge/trace_utils.h +251 -0
  37. dace_fortran/bridge_types.py +237 -0
  38. dace_fortran/build.py +560 -0
  39. dace_fortran/build_bridge.py +365 -0
  40. dace_fortran/builder/__init__.py +2280 -0
  41. dace_fortran/builder/access.py +978 -0
  42. dace_fortran/builder/auto_dim_symbols.py +84 -0
  43. dace_fortran/builder/context.py +103 -0
  44. dace_fortran/builder/descriptors.py +1233 -0
  45. dace_fortran/builder/emit_cfg.py +1336 -0
  46. dace_fortran/builder/emit_library.py +2612 -0
  47. dace_fortran/builder/emit_tasklet.py +617 -0
  48. dace_fortran/builder/loop_local_arrays.py +59 -0
  49. dace_fortran/builder/prune_unused_arrays.py +120 -0
  50. dace_fortran/builder/records.py +110 -0
  51. dace_fortran/builder/scalar_shape_symbol_cleanup.py +76 -0
  52. dace_fortran/builder/statement_order.py +179 -0
  53. dace_fortran/builder/view_interstate_reads.py +79 -0
  54. dace_fortran/dace_setup.py +105 -0
  55. dace_fortran/dace_types.py +58 -0
  56. dace_fortran/data/__init__.py +7 -0
  57. dace_fortran/data/distributed.py +75 -0
  58. dace_fortran/demote_symbols.py +217 -0
  59. dace_fortran/emit_hlfir.py +372 -0
  60. dace_fortran/entry_names.py +105 -0
  61. dace_fortran/external.py +716 -0
  62. dace_fortran/external_functions.py +60 -0
  63. dace_fortran/flang_codebase.py +488 -0
  64. dace_fortran/fparser_inliner.py +1736 -0
  65. dace_fortran/inliner/__init__.py +10 -0
  66. dace_fortran/inliner/ast_desugaring/__init__.py +8 -0
  67. dace_fortran/inliner/ast_desugaring/analysis.py +2054 -0
  68. dace_fortran/inliner/ast_desugaring/cleanup.py +712 -0
  69. dace_fortran/inliner/ast_desugaring/desugaring.py +1112 -0
  70. dace_fortran/inliner/ast_desugaring/monomorphize.py +190 -0
  71. dace_fortran/inliner/ast_desugaring/monomorphize_rewrite.py +2014 -0
  72. dace_fortran/inliner/ast_desugaring/optimizations.py +853 -0
  73. dace_fortran/inliner/ast_desugaring/pruning.py +610 -0
  74. dace_fortran/inliner/ast_desugaring/specialize_at_source.py +742 -0
  75. dace_fortran/inliner/ast_desugaring/types.py +232 -0
  76. dace_fortran/inliner/ast_desugaring/utils.py +251 -0
  77. dace_fortran/inliner/ast_utils.py +56 -0
  78. dace_fortran/integer_power_exponents.py +87 -0
  79. dace_fortran/intrinsics/__init__.py +18 -0
  80. dace_fortran/intrinsics/base.py +16 -0
  81. dace_fortran/intrinsics/linalg.py +34 -0
  82. dace_fortran/libraries/__init__.py +2 -0
  83. dace_fortran/libraries/fft/__init__.py +2 -0
  84. dace_fortran/libraries/fft/nodes/__init__.py +10 -0
  85. dace_fortran/libraries/fft/nodes/fft_interpolate.py +403 -0
  86. dace_fortran/libraries/fortran_io/__init__.py +19 -0
  87. dace_fortran/libraries/fortran_io/dace_fortran_io.f90 +346 -0
  88. dace_fortran/libraries/fortran_io/dace_fortran_io.h +48 -0
  89. dace_fortran/libraries/fortran_io/environments/__init__.py +5 -0
  90. dace_fortran/libraries/fortran_io/environments/fortran_io.py +32 -0
  91. dace_fortran/libraries/fortran_io/fortran_io.cmake +16 -0
  92. dace_fortran/libraries/fortran_io/nodes/__init__.py +7 -0
  93. dace_fortran/libraries/fortran_io/nodes/namelist.py +91 -0
  94. dace_fortran/libraries/fortran_io/nodes/node.py +76 -0
  95. dace_fortran/libraries/fortran_io/nodes/read.py +70 -0
  96. dace_fortran/libraries/fortran_io/nodes/write.py +74 -0
  97. dace_fortran/llvm_compat.h +57 -0
  98. dace_fortran/llvm_toolchain.py +112 -0
  99. dace_fortran/loop_unroll.py +100 -0
  100. dace_fortran/omp_threads.py +73 -0
  101. dace_fortran/passes/DefaultIntent.cpp +168 -0
  102. dace_fortran/passes/DropStubCalls.cpp +124 -0
  103. dace_fortran/passes/EliminateDoubleBufferToggle.cpp +439 -0
  104. dace_fortran/passes/ExpandVectorSubscriptGather.cpp +379 -0
  105. dace_fortran/passes/ExpandVectorSubscriptScatter.cpp +506 -0
  106. dace_fortran/passes/FlattenGlobalScalarReads.cpp +261 -0
  107. dace_fortran/passes/FlattenStructs.cpp +6070 -0
  108. dace_fortran/passes/FoldAssumedRankQueries.cpp +356 -0
  109. dace_fortran/passes/FoldConstantScalars.cpp +248 -0
  110. dace_fortran/passes/FoldCopyInOut.cpp +833 -0
  111. dace_fortran/passes/FoldElementAliases.cpp +210 -0
  112. dace_fortran/passes/InlineAll.cpp +264 -0
  113. dace_fortran/passes/LiftAllocArrayOfRecords.cpp +867 -0
  114. dace_fortran/passes/LiftAosPointerRecords.cpp +1103 -0
  115. dace_fortran/passes/LiftReductionOperands.cpp +532 -0
  116. dace_fortran/passes/LowerFirSelectCase.cpp +187 -0
  117. dace_fortran/passes/MarkBoundsRemapViews.cpp +386 -0
  118. dace_fortran/passes/MarshalExternalStructs.cpp +675 -0
  119. dace_fortran/passes/Passes.cpp +82 -0
  120. dace_fortran/passes/Passes.h +64 -0
  121. dace_fortran/passes/PreserveMutableGlobals.cpp +251 -0
  122. dace_fortran/passes/PropagateShapes.cpp +209 -0
  123. dace_fortran/passes/PruneNeverAllocatedMemberDeref.cpp +252 -0
  124. dace_fortran/passes/PruneUnreachable.cpp +170 -0
  125. dace_fortran/passes/RaggedAos.cpp +803 -0
  126. dace_fortran/passes/RejectPolymorphism.cpp +114 -0
  127. dace_fortran/passes/RewritePointerAssigns.cpp +2007 -0
  128. dace_fortran/passes/RewriteSequenceAssociation.cpp +634 -0
  129. dace_fortran/passes/StripCharacterRuntime.cpp +288 -0
  130. dace_fortran/passes/StripErrorHelpers.cpp +239 -0
  131. dace_fortran/passes/StripRuntimeIo.cpp +225 -0
  132. dace_fortran/passes/UnwrapEvalInMem.cpp +394 -0
  133. dace_fortran/passes/VerifyNoUnresolvedCalls.cpp +106 -0
  134. dace_fortran/passes/VersionShapeScalars.cpp +319 -0
  135. dace_fortran/passes/ragged_aos.h +47 -0
  136. dace_fortran/passes/shallow_alias.h +33 -0
  137. dace_fortran/persistent_transients.py +101 -0
  138. dace_fortran/pipelines.py +466 -0
  139. dace_fortran/preprocess.py +1304 -0
  140. dace_fortran/preprocess_cli.py +259 -0
  141. dace_fortran-1.3.dist-info/METADATA +604 -0
  142. dace_fortran-1.3.dist-info/RECORD +148 -0
  143. dace_fortran-1.3.dist-info/WHEEL +5 -0
  144. dace_fortran-1.3.dist-info/entry_points.txt +2 -0
  145. dace_fortran-1.3.dist-info/licenses/AUTHORS +8 -0
  146. dace_fortran-1.3.dist-info/licenses/LICENSE +674 -0
  147. dace_fortran-1.3.dist-info/licenses/NOTICE +27 -0
  148. dace_fortran-1.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,436 @@
1
+ # ============================================================================
2
+ # CMakeLists.txt -- hlfir_bridge
3
+ # ============================================================================
4
+ # Build targets:
5
+ # hlfir_bridge_core -- static lib (trace/extract)
6
+ # hlfir_bridge_passes -- static lib (MLIR passes)
7
+ # hlfir_bridge -- Python ext (nanobind; links both above)
8
+ #
9
+ # MLIR linking strategy (cf. pixel-druid.com/articles/how-to-link-against-mlir-with-cmake):
10
+ # Debian/Ubuntu MLIR cmake configs are often broken (missing tool binaries
11
+ # cause CMake export-set errors), so find_package(MLIR) is used only on a
12
+ # prefix that has no monolithic libMLIR. Otherwise find_package(LLVM) --
13
+ # which always works -- locates MLIR headers and libraries through LLVM's
14
+ # install prefix. MLIR is always co-installed alongside LLVM.
15
+ # ============================================================================
16
+
17
+ cmake_minimum_required(VERSION 3.18)
18
+
19
+ # --- LLVM version ------------------------------------------------------------
20
+ # -DLLVM_VERSION pins a major; empty means "probe LLVM_SUPPORTED_VERSIONS and take
21
+ # the first one installed". Keep this list in sync with llvm_toolchain.py's
22
+ # SUPPORTED_LLVM_VERSIONS and with llvm_compat.h's LLVM_VERSION_MAJOR arms.
23
+ set(LLVM_SUPPORTED_VERSIONS "21;22" CACHE STRING "LLVM major versions the bridge supports, in preference order")
24
+ set(LLVM_VERSION "" CACHE STRING "LLVM major version to use (empty: auto-detect)")
25
+
26
+ # Debian/Ubuntu ship flang-new-<major>/flang-<major>; spack and upstream installs
27
+ # ship only unversioned flang-new/flang, which have to self-identify.
28
+ function(_flang_reported_major out_var binary)
29
+ execute_process(COMMAND "${binary}" --version OUTPUT_VARIABLE _out ERROR_QUIET)
30
+ string(REGEX MATCH "flang(-new)? version ([0-9]+)" _match "${_out}")
31
+ set(${out_var} "${CMAKE_MATCH_2}" PARENT_SCOPE)
32
+ endfunction()
33
+
34
+ function(_find_flang_for out_bin out_version)
35
+ set(_versions "${LLVM_SUPPORTED_VERSIONS}")
36
+ if(LLVM_VERSION)
37
+ set(_versions "${LLVM_VERSION}")
38
+ endif()
39
+ foreach(_v IN LISTS _versions)
40
+ unset(_probe CACHE)
41
+ find_program(_probe NAMES flang-new-${_v} flang-${_v})
42
+ if(NOT _probe)
43
+ unset(_probe CACHE)
44
+ find_program(_probe NAMES flang-new flang)
45
+ if(_probe)
46
+ _flang_reported_major(_major "${_probe}")
47
+ if(NOT _major STREQUAL _v)
48
+ set(_probe "_probe-NOTFOUND")
49
+ endif()
50
+ endif()
51
+ endif()
52
+ if(_probe)
53
+ set(${out_bin} "${_probe}" PARENT_SCOPE)
54
+ set(${out_version} "${_v}" PARENT_SCOPE)
55
+ return()
56
+ endif()
57
+ endforeach()
58
+ set(${out_bin} "" PARENT_SCOPE)
59
+ set(${out_version} "" PARENT_SCOPE)
60
+ endfunction()
61
+
62
+ # A caller that already resolved the toolchain pins it with -DFLANG_BIN. Probing again here is
63
+ # what let two detectors disagree: this file overwrites LLVM_VERSION with whatever IT found, so a
64
+ # build told to use one major could compile against another's MLIR and fail at dlopen.
65
+ if(FLANG_BIN)
66
+ set(_FLANG_BIN "${FLANG_BIN}")
67
+ _flang_reported_major(_FLANG_VERSION "${FLANG_BIN}")
68
+ if(LLVM_VERSION AND _FLANG_VERSION AND NOT _FLANG_VERSION STREQUAL LLVM_VERSION)
69
+ message(FATAL_ERROR "FLANG_BIN (${FLANG_BIN}) is LLVM ${_FLANG_VERSION}, but LLVM_VERSION="
70
+ "${LLVM_VERSION} was requested. Pass a matching pair, or neither.")
71
+ endif()
72
+ else()
73
+ _find_flang_for(_FLANG_BIN _FLANG_VERSION)
74
+ endif()
75
+ if(_FLANG_VERSION)
76
+ set(LLVM_VERSION "${_FLANG_VERSION}")
77
+ elseif(NOT LLVM_VERSION)
78
+ # No flang on PATH: fall back to the newest supported major so LLVM_DIR /
79
+ # the distro paths below still get a version to substitute.
80
+ list(GET LLVM_SUPPORTED_VERSIONS -1 LLVM_VERSION)
81
+ message(STATUS "No flang found for LLVM ${LLVM_SUPPORTED_VERSIONS}; assuming ${LLVM_VERSION}")
82
+ endif()
83
+
84
+ # --- Discover LLVM prefix from flang -----------------------------------------
85
+ set(_LLVM_PREFIX "" CACHE PATH "LLVM installation prefix (auto-detected)")
86
+
87
+ if(NOT _LLVM_PREFIX AND _FLANG_BIN)
88
+ get_filename_component(_FLANG_REAL "${_FLANG_BIN}" REALPATH)
89
+ get_filename_component(_FLANG_BINDIR "${_FLANG_REAL}" DIRECTORY)
90
+ get_filename_component(_LLVM_PREFIX "${_FLANG_BINDIR}" DIRECTORY)
91
+ message(STATUS "Derived LLVM ${LLVM_VERSION} prefix from ${_FLANG_BIN}: ${_LLVM_PREFIX}")
92
+ endif()
93
+
94
+ # --- Default compilers -------------------------------------------------------
95
+ # Prefer the clang shipped in the same prefix as the LLVM we link against, under
96
+ # either the versioned (distro) or unversioned (spack/upstream) name.
97
+ macro(_default_compiler lang envvar stem)
98
+ if(NOT DEFINED CMAKE_${lang}_COMPILER AND NOT DEFINED ENV{${envvar}})
99
+ unset(_found CACHE)
100
+ if(_LLVM_PREFIX)
101
+ find_program(_found NAMES ${stem}-${LLVM_VERSION} ${stem} PATHS "${_LLVM_PREFIX}/bin" NO_DEFAULT_PATH)
102
+ endif()
103
+ if(NOT _found)
104
+ unset(_found CACHE)
105
+ find_program(_found NAMES ${stem}-${LLVM_VERSION})
106
+ endif()
107
+ if(_found)
108
+ set(CMAKE_${lang}_COMPILER "${_found}" CACHE FILEPATH "")
109
+ endif()
110
+ unset(_found CACHE)
111
+ endif()
112
+ endmacro()
113
+ _default_compiler(C CC clang)
114
+ _default_compiler(CXX CXX clang++)
115
+
116
+ if(NOT DEFINED CMAKE_Fortran_COMPILER AND NOT DEFINED ENV{FC})
117
+ if(_FLANG_BIN)
118
+ set(CMAKE_Fortran_COMPILER "${_FLANG_BIN}" CACHE FILEPATH "")
119
+ endif()
120
+ endif()
121
+
122
+ project(hlfir_bridge C CXX)
123
+
124
+ set(CMAKE_CXX_STANDARD 17)
125
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
126
+ set(CMAKE_POSITION_INDEPENDENT_CODE ON)
127
+
128
+ # --- LLVM (the only find_package we use) -------------------------------------
129
+ if(NOT LLVM_DIR)
130
+ if(_LLVM_PREFIX AND EXISTS "${_LLVM_PREFIX}/lib/cmake/llvm/LLVMConfig.cmake")
131
+ set(LLVM_DIR "${_LLVM_PREFIX}/lib/cmake/llvm" CACHE PATH "")
132
+ else()
133
+ message(FATAL_ERROR "No LLVMConfig.cmake next to flang ${_FLANG_BIN} (prefix '${_LLVM_PREFIX}'); "
134
+ "put an LLVM ${LLVM_VERSION} flang on PATH or pass -DLLVM_DIR.")
135
+ endif()
136
+ endif()
137
+
138
+ find_package(LLVM REQUIRED CONFIG)
139
+ if(NOT LLVM_VERSION_MAJOR IN_LIST LLVM_SUPPORTED_VERSIONS)
140
+ message(FATAL_ERROR "LLVM ${LLVM_PACKAGE_VERSION} in ${LLVM_DIR} is unsupported; "
141
+ "the bridge builds against LLVM ${LLVM_SUPPORTED_VERSIONS}.")
142
+ endif()
143
+ # Every component has to be the same major. flang emits the HLFIR that MLIR then parses, so a
144
+ # flang of one major against an MLIR of another is not a version skew that shows up at build time
145
+ # -- it links, and then misparses or fails to dlopen.
146
+ if(_FLANG_VERSION AND NOT _FLANG_VERSION STREQUAL LLVM_VERSION_MAJOR)
147
+ message(FATAL_ERROR "Mixed LLVM majors: flang ${_FLANG_BIN} is ${_FLANG_VERSION}, but "
148
+ "${LLVM_DIR} is LLVM ${LLVM_PACKAGE_VERSION}. Point LLVM_DIR and "
149
+ "FLANG_BIN at one install.")
150
+ endif()
151
+ set(LLVM_VERSION "${LLVM_VERSION_MAJOR}")
152
+ message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION} in ${LLVM_DIR}")
153
+
154
+ # Same major, different install: legal, but flang and MLIR then differ by point release, which is
155
+ # a skew nothing downstream can detect. Say so rather than let it pass unremarked.
156
+ if(DEFINED LLVM_INSTALL_PREFIX AND _LLVM_PREFIX AND NOT _LLVM_PREFIX STREQUAL LLVM_INSTALL_PREFIX)
157
+ message(WARNING "flang comes from ${_LLVM_PREFIX} but LLVM/MLIR from ${LLVM_INSTALL_PREFIX}; "
158
+ "both are LLVM ${LLVM_VERSION_MAJOR}, but they are different installs.")
159
+ endif()
160
+ message(STATUS "LLVM include dirs: ${LLVM_INCLUDE_DIRS}")
161
+ message(STATUS "LLVM library dir: ${LLVM_LIBRARY_DIR}")
162
+
163
+ list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}")
164
+ include(AddLLVM)
165
+
166
+ # Debian builds LLVM with RTTI, upstream/spack default to without. Subclassing an
167
+ # MLIR class from an -frtti translation unit against an -fno-rtti LLVM leaves the
168
+ # base's typeinfo undefined at import time, so the MLIR-facing libraries follow
169
+ # whatever the prefix was built with. The nanobind module cannot: nanobind's own
170
+ # headers use typeid. Hence installPassTracer lives in the passes library.
171
+ if(LLVM_ENABLE_RTTI)
172
+ set(BRIDGE_MLIR_RTTI_FLAGS "")
173
+ else()
174
+ set(BRIDGE_MLIR_RTTI_FLAGS -fno-rtti)
175
+ endif()
176
+
177
+ # --- MLIR --------------------------------------------------------------------
178
+ # A monolithic libMLIR tells the two prefix shapes apart. Debian ships one and
179
+ # splits the cmake config across packages so that including it is a hard error,
180
+ # not a QUIET miss -- its export set names tool binaries the packages omit; MLIR
181
+ # is located through the LLVM prefix there. A source or spack install has no
182
+ # dylib but a working MLIRConfig.cmake, and the static component closure has to
183
+ # come from that package: its imported targets pre-empt the manual ones below.
184
+ # Search the prefix ONLY: a dylib from the system path can belong to a different
185
+ # point release than the prefix's static libs, which links and then misbehaves.
186
+ #
187
+ # find_library alone is not enough. It matches the unversioned development
188
+ # symlink, which a spack or source install frequently omits -- it ships
189
+ # libLLVM.so.21.1 and nothing else. Missing the dylib is not a cosmetic miss:
190
+ # the static branch further down then links LLVM into this module while the same
191
+ # dylib still arrives through DT_NEEDED on the flang libraries, and a global that
192
+ # exists in both copies has its destructor run twice. Observed as a SIGABRT in
193
+ # llvm::TensorSpec::~TensorSpec() out of exit().
194
+ macro(find_mono_lib out)
195
+ find_library(${out} NAMES ${ARGN} PATHS "${LLVM_LIBRARY_DIR}" NO_DEFAULT_PATH)
196
+ if(NOT ${out})
197
+ foreach(_base ${ARGN})
198
+ file(GLOB _versioned "${LLVM_LIBRARY_DIR}/lib${_base}.so.*")
199
+ list(SORT _versioned)
200
+ if(_versioned)
201
+ list(GET _versioned 0 ${out})
202
+ break()
203
+ endif()
204
+ endforeach()
205
+ endif()
206
+ endmacro()
207
+
208
+ find_mono_lib(MLIR_MONO_LIB MLIR)
209
+ if(NOT MLIR_MONO_LIB)
210
+ find_package(MLIR CONFIG QUIET HINTS "${LLVM_LIBRARY_DIR}/cmake/mlir")
211
+ endif()
212
+ if(NOT MLIR_FOUND)
213
+ set(MLIR_INCLUDE_DIRS "${LLVM_INCLUDE_DIRS}" CACHE PATH "MLIR include dirs")
214
+ endif()
215
+ message(STATUS "MLIR cmake package: ${MLIR_FOUND}")
216
+
217
+ # Helper: find one MLIR (or Flang) library and create an imported target.
218
+ # Usage: find_mlir_lib(MLIRIR) -> creates target MLIRIR if libMLIRIR.a exists.
219
+ macro(find_mlir_lib name)
220
+ if(NOT TARGET ${name})
221
+ find_library(_${name}_LIB ${name} HINTS ${LLVM_LIBRARY_DIR} NO_DEFAULT_PATH)
222
+ if(_${name}_LIB)
223
+ add_library(${name} STATIC IMPORTED)
224
+ set_target_properties(${name} PROPERTIES IMPORTED_LOCATION "${_${name}_LIB}")
225
+ else()
226
+ message(WARNING "Cannot find lib${name} in ${LLVM_LIBRARY_DIR}")
227
+ endif()
228
+ unset(_${name}_LIB CACHE)
229
+ endif()
230
+ endmacro()
231
+
232
+ # The MLIR libraries we actually use.
233
+ set(_MLIR_LIBS
234
+ MLIRIR MLIRParser MLIRSupport
235
+ MLIRPass MLIRTransforms
236
+ MLIRFuncDialect MLIRArithDialect MLIRSCFDialect
237
+ MLIRControlFlowToSCF
238
+ MLIROptLib
239
+ )
240
+ foreach(_lib ${_MLIR_LIBS})
241
+ find_mlir_lib(${_lib})
242
+ endforeach()
243
+
244
+ # Monolithic shared libs (Debian ships these; handles transitive deps).
245
+ # Debian names it libLLVM-<major>.so and drops it on the default link path; spack
246
+ # and upstream keep it in the LLVM prefix, sometimes as a plain libLLVM.so -- so
247
+ # resolve a full path rather than emitting a bare -lLLVM-<major>.
248
+ # Search the prefix ONLY, for the reason given at the MLIR_MONO_LIB probe above.
249
+ find_mono_lib(LLVM_MONO_LIB LLVM-${LLVM_VERSION_MAJOR} LLVM)
250
+ # What the bridge finally links for MLIR/LLVM. Two shapes:
251
+ # * dylib prefix (Debian): the two monolithic libs resolve everything;
252
+ # * static-only prefix (source / spack builds): no dylib exists, so the whole
253
+ # archive set stands in for it. The flang dialect libs are pulled with
254
+ # --whole-archive ahead of these, and they reference far more of MLIR than
255
+ # the components this bridge names itself, so nothing narrower resolves.
256
+ if(MLIR_MONO_LIB)
257
+ set(MLIR_LINK_LIBS "${MLIR_MONO_LIB}")
258
+ else()
259
+ file(GLOB MLIR_LINK_LIBS "${LLVM_LIBRARY_DIR}/libMLIR*.a")
260
+ endif()
261
+ if(LLVM_MONO_LIB)
262
+ set(LLVM_LINK_LIBS "${LLVM_MONO_LIB}")
263
+ elseif(MLIR_LINK_LIBS)
264
+ file(GLOB LLVM_LINK_LIBS "${LLVM_LIBRARY_DIR}/libLLVM*.a")
265
+ else()
266
+ set(LLVM_LINK_LIBS "LLVM-${LLVM_VERSION_MAJOR}")
267
+ endif()
268
+ # Never mix a shared MLIR with static LLVM archives. libMLIR.so carries its own LLVM through
269
+ # DT_NEEDED, so linking the archives beside it puts every LLVM global in the process twice and
270
+ # both copies are destroyed at exit -- which aborts as "double free or corruption" long after
271
+ # the build itself looked fine. A prefix that ships libMLIR.so ships an LLVM dylib too, so
272
+ # failing to resolve one is a broken probe, not a supported layout.
273
+ if(MLIR_MONO_LIB AND NOT LLVM_MONO_LIB)
274
+ message(FATAL_ERROR
275
+ "Found a monolithic MLIR (${MLIR_MONO_LIB}) but no monolithic LLVM in "
276
+ "${LLVM_LIBRARY_DIR}. Linking static libLLVM*.a beside a shared MLIR duplicates "
277
+ "LLVM's globals and aborts at exit. Point LLVM_DIR at a prefix that ships an LLVM "
278
+ "dylib (libLLVM.so, libLLVM.so.<ver>, or libLLVM-${LLVM_VERSION_MAJOR}.so).")
279
+ endif()
280
+
281
+ list(LENGTH MLIR_LINK_LIBS _n_mlir_link)
282
+ list(LENGTH LLVM_LINK_LIBS _n_llvm_link)
283
+ message(STATUS "MLIR link: ${_n_mlir_link} lib(s) (${MLIR_MONO_LIB}), "
284
+ "LLVM link: ${_n_llvm_link} lib(s) (${LLVM_MONO_LIB})")
285
+
286
+ # --- Flang dialect libraries --------------------------------------------------
287
+ set(FLANG_DIALECT_LIBS
288
+ HLFIRDialect FIRDialect FIRDialectSupport FIRSupport
289
+ FIRBuilder FIRAnalysis CUFDialect CUFAttrs
290
+ # ---- flang transforms / codegen ---------------------------------
291
+ # Needed so the bridge can run ``fir-polymorphic-op``, which
292
+ # statically devirtualises ``fir.dispatch`` / ``fir.select_type``
293
+ # ops whose target is resolvable at compile time. Surviving
294
+ # dispatches after the conversion are caught loudly by our own
295
+ # ``hlfir-reject-polymorphism`` pass. The user-visible benefit:
296
+ # CLASS-typed code that doesn't actually USE polymorphism (every
297
+ # call site has a static target) lowers cleanly.
298
+ #
299
+ # The cascade of libs here is dictated by what
300
+ # PolymorphicOpConversion.cpp actually references. Each one is
301
+ # noted with the symbol that pulls it in:
302
+ # FIRTransforms fir::createPolymorphicOpConversion
303
+ # FIRCodeGenDialect fir.cg.XDeclareOp (used by select_type
304
+ # -> cf branch lowering)
305
+ # FIRCodeGen fir::LLVMTypeConverter::convertBoxTypeAsStruct
306
+ # FortranSupport Fortran::common::getFlangFullVersion (codegen
307
+ # produced-by metadata)
308
+ # FIROpenACCSupport fir::acc::registerTransformationalAttrs
309
+ # FIROpenMPSupport fir::omp::registerTransformationalAttrs
310
+ # (both are defensive dialect registrations
311
+ # FIRCodeGen.a calls unconditionally; the
312
+ # bridge doesn't use OpenACC or OpenMP, this
313
+ # is purely transitive linker-cleanup.)
314
+ FIRTransforms FIRCodeGenDialect FIRCodeGen FortranSupport
315
+ FIROpenACCSupport FIROpenMPSupport
316
+ )
317
+
318
+ # LLVM 22 added the ``mif`` (multi-image FIR / coarray) dialect --
319
+ # flang/lib/Optimizer/Dialect/MIF, absent in 21 -- and FIRTransforms.a now
320
+ # references its op TypeIDs, so the module fails to dlopen without it.
321
+ if(LLVM_VERSION_MAJOR GREATER_EQUAL 22)
322
+ list(APPEND FLANG_DIALECT_LIBS MIFDialect)
323
+ endif()
324
+
325
+ foreach(_lib ${FLANG_DIALECT_LIBS})
326
+ find_mlir_lib(${_lib})
327
+ endforeach()
328
+
329
+ # --- Flang include dir --------------------------------------------------------
330
+ if(NOT FLANG_INCLUDE_DIR)
331
+ set(FLANG_INCLUDE_DIR "${LLVM_INCLUDE_DIRS}")
332
+ endif()
333
+
334
+ # --- Python + nanobind --------------------------------------------------------
335
+ find_package(Python 3.8 REQUIRED COMPONENTS Interpreter Development.Module)
336
+
337
+ execute_process(
338
+ COMMAND ${Python_EXECUTABLE} -c "import nanobind; print(nanobind.cmake_dir())"
339
+ OUTPUT_VARIABLE NB_CMAKE_DIR
340
+ OUTPUT_STRIP_TRAILING_WHITESPACE
341
+ RESULT_VARIABLE NB_STATUS)
342
+ if(NOT NB_STATUS EQUAL 0)
343
+ message(FATAL_ERROR "nanobind not found. Install with: pip install nanobind")
344
+ endif()
345
+ list(APPEND CMAKE_PREFIX_PATH "${NB_CMAKE_DIR}")
346
+ find_package(nanobind CONFIG REQUIRED)
347
+
348
+ # --- Common include paths -----------------------------------------------------
349
+ include_directories(
350
+ ${CMAKE_SOURCE_DIR}
351
+ ${LLVM_INCLUDE_DIRS}
352
+ ${MLIR_INCLUDE_DIRS}
353
+ ${FLANG_INCLUDE_DIR}
354
+ )
355
+ add_compile_definitions(FLANG_LITTLE_ENDIAN=1)
356
+ separate_arguments(LLVM_DEFINITIONS_LIST NATIVE_COMMAND ${LLVM_DEFINITIONS})
357
+ add_compile_definitions(${LLVM_DEFINITIONS_LIST})
358
+
359
+ # --- Core: trace + extraction -------------------------------------------------
360
+ add_library(hlfir_bridge_core STATIC
361
+ bridge/trace_utils.cpp
362
+ bridge/extract_vars.cpp
363
+ bridge/extract_ast.cpp
364
+ bridge/ast/expressions.cpp
365
+ bridge/ast/assigns.cpp
366
+ bridge/ast/elementals.cpp
367
+ bridge/ast/control_flow.cpp
368
+ bridge/ast/dispatch.cpp
369
+ )
370
+ target_link_libraries(hlfir_bridge_core PUBLIC
371
+ MLIRIR MLIRParser MLIRSupport MLIRFuncDialect MLIRArithDialect
372
+ )
373
+ target_compile_options(hlfir_bridge_core PRIVATE ${BRIDGE_MLIR_RTTI_FLAGS})
374
+
375
+ # --- Passes library -----------------------------------------------------------
376
+ add_library(hlfir_bridge_passes STATIC
377
+ passes/Passes.cpp
378
+ passes/PropagateShapes.cpp
379
+ passes/VersionShapeScalars.cpp
380
+ passes/InlineAll.cpp
381
+ passes/LowerFirSelectCase.cpp
382
+ passes/FlattenStructs.cpp
383
+ passes/RaggedAos.cpp
384
+ passes/FlattenGlobalScalarReads.cpp
385
+ passes/EliminateDoubleBufferToggle.cpp
386
+ passes/DefaultIntent.cpp
387
+ passes/VerifyNoUnresolvedCalls.cpp
388
+ passes/FoldElementAliases.cpp
389
+ passes/DropStubCalls.cpp
390
+ passes/FoldCopyInOut.cpp
391
+ passes/ExpandVectorSubscriptGather.cpp
392
+ passes/ExpandVectorSubscriptScatter.cpp
393
+ passes/RejectPolymorphism.cpp
394
+ passes/RewritePointerAssigns.cpp
395
+ passes/RewriteSequenceAssociation.cpp
396
+ passes/LiftReductionOperands.cpp
397
+ passes/LiftAllocArrayOfRecords.cpp
398
+ passes/LiftAosPointerRecords.cpp
399
+ passes/PruneUnreachable.cpp
400
+ passes/MarshalExternalStructs.cpp
401
+ passes/UnwrapEvalInMem.cpp
402
+ passes/StripErrorHelpers.cpp
403
+ passes/StripRuntimeIo.cpp
404
+ passes/StripCharacterRuntime.cpp
405
+ passes/PreserveMutableGlobals.cpp
406
+ passes/MarkBoundsRemapViews.cpp
407
+ passes/FoldAssumedRankQueries.cpp
408
+ passes/PruneNeverAllocatedMemberDeref.cpp
409
+ passes/FoldConstantScalars.cpp
410
+ )
411
+ target_link_libraries(hlfir_bridge_passes PUBLIC
412
+ hlfir_bridge_core
413
+ MLIRPass MLIRTransforms
414
+ MLIRControlFlowToSCF
415
+ )
416
+ target_compile_options(hlfir_bridge_passes PRIVATE ${BRIDGE_MLIR_RTTI_FLAGS})
417
+
418
+ # --- Python extension ---------------------------------------------------------
419
+ nanobind_add_module(hlfir_bridge NB_STATIC bridge/bridge.cpp)
420
+ target_link_libraries(hlfir_bridge PRIVATE
421
+ hlfir_bridge_core
422
+ hlfir_bridge_passes
423
+ -Wl,--whole-archive
424
+ ${FLANG_DIALECT_LIBS}
425
+ -Wl,--no-whole-archive
426
+ -Wl,--start-group
427
+ ${MLIR_LINK_LIBS}
428
+ ${LLVM_LINK_LIBS}
429
+ -Wl,--end-group
430
+ )
431
+ set_target_properties(hlfir_bridge PROPERTIES
432
+ INSTALL_RPATH "${LLVM_LIBRARY_DIR}"
433
+ BUILD_WITH_INSTALL_RPATH TRUE)
434
+
435
+ # --- Install ------------------------------------------------------------------
436
+ install(TARGETS hlfir_bridge LIBRARY DESTINATION .)
@@ -0,0 +1,161 @@
1
+ # Copyright 2025-2026 ETH Zurich and the dace-fortran authors. All rights reserved.
2
+ # SPDX-License-Identifier: GPL-3.0-or-later
3
+ """Fortran (HLFIR) frontend for DaCe: lowers Fortran through flang-new's
4
+ HLFIR and an MLIR/C++ bridge into a ``dace.SDFG``.
5
+
6
+ Entry points below are exposed lazily so ``import dace_fortran`` stays
7
+ cheap -- the C++ bridge builds on first use, not at import time. See
8
+ README "Building an SDFG from a real project" for worked examples.
9
+ """
10
+
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from dace_fortran.dace_setup import ensure_dace
14
+
15
+ # Before anything imports dace: a PyPI DaCe is replaced by the DaCe branch the frontend needs (dace_setup.py).
16
+ ensure_dace()
17
+
18
+ if TYPE_CHECKING:
19
+ from dace_fortran.acc_residency import extract_acc_residency, write_acc_residency_sidecar
20
+ from dace_fortran.build import build_sdfg, build_sdfg_from_files, build_sdfg_from_hlfir, build_sdfg_from_project
21
+ from dace_fortran.builder import DEFAULT_PIPELINE, MULTI_FILE_PIPELINE, SDFGBuilder
22
+ from dace_fortran.external import (
23
+ Arg,
24
+ ArgKind,
25
+ CAbi,
26
+ ExternalSignature,
27
+ Intent,
28
+ apply_external_functions,
29
+ clear_external_registry,
30
+ keep_external,
31
+ register_external,
32
+ )
33
+ from dace_fortran.external_functions import ExternalFunction
34
+ from dace_fortran.flang_codebase import (
35
+ FLANG_BUG_PATCHES,
36
+ LIBRARY_STUBS,
37
+ emit_hlfir_from_codebase,
38
+ extract_make_compile_args,
39
+ find_openmpi_include,
40
+ mpi_stub_source,
41
+ prepare_flang_translation_unit,
42
+ vendor_netcdf_fortran,
43
+ )
44
+ from dace_fortran.fparser_inliner import inline_to_ast, inline_to_single_tu
45
+ from dace_fortran.preprocess import (
46
+ MergeEngine,
47
+ merge_used_modules,
48
+ normalize_kind_parameters,
49
+ preprocess_fortran,
50
+ preprocess_fortran_source,
51
+ replace_external_with_modules,
52
+ rewrite_integer_powers,
53
+ rewrite_string_enum_to_integer,
54
+ )
55
+
56
+ _LAZY = {
57
+ # Public build entry points (the documented surface).
58
+ "build_sdfg": "dace_fortran.build",
59
+ "build_sdfg_from_files": "dace_fortran.build",
60
+ "build_sdfg_from_hlfir": "dace_fortran.build",
61
+ "build_sdfg_from_project": "dace_fortran.build",
62
+ # emit_hlfir is a module (CLI or direct import), not a single function -- not in this facade.
63
+ "register_external": "dace_fortran.external",
64
+ "keep_external": "dace_fortran.external",
65
+ "apply_external_functions": "dace_fortran.external",
66
+ "ExternalSignature": "dace_fortran.external",
67
+ "Arg": "dace_fortran.external",
68
+ "ArgKind": "dace_fortran.external",
69
+ "CAbi": "dace_fortran.external",
70
+ "Intent": "dace_fortran.external",
71
+ "clear_external_registry": "dace_fortran.external",
72
+ # Distinct from the internal ExternalCall libnode / ExternalSignature ABI record -- no name conflict.
73
+ "ExternalFunction": "dace_fortran.external_functions",
74
+ # Lower-level / advanced.
75
+ "SDFGBuilder": "dace_fortran.builder",
76
+ "DEFAULT_PIPELINE": "dace_fortran.builder",
77
+ "MULTI_FILE_PIPELINE": "dace_fortran.builder",
78
+ "MergeEngine": "dace_fortran.preprocess",
79
+ "preprocess_fortran_source": "dace_fortran.preprocess",
80
+ "merge_used_modules": "dace_fortran.preprocess",
81
+ # fparser-based single-TU inliner (opt-in alternative to the regex merge_used_modules splicer).
82
+ "inline_to_single_tu": "dace_fortran.fparser_inliner",
83
+ "inline_to_ast": "dace_fortran.fparser_inliner",
84
+ "preprocess_fortran": "dace_fortran.preprocess",
85
+ "rewrite_integer_powers": "dace_fortran.preprocess",
86
+ "normalize_kind_parameters": "dace_fortran.preprocess",
87
+ "replace_external_with_modules": "dace_fortran.preprocess",
88
+ "rewrite_string_enum_to_integer": "dace_fortran.preprocess",
89
+ # Real-world-codebase helpers (ICON / IFS / ECRAD etc.).
90
+ "prepare_flang_translation_unit": "dace_fortran.flang_codebase",
91
+ "emit_hlfir_from_codebase": "dace_fortran.flang_codebase",
92
+ "extract_make_compile_args": "dace_fortran.flang_codebase",
93
+ "vendor_netcdf_fortran": "dace_fortran.flang_codebase",
94
+ "mpi_stub_source": "dace_fortran.flang_codebase",
95
+ "find_openmpi_include": "dace_fortran.flang_codebase",
96
+ "LIBRARY_STUBS": "dace_fortran.flang_codebase",
97
+ "FLANG_BUG_PATCHES": "dace_fortran.flang_codebase",
98
+ # OpenACC data-residency pre-pass (reads the ORIGINAL source: the HLFIR path
99
+ # strips !$ACC before flang, so residency cannot come from the parse tree).
100
+ "extract_acc_residency": "dace_fortran.acc_residency",
101
+ "write_acc_residency_sidecar": "dace_fortran.acc_residency",
102
+ }
103
+
104
+ __all__ = [
105
+ "DEFAULT_PIPELINE",
106
+ "FLANG_BUG_PATCHES",
107
+ "LIBRARY_STUBS",
108
+ "MULTI_FILE_PIPELINE",
109
+ "Arg",
110
+ "ArgKind",
111
+ "CAbi",
112
+ "ExternalFunction",
113
+ "ExternalSignature",
114
+ "Intent",
115
+ "MergeEngine",
116
+ "SDFGBuilder",
117
+ "apply_external_functions",
118
+ "build_sdfg",
119
+ "build_sdfg_from_files",
120
+ "build_sdfg_from_hlfir",
121
+ "build_sdfg_from_project",
122
+ "clear_external_registry",
123
+ "emit_hlfir_from_codebase",
124
+ "extract_acc_residency",
125
+ "extract_make_compile_args",
126
+ "find_openmpi_include",
127
+ "inline_to_ast",
128
+ "inline_to_single_tu",
129
+ "keep_external",
130
+ "merge_used_modules",
131
+ "mpi_stub_source",
132
+ "normalize_kind_parameters",
133
+ "prepare_flang_translation_unit",
134
+ "preprocess_fortran",
135
+ "preprocess_fortran_source",
136
+ "register_external",
137
+ "replace_external_with_modules",
138
+ "rewrite_integer_powers",
139
+ "rewrite_string_enum_to_integer",
140
+ "vendor_netcdf_fortran",
141
+ "write_acc_residency_sidecar",
142
+ ]
143
+
144
+ # Static ``__all__`` for type checkers; it must name exactly the lazily-exported attributes.
145
+ assert set(__all__) == set(_LAZY), set(__all__) ^ set(_LAZY)
146
+
147
+
148
+ def __getattr__(name: str) -> Any:
149
+ """PEP 562 lazy attribute access -- defers importing the builder (and its C++-bridge build) until first use."""
150
+ target = _LAZY.get(name)
151
+ if target is None:
152
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
153
+ import importlib
154
+
155
+ value = getattr(importlib.import_module(target), name)
156
+ globals()[name] = value # cache so __getattr__ runs once per name
157
+ return value
158
+
159
+
160
+ def __dir__() -> list[str]:
161
+ return sorted(__all__)