[Openmp-commits] [clang] [flang] [llvm] [openmp] [Flang][OpenMP] Move builtin .mod generation into runtimes (PR #137828)

Michael Kruse via Openmp-commits openmp-commits at lists.llvm.org
Tue Apr 29 08:47:47 PDT 2025


https://github.com/Meinersbur created https://github.com/llvm/llvm-project/pull/137828

Experiments for per-target builtin modules

>From 68b09d943c78082e48728952dbef423735b96d99 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Thu, 5 Dec 2024 02:38:51 +0100
Subject: [PATCH 01/13] Split FortranSemantics.a

---
 flang/lib/Semantics/CMakeLists.txt | 65 ++++++++++++++++++++----------
 1 file changed, 43 insertions(+), 22 deletions(-)

diff --git a/flang/lib/Semantics/CMakeLists.txt b/flang/lib/Semantics/CMakeLists.txt
index 93bf0c7c5facd..02eb07e1c97f5 100644
--- a/flang/lib/Semantics/CMakeLists.txt
+++ b/flang/lib/Semantics/CMakeLists.txt
@@ -1,31 +1,10 @@
-add_flang_library(FortranSemantics
+add_flang_library(FortranSemantics PARTIAL_SOURCES_INTENDED
   assignment.cpp
   attr.cpp
   canonicalize-acc.cpp
   canonicalize-directives.cpp
   canonicalize-do.cpp
   canonicalize-omp.cpp
-  check-acc-structure.cpp
-  check-allocate.cpp
-  check-arithmeticif.cpp
-  check-call.cpp
-  check-case.cpp
-  check-coarray.cpp
-  check-cuda.cpp
-  check-data.cpp
-  check-deallocate.cpp
-  check-declarations.cpp
-  check-do-forall.cpp
-  check-if-stmt.cpp
-  check-io.cpp
-  check-namelist.cpp
-  check-nullify.cpp
-  check-omp-structure.cpp
-  check-purity.cpp
-  check-return.cpp
-  check-select-rank.cpp
-  check-select-type.cpp
-  check-stop.cpp
   compute-offsets.cpp
   data-to-inits.cpp
   definable.cpp
@@ -64,3 +43,45 @@ add_flang_library(FortranSemantics
   FrontendOpenACC
   TargetParser
 )
+
+
+add_flang_library(FortranSemanticsCheck PARTIAL_SOURCES_INTENDED
+  check-acc-structure.cpp
+  check-allocate.cpp
+  check-arithmeticif.cpp
+  check-call.cpp
+  check-case.cpp
+  check-coarray.cpp
+  check-cuda.cpp
+  check-data.cpp
+  check-deallocate.cpp
+  check-declarations.cpp
+  check-do-forall.cpp
+  check-if-stmt.cpp
+  check-io.cpp
+  check-namelist.cpp
+  check-nullify.cpp
+  check-omp-structure.cpp
+  check-purity.cpp
+  check-return.cpp
+  check-select-rank.cpp
+  check-select-type.cpp
+  check-stop.cpp
+
+  DEPENDS
+  acc_gen
+  omp_gen
+
+  LINK_LIBS
+  FortranCommon
+  FortranParser
+  FortranEvaluate
+
+  LINK_COMPONENTS
+  Support
+  FrontendOpenMP
+  FrontendOpenACC
+  TargetParser
+)
+
+target_link_libraries(FortranSemantics PUBLIC FortranSemanticsCheck)

>From 3c554c7b8825dcb174710a17cd6f3aa9b7acc94f Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Sat, 15 Mar 2025 13:39:54 +0100
Subject: [PATCH 02/13] Do not emit numeric_storage_size into object file

---
 flang/lib/Lower/Bridge.cpp | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)

diff --git a/flang/lib/Lower/Bridge.cpp b/flang/lib/Lower/Bridge.cpp
index 93f54d88a029d..4bee79095af5a 100644
--- a/flang/lib/Lower/Bridge.cpp
+++ b/flang/lib/Lower/Bridge.cpp
@@ -5933,12 +5933,25 @@ class FirConverter : public Fortran::lower::AbstractConverter {
     createGlobalOutsideOfFunctionLowering([&]() {
       auto &scopeVariableListMap =
           Fortran::lower::pft::getScopeVariableListMap(mod);
-      for (const auto &var : Fortran::lower::pft::getScopeVariableList(
-               mod.getScope(), scopeVariableListMap)) {
+      for (const auto &var : Fortran::lower::pft::getScopeVariableList(mod.getScope(), scopeVariableListMap)) {
+       
         // Only define the variables owned by this module.
         const Fortran::semantics::Scope *owningScope = var.getOwningScope();
-        if (!owningScope || mod.getScope() == *owningScope)
-          Fortran::lower::defineModuleVariable(*this, var);
+        if (owningScope && mod.getScope() != *owningScope)
+          continue ;
+
+
+
+      // Very special case: The value of numeric_storage_size depends on compilation options and therefore its value is not yet known when building the builtins runtime. Instead, the parameter is folding a __numeric_storage_size() expression which is loaded into the user program. For the runtime object file, omit the symbols as it is never used.
+     if (var.hasSymbol())  {
+        const Fortran::semantics::Symbol &sym = var.getSymbol(); 
+         const Fortran::semantics::Scope &owner = sym.owner();
+        if (sym.name() == "numeric_storage_size" && owner.IsModule()  &&    DEREF(owner.symbol()).name() == "iso_fortran_env")
+          continue ;
+        }
+
+
+        Fortran::lower::defineModuleVariable(*this, var); 
       }
       for (auto &eval : mod.evaluationList)
         genFIR(eval);

>From 3e6f5e91661be2848df8269de44b722e813508f4 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Sat, 15 Mar 2025 15:46:48 +0100
Subject: [PATCH 03/13] Flang build-mod dev edition

---
 flang-rt/cmake/modules/AddFlangRT.cmake | 14 +++++++-------
 flang-rt/lib/runtime/CMakeLists.txt     |  6 ++++++
 flang/lib/Semantics/CMakeLists.txt      |  2 --
 llvm/include/llvm/ADT/SmallVector.h     |  2 +-
 4 files changed, 14 insertions(+), 10 deletions(-)

diff --git a/flang-rt/cmake/modules/AddFlangRT.cmake b/flang-rt/cmake/modules/AddFlangRT.cmake
index 999128fcd55f0..41c8240172ff1 100644
--- a/flang-rt/cmake/modules/AddFlangRT.cmake
+++ b/flang-rt/cmake/modules/AddFlangRT.cmake
@@ -241,8 +241,8 @@ function (add_flangrt_library name)
     target_include_directories(${tgtname} PUBLIC "${FLANG_RT_SOURCE_DIR}/include")
 
     # For ISO_Fortran_binding.h to be found by the runtime itself (Accessed as #include "flang/ISO_Fortran_binding.h")
-      # User applications can use #include <ISO_Fortran_binding.h>
-  target_include_directories(${tgtname} PUBLIC "${FLANG_SOURCE_DIR}/include")
+    # User applications can use #include <ISO_Fortran_binding.h>
+    target_include_directories(${tgtname} PUBLIC "${FLANG_SOURCE_DIR}/include")
 
     # For Flang-RT's configured config.h to be found
     target_include_directories(${tgtname} PRIVATE "${FLANG_RT_BINARY_DIR}")
@@ -250,15 +250,15 @@ function (add_flangrt_library name)
     # Disable libstdc++/libc++ assertions, even in an LLVM_ENABLE_ASSERTIONS
     # build, to avoid an unwanted dependency on libstdc++/libc++.so.
     if (FLANG_RT_SUPPORTS_UNDEFINE_FLAG)
-      target_compile_options(${tgtname} PUBLIC -U_GLIBCXX_ASSERTIONS)
-      target_compile_options(${tgtname} PUBLIC -U_LIBCPP_ENABLE_ASSERTIONS)
+      target_compile_options(${tgtname} PUBLIC $<$<COMPILE_LANGUAGE:C,CXX>:-U_GLIBCXX_ASSERTIONS>)
+      target_compile_options(${tgtname} PUBLIC $<$<COMPILE_LANGUAGE:C,CXX>:-U_LIBCPP_ENABLE_ASSERTIONS>)
     endif ()
 
     # When building the flang runtime if LTO is enabled the archive file
     # contains LLVM IR rather than object code. Currently flang is not
     # LTO aware so cannot link this file to compiled Fortran code.
     if (FLANG_RT_HAS_FNO_LTO_FLAG)
-      target_compile_options(${tgtname} PRIVATE -fno-lto)
+      #target_compile_options(${tgtname} PRIVATE -fno-lto)
     endif ()
 
     # Flang/Clang (including clang-cl) -compiled programs targeting the MSVC ABI
@@ -268,12 +268,12 @@ function (add_flangrt_library name)
     # dependency to Compiler-RT's builtin library where these are implemented.
     if (MSVC AND CMAKE_CXX_COMPILER_ID MATCHES "Clang")
       if (FLANG_RT_BUILTINS_LIBRARY)
-      target_compile_options(${tgtname} PRIVATE "$<$<COMPILE_LANGUAGE:CXX,C>:-Xclang>" "$<$<COMPILE_LANGUAGE:CXX,C>:--dependent-lib=${FLANG_RT_BUILTINS_LIBRARY}>")
+      #target_compile_options(${tgtname} PRIVATE "$<$<COMPILE_LANGUAGE:CXX,C>:-Xclang>" "$<$<COMPILE_LANGUAGE:CXX,C>:--dependent-lib=${FLANG_RT_BUILTINS_LIBRARY}>")
       endif ()
     endif ()
     if (MSVC AND CMAKE_Fortran_COMPILER_ID STREQUAL "LLVMFlang")
       if (FLANG_RT_BUILTINS_LIBRARY)
-      target_compile_options(${tgtname} PRIVATE "$<$<COMPILE_LANGUAGE:Fortran>:-Xflang>" "$<$<COMPILE_LANGUAGE:Fortran>:--dependent-lib=${FLANG_RT_BUILTINS_LIBRARY}>")
+      #target_compile_options(${tgtname} PRIVATE "$<$<COMPILE_LANGUAGE:Fortran>:-Xflang>" "$<$<COMPILE_LANGUAGE:Fortran>:--dependent-lib=${FLANG_RT_BUILTINS_LIBRARY}>")
       else ()
         message(WARNING "Did not find libclang_rt.builtins.lib.
           LLVM may emit builtins that are not implemented in msvcrt/ucrt and
diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index c07348ea78c9f..2d226cce2f7c1 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -72,6 +72,8 @@ set(supported_sources
 # List of source not used for GPU offloading.
 set(host_sources
   ${FLANG_SOURCE_DIR}/module/iso_fortran_env_impl.f90
+  ${FLANG_SOURCE_DIR}/module/iso_fortran_env.f90
+  ${FLANG_SOURCE_DIR}/module/__fortran_builtins.f90
   command.cpp
   complex-powi.cpp
   complex-reduction.c
@@ -88,6 +90,10 @@ set(host_sources
   unit-map.cpp
 )
 
+add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
+set(CMAKE_Fortran_PREPROCESS FALSE)
+#add_compile_options(-mllvm -ignore-missing-type-desc)
+
 file(GLOB_RECURSE public_headers
   "${FLANG_RT_SOURCE_DIR}/include/flang_rt/*.h"
   "${FLANG_SOURCE_DIR}/include/flang/Common/*.h"
diff --git a/flang/lib/Semantics/CMakeLists.txt b/flang/lib/Semantics/CMakeLists.txt
index 02eb07e1c97f5..bd21b521fe20f 100644
--- a/flang/lib/Semantics/CMakeLists.txt
+++ b/flang/lib/Semantics/CMakeLists.txt
@@ -33,7 +33,6 @@ add_flang_library(FortranSemantics PARTIAL_SOURCES_INTENDED
   omp_gen
 
   LINK_LIBS
-  FortranSupport
   FortranParser
   FortranEvaluate
 
@@ -73,7 +72,6 @@ add_flang_library(FortranSemanticsCheck PARTIAL_SOURCES_INTENDED
   omp_gen
 
   LINK_LIBS
-  FortranCommon
   FortranParser
   FortranEvaluate
 
diff --git a/llvm/include/llvm/ADT/SmallVector.h b/llvm/include/llvm/ADT/SmallVector.h
index bd3e887e36bce..069216556b860 100644
--- a/llvm/include/llvm/ADT/SmallVector.h
+++ b/llvm/include/llvm/ADT/SmallVector.h
@@ -1159,7 +1159,7 @@ template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
   // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
   // 64-bit host, is expected to be very rare.
   static_assert(
-      sizeof(T) <= 256,
+      sizeof(T) <= 512,
       "You are trying to use a default number of inlined elements for "
       "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
       "explicit number of inlined elements with `SmallVector<T, N>` to make "

>From f69551048b0aa33205f79bceebc6351c24111c68 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Mon, 17 Mar 2025 15:15:58 +0100
Subject: [PATCH 04/13] WIP: Cmake for .mod files

---
 flang-rt/CMakeLists.txt                       |  12 ++
 flang-rt/lib/runtime/CMakeLists.txt           |  26 ++-
 .../lib/runtime}/__cuda_builtins.f90          |   0
 .../lib/runtime}/__cuda_device.f90            |   0
 .../lib/runtime}/__fortran_builtins.f90       |   0
 .../runtime}/__fortran_ieee_exceptions.f90    |   0
 .../lib/runtime}/__fortran_type_info.f90      |   0
 .../lib/runtime}/__ppc_intrinsics.f90         |  75 ++++++--
 .../lib/runtime}/__ppc_types.f90              |   0
 .../lib/runtime}/cudadevice.f90               |   0
 .../lib/runtime}/ieee_arithmetic.f90          |   0
 .../lib/runtime}/ieee_exceptions.f90          |   0
 .../lib/runtime}/ieee_features.f90            |   0
 .../lib/runtime}/iso_c_binding.f90            |   0
 .../lib/runtime}/iso_fortran_env.f90          |   0
 .../lib/runtime}/iso_fortran_env_impl.f90     |   0
 .../module => flang-rt/lib/runtime}/mma.f90   |   0
 flang/CMakeLists.txt                          |   8 +
 flang/cmake/modules/FlangCommon.cmake         |   7 -
 flang/lib/Semantics/CMakeLists.txt            |   1 +
 flang/module/.clang-format                    |   1 -
 flang/test/CMakeLists.txt                     |   1 -
 flang/tools/CMakeLists.txt                    |   1 -
 flang/tools/f18/CMakeLists.txt                | 181 ------------------
 flang/tools/f18/dump.cpp                      |  42 ----
 llvm/runtimes/CMakeLists.txt                  |   2 +-
 26 files changed, 102 insertions(+), 255 deletions(-)
 rename {flang/module => flang-rt/lib/runtime}/__cuda_builtins.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/__cuda_device.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/__fortran_builtins.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/__fortran_ieee_exceptions.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/__fortran_type_info.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/__ppc_intrinsics.f90 (98%)
 rename {flang/module => flang-rt/lib/runtime}/__ppc_types.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/cudadevice.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/ieee_arithmetic.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/ieee_exceptions.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/ieee_features.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/iso_c_binding.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/iso_fortran_env.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/iso_fortran_env_impl.f90 (100%)
 rename {flang/module => flang-rt/lib/runtime}/mma.f90 (100%)
 delete mode 100644 flang/module/.clang-format
 delete mode 100644 flang/tools/f18/CMakeLists.txt
 delete mode 100644 flang/tools/f18/dump.cpp

diff --git a/flang-rt/CMakeLists.txt b/flang-rt/CMakeLists.txt
index a0b998dc3abd9..b10398a5ea897 100644
--- a/flang-rt/CMakeLists.txt
+++ b/flang-rt/CMakeLists.txt
@@ -299,6 +299,18 @@ elseif (FLANG_RT_GCC_RESOURCE_DIR)
   endif ()
 endif ()
 
+
+
+if (CMAKE_C_BYTE_ORDER STREQUAL "BIG_ENDIAN")
+  add_compile_definitions(FLANG_BIG_ENDIAN=1)
+elseif (CMAKE_C_BYTE_ORDER STREQUAL "LITTLE_ENDIAN")
+  add_compile_definitions(FLANG_LITTLE_ENDIAN=1)
+else ()
+  #message(SEND_ERROR "Cannot determine endian '${CMAKE_C_BYTE_ORDER}' '${CMAKE_CXX_BYTE_ORDER}'")
+endif ()
+
+
+
 #####################
 # Build Preparation #
 #####################
diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index 2d226cce2f7c1..ae1260b290a38 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -71,9 +71,21 @@ set(supported_sources
 
 # List of source not used for GPU offloading.
 set(host_sources
-  ${FLANG_SOURCE_DIR}/module/iso_fortran_env_impl.f90
-  ${FLANG_SOURCE_DIR}/module/iso_fortran_env.f90
-  ${FLANG_SOURCE_DIR}/module/__fortran_builtins.f90
+  __cuda_builtins.f90
+  __cuda_device.f90
+  __fortran_builtins.f90
+  __fortran_ieee_exceptions.f90
+  __fortran_type_info.f90
+  __ppc_types.f90
+  cudadevice.f90
+  ieee_arithmetic.f90
+  ieee_exceptions.f90
+  ieee_features.f90
+  iso_c_binding.f90
+  iso_fortran_env_impl.f90
+  iso_fortran_env.f90
+  mma.f90
+
   command.cpp
   complex-powi.cpp
   complex-reduction.c
@@ -90,6 +102,14 @@ set(host_sources
   unit-map.cpp
 )
 
+message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
+message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
+if  (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
+  list(APPEND host_source
+    __ppc_intrinsics.f90
+  )
+endif ()
+
 add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
 set(CMAKE_Fortran_PREPROCESS FALSE)
 #add_compile_options(-mllvm -ignore-missing-type-desc)
diff --git a/flang/module/__cuda_builtins.f90 b/flang-rt/lib/runtime/__cuda_builtins.f90
similarity index 100%
rename from flang/module/__cuda_builtins.f90
rename to flang-rt/lib/runtime/__cuda_builtins.f90
diff --git a/flang/module/__cuda_device.f90 b/flang-rt/lib/runtime/__cuda_device.f90
similarity index 100%
rename from flang/module/__cuda_device.f90
rename to flang-rt/lib/runtime/__cuda_device.f90
diff --git a/flang/module/__fortran_builtins.f90 b/flang-rt/lib/runtime/__fortran_builtins.f90
similarity index 100%
rename from flang/module/__fortran_builtins.f90
rename to flang-rt/lib/runtime/__fortran_builtins.f90
diff --git a/flang/module/__fortran_ieee_exceptions.f90 b/flang-rt/lib/runtime/__fortran_ieee_exceptions.f90
similarity index 100%
rename from flang/module/__fortran_ieee_exceptions.f90
rename to flang-rt/lib/runtime/__fortran_ieee_exceptions.f90
diff --git a/flang/module/__fortran_type_info.f90 b/flang-rt/lib/runtime/__fortran_type_info.f90
similarity index 100%
rename from flang/module/__fortran_type_info.f90
rename to flang-rt/lib/runtime/__fortran_type_info.f90
diff --git a/flang/module/__ppc_intrinsics.f90 b/flang-rt/lib/runtime/__ppc_intrinsics.f90
similarity index 98%
rename from flang/module/__ppc_intrinsics.f90
rename to flang-rt/lib/runtime/__ppc_intrinsics.f90
index b3ff33b0619ff..1ec134261c2ed 100644
--- a/flang/module/__ppc_intrinsics.f90
+++ b/flang-rt/lib/runtime/__ppc_intrinsics.f90
@@ -55,13 +55,24 @@ elemental vector(real(VKIND)) function elem_func_vr##VKIND##r##VKIND(arg1); \
     real(VKIND), intent(in) :: arg1; \
   end function ;
 
-  ELEM_FUNC_VIVI(1) ELEM_FUNC_VIVI(2) ELEM_FUNC_VIVI(4) ELEM_FUNC_VIVI(8)
+  ELEM_FUNC_VIVI(1)
+  ELEM_FUNC_VIVI(2)
+  ELEM_FUNC_VIVI(4)
+  ELEM_FUNC_VIVI(8)
   ELEM_FUNC_VUVU(1)
-  ELEM_FUNC_VRVR_2(4,8) ELEM_FUNC_VRVR_2(8,4)
-  ELEM_FUNC_VRVR(4) ELEM_FUNC_VRVR(8)
-  ELEM_FUNC_VII_2(4,1) ELEM_FUNC_VII_2(4,2) ELEM_FUNC_VII_2(4,8)
-  ELEM_FUNC_VII(1) ELEM_FUNC_VII(2) ELEM_FUNC_VII(4) ELEM_FUNC_VII(8)
-  ELEM_FUNC_VRR(4) ELEM_FUNC_VRR(8)
+  ELEM_FUNC_VRVR_2(4,8)
+  ELEM_FUNC_VRVR_2(8,4)
+  ELEM_FUNC_VRVR(4)
+  ELEM_FUNC_VRVR(8)
+  ELEM_FUNC_VII_2(4,1)
+  ELEM_FUNC_VII_2(4,2)
+  ELEM_FUNC_VII_2(4,8)
+  ELEM_FUNC_VII(1)
+  ELEM_FUNC_VII(2)
+  ELEM_FUNC_VII(4)
+  ELEM_FUNC_VII(8)
+  ELEM_FUNC_VRR(4)
+  ELEM_FUNC_VRR(8)
 
 #undef ELEM_FUNC_VRR
 #undef ELEM_FUNC_VII
@@ -322,9 +333,16 @@ pure vector(real(VKIND)) function func_vec_convert_vr##VKIND##vi##vr##VKIND(v, m
     !dir$ ignore_tkr(r) mold; \
   end function ;
 
-  FUNC_VEC_CONVERT_VIVIVI(1) FUNC_VEC_CONVERT_VIVIVI(2) FUNC_VEC_CONVERT_VIVIVI(4) FUNC_VEC_CONVERT_VIVIVI(8)
-  FUNC_VEC_CONVERT_VUVIVU(1) FUNC_VEC_CONVERT_VUVIVU(2) FUNC_VEC_CONVERT_VUVIVU(4) FUNC_VEC_CONVERT_VUVIVU(8)
-  FUNC_VEC_CONVERT_VRVIVR(4) FUNC_VEC_CONVERT_VRVIVR(8)
+  FUNC_VEC_CONVERT_VIVIVI(1)
+  FUNC_VEC_CONVERT_VIVIVI(2)
+  FUNC_VEC_CONVERT_VIVIVI(4)
+  FUNC_VEC_CONVERT_VIVIVI(8)
+  FUNC_VEC_CONVERT_VUVIVU(1)
+  FUNC_VEC_CONVERT_VUVIVU(2)
+  FUNC_VEC_CONVERT_VUVIVU(4)
+  FUNC_VEC_CONVERT_VUVIVU(8)
+  FUNC_VEC_CONVERT_VRVIVR(4)
+  FUNC_VEC_CONVERT_VRVIVR(8)
   ELEM_FUNC_IVII(1) ELEM_FUNC_IVII(2) ELEM_FUNC_IVII(4) ELEM_FUNC_IVII(8)
   ELEM_FUNC_RVRI(4) ELEM_FUNC_RVRI(8)
   ELEM_FUNC_VIVIVI(1) ELEM_FUNC_VIVIVI(2) ELEM_FUNC_VIVIVI(4) ELEM_FUNC_VIVIVI(8)
@@ -611,15 +629,36 @@ pure subroutine sub_vpi0r0(arg1, arg2, arg3)
     !dir$ ignore_tkr(kr) arg3
   end subroutine
 
-  SUB_VIIVI(1) SUB_VIIVI(2) SUB_VIIVI(4) SUB_VIIVI(8)
-  SUB_VUIVU(1) SUB_VUIVU(2) SUB_VUIVU(4) SUB_VUIVU(8)
-  SUB_VRIVR(4) SUB_VRIVR(8)
-  SUB_VIII(1) SUB_VIII(2) SUB_VIII(4) SUB_VIII(8)
-  SUB_VUII(1) SUB_VUII(2) SUB_VUII(4) SUB_VUII(8)
-  SUB_VRIR(4) SUB_VRIR(8)
-  SUB_VPI0VI(1) SUB_VPI0VI(2) SUB_VPI0VI(4) SUB_VPI0VI(8)
-  SUB_VPI0VU(1) SUB_VPI0VU(2) SUB_VPI0VU(4) SUB_VPI0VU(8)
-  SUB_VPI0VR(4) SUB_VPI0VR(8)
+  SUB_VIIVI(1)
+  SUB_VIIVI(2)
+  SUB_VIIVI(4)
+  SUB_VIIVI(8)
+  SUB_VUIVU(1)
+  SUB_VUIVU(2)
+  SUB_VUIVU(4)
+  SUB_VUIVU(8)
+  SUB_VRIVR(4)
+  SUB_VRIVR(8)
+  SUB_VIII(1)
+  SUB_VIII(2)
+  SUB_VIII(4)
+  SUB_VIII(8)
+  SUB_VUII(1)
+  SUB_VUII(2)
+  SUB_VUII(4)
+  SUB_VUII(8)
+  SUB_VRIR(4)
+  SUB_VRIR(8)
+  SUB_VPI0VI(1)
+  SUB_VPI0VI(2)
+  SUB_VPI0VI(4)
+  SUB_VPI0VI(8)
+  SUB_VPI0VU(1)
+  SUB_VPI0VU(2)
+  SUB_VPI0VU(4)
+  SUB_VPI0VU(8)
+  SUB_VPI0VR(4)
+  SUB_VPI0VR(8)
 
 #undef SUB_VPI0VR
 #undef SUB_VPI0VU
diff --git a/flang/module/__ppc_types.f90 b/flang-rt/lib/runtime/__ppc_types.f90
similarity index 100%
rename from flang/module/__ppc_types.f90
rename to flang-rt/lib/runtime/__ppc_types.f90
diff --git a/flang/module/cudadevice.f90 b/flang-rt/lib/runtime/cudadevice.f90
similarity index 100%
rename from flang/module/cudadevice.f90
rename to flang-rt/lib/runtime/cudadevice.f90
diff --git a/flang/module/ieee_arithmetic.f90 b/flang-rt/lib/runtime/ieee_arithmetic.f90
similarity index 100%
rename from flang/module/ieee_arithmetic.f90
rename to flang-rt/lib/runtime/ieee_arithmetic.f90
diff --git a/flang/module/ieee_exceptions.f90 b/flang-rt/lib/runtime/ieee_exceptions.f90
similarity index 100%
rename from flang/module/ieee_exceptions.f90
rename to flang-rt/lib/runtime/ieee_exceptions.f90
diff --git a/flang/module/ieee_features.f90 b/flang-rt/lib/runtime/ieee_features.f90
similarity index 100%
rename from flang/module/ieee_features.f90
rename to flang-rt/lib/runtime/ieee_features.f90
diff --git a/flang/module/iso_c_binding.f90 b/flang-rt/lib/runtime/iso_c_binding.f90
similarity index 100%
rename from flang/module/iso_c_binding.f90
rename to flang-rt/lib/runtime/iso_c_binding.f90
diff --git a/flang/module/iso_fortran_env.f90 b/flang-rt/lib/runtime/iso_fortran_env.f90
similarity index 100%
rename from flang/module/iso_fortran_env.f90
rename to flang-rt/lib/runtime/iso_fortran_env.f90
diff --git a/flang/module/iso_fortran_env_impl.f90 b/flang-rt/lib/runtime/iso_fortran_env_impl.f90
similarity index 100%
rename from flang/module/iso_fortran_env_impl.f90
rename to flang-rt/lib/runtime/iso_fortran_env_impl.f90
diff --git a/flang/module/mma.f90 b/flang-rt/lib/runtime/mma.f90
similarity index 100%
rename from flang/module/mma.f90
rename to flang-rt/lib/runtime/mma.f90
diff --git a/flang/CMakeLists.txt b/flang/CMakeLists.txt
index 4b703b456cae2..5702f74bd3e81 100644
--- a/flang/CMakeLists.txt
+++ b/flang/CMakeLists.txt
@@ -481,6 +481,14 @@ endif()
 include(AddFlang)
 include(FlangCommon)
 
+include(TestBigEndian)
+test_big_endian(IS_BIGENDIAN)
+if (IS_BIGENDIAN)
+  add_compile_definitions(FLANG_BIG_ENDIAN=1)
+else ()
+  add_compile_definitions(FLANG_LITTLE_ENDIAN=1)
+endif ()
+
 if (FLANG_INCLUDE_TESTS)
   add_compile_definitions(FLANG_INCLUDE_TESTS=1)
 endif()
diff --git a/flang/cmake/modules/FlangCommon.cmake b/flang/cmake/modules/FlangCommon.cmake
index bb2a76cb19453..0069685c599f3 100644
--- a/flang/cmake/modules/FlangCommon.cmake
+++ b/flang/cmake/modules/FlangCommon.cmake
@@ -38,10 +38,3 @@ check_c_source_compiles(
   "
   HAVE_LDBL_MANT_DIG_113)
 
-include(TestBigEndian)
-test_big_endian(IS_BIGENDIAN)
-if (IS_BIGENDIAN)
-  add_compile_definitions(FLANG_BIG_ENDIAN=1)
-else ()
-  add_compile_definitions(FLANG_LITTLE_ENDIAN=1)
-endif ()
diff --git a/flang/lib/Semantics/CMakeLists.txt b/flang/lib/Semantics/CMakeLists.txt
index bd21b521fe20f..70d220e05dd42 100644
--- a/flang/lib/Semantics/CMakeLists.txt
+++ b/flang/lib/Semantics/CMakeLists.txt
@@ -74,6 +74,7 @@ add_flang_library(FortranSemanticsCheck PARTIAL_SOURCES_INTENDED
   LINK_LIBS
   FortranParser
   FortranEvaluate
+  FortranSemantics
 
   LINK_COMPONENTS
   Support
diff --git a/flang/module/.clang-format b/flang/module/.clang-format
deleted file mode 100644
index e3845288a2aec..0000000000000
--- a/flang/module/.clang-format
+++ /dev/null
@@ -1 +0,0 @@
-DisableFormat: true
diff --git a/flang/test/CMakeLists.txt b/flang/test/CMakeLists.txt
index 17a7f58902dca..512372570995d 100644
--- a/flang/test/CMakeLists.txt
+++ b/flang/test/CMakeLists.txt
@@ -59,7 +59,6 @@ set(FLANG_TEST_PARAMS
 
 set(FLANG_TEST_DEPENDS
   flang
-  module_files
   fir-opt
   tco
   bbc
diff --git a/flang/tools/CMakeLists.txt b/flang/tools/CMakeLists.txt
index 1d2d2c608faf9..1b297af74cae7 100644
--- a/flang/tools/CMakeLists.txt
+++ b/flang/tools/CMakeLists.txt
@@ -7,7 +7,6 @@
 #===------------------------------------------------------------------------===#
 
 add_subdirectory(bbc)
-add_subdirectory(f18)
 add_subdirectory(flang-driver)
 add_subdirectory(tco)
 add_subdirectory(f18-parse-demo)
diff --git a/flang/tools/f18/CMakeLists.txt b/flang/tools/f18/CMakeLists.txt
deleted file mode 100644
index a66c8e36b3326..0000000000000
--- a/flang/tools/f18/CMakeLists.txt
+++ /dev/null
@@ -1,181 +0,0 @@
-set(LLVM_LINK_COMPONENTS
-  FrontendOpenACC
-  FrontendOpenMP
-  Support
-  )
-
-# Define the list of Fortran module files that need to be compiled
-# to produce an object file for inclusion into the flang_rt.runtime
-# library.
-set(MODULES_WITH_IMPLEMENTATION
-  "iso_fortran_env_impl"
-)
-
-# Define the list of Fortran module files for which it is
-# sufficient to generate the module file via -fsyntax-only.
-set(MODULES_WITHOUT_IMPLEMENTATION
-  "__fortran_builtins"
-  "__fortran_ieee_exceptions"
-  "__fortran_type_info"
-  "__ppc_types"
-  "__ppc_intrinsics"
-  "mma"
-  "__cuda_builtins"
-  "__cuda_device"
-  "cudadevice"
-  "ieee_arithmetic"
-  "ieee_exceptions"
-  "ieee_features"
-  "iso_c_binding"
-  "iso_fortran_env"
-)
-
-set(MODULES ${MODULES_WITH_IMPLEMENTATION} ${MODULES_WITHOUT_IMPLEMENTATION})
-
-# Check if 128-bit float computations can be done via long double.
-check_cxx_source_compiles(
-  "#include <cfloat>
-   #if LDBL_MANT_DIG != 113
-   #error LDBL_MANT_DIG != 113
-   #endif
-   int main() { return 0; }
-  "
-  HAVE_LDBL_MANT_DIG_113)
-
-# Figure out whether we can support REAL(KIND=16)
-if (FLANG_RUNTIME_F128_MATH_LIB)
-  set(FLANG_SUPPORT_R16 "1")
-elseif (HAVE_LDBL_MANT_DIG_113)
-  set(FLANG_SUPPORT_R16 "1")
-else()
-  set(FLANG_SUPPORT_R16 "0")
-endif()
-
-# Init variable to hold extra object files coming from the Fortran modules;
-# these module files will be contributed from the CMakeLists in flang/tools/f18.
-set(module_objects "")
-
-# Create module files directly from the top-level module source directory.
-# If CMAKE_CROSSCOMPILING, then the newly built flang executable was
-# cross compiled, and thus can't be executed on the build system and thus
-# can't be used for generating module files.
-if (NOT CMAKE_CROSSCOMPILING)
-  foreach(filename ${MODULES})
-    set(depends "")
-    set(opts "")
-    if(${filename} STREQUAL "__fortran_builtins" OR
-       ${filename} STREQUAL "__ppc_types")
-    elseif(${filename} STREQUAL "__ppc_intrinsics" OR
-           ${filename} STREQUAL "mma")
-      set(depends ${FLANG_INTRINSIC_MODULES_DIR}/__ppc_types.mod)
-    elseif(${filename} STREQUAL "__cuda_device")
-      set(opts -fc1 -xcuda)
-      set(depends ${FLANG_INTRINSIC_MODULES_DIR}/__cuda_builtins.mod)
-    elseif(${filename} STREQUAL "cudadevice")
-      set(opts -fc1 -xcuda)
-      set(depends ${FLANG_INTRINSIC_MODULES_DIR}/__cuda_device.mod)
-    else()
-      set(depends ${FLANG_INTRINSIC_MODULES_DIR}/__fortran_builtins.mod)
-      if(${filename} STREQUAL "iso_fortran_env")
-        set(depends ${depends} ${FLANG_INTRINSIC_MODULES_DIR}/iso_fortran_env_impl.mod)
-      endif()
-      if(${filename} STREQUAL "ieee_arithmetic" OR
-         ${filename} STREQUAL "ieee_exceptions")
-        set(depends ${depends} ${FLANG_INTRINSIC_MODULES_DIR}/__fortran_ieee_exceptions.mod)
-      endif()
-    endif()
-    if(NOT ${filename} STREQUAL "__fortran_type_info" AND NOT ${filename} STREQUAL "__fortran_builtins")
-      set(depends ${depends} ${FLANG_INTRINSIC_MODULES_DIR}/__fortran_type_info.mod)
-    endif()
-
-    # The module contains PPC vector types that needs the PPC target.
-    if(${filename} STREQUAL "__ppc_intrinsics" OR
-       ${filename} STREQUAL "mma")
-      if (PowerPC IN_LIST LLVM_TARGETS_TO_BUILD)
-        set(opts "--target=ppc64le")
-      else()
-        # Do not compile PPC module if the target is not available.
-        continue()
-      endif()
-    endif()
-
-    set(decls "")
-    if (FLANG_SUPPORT_R16)
-      set(decls "-DFLANG_SUPPORT_R16")
-    endif()
-
-    # Some modules have an implementation part that needs to be added to the
-    # flang_rt.runtime library.
-    set(compile_with "-fsyntax-only")
-    set(object_output "")
-    set(include_in_link FALSE)
-    if(${filename} IN_LIST MODULES_WITH_IMPLEMENTATION AND FLANG_INCLUDE_RUNTIME)
-      set(object_output "${CMAKE_CURRENT_BINARY_DIR}/${filename}${CMAKE_CXX_OUTPUT_EXTENSION}")
-      set(compile_with -c -o ${object_output})
-      set(include_in_link TRUE)
-    endif()
-
-    set(base ${FLANG_INTRINSIC_MODULES_DIR}/${filename})
-    # TODO: We may need to flag this with conditional, in case Flang is built w/o OpenMP support
-    add_custom_command(OUTPUT ${base}.mod ${object_output}
-      COMMAND ${CMAKE_COMMAND} -E make_directory ${FLANG_INTRINSIC_MODULES_DIR}
-      COMMAND flang ${opts} ${decls} -cpp ${compile_with} -module-dir ${FLANG_INTRINSIC_MODULES_DIR}
-        ${FLANG_SOURCE_DIR}/module/${filename}.f90
-      DEPENDS flang ${FLANG_SOURCE_DIR}/module/${filename}.f90 ${FLANG_SOURCE_DIR}/module/__fortran_builtins.f90 ${depends}
-    )
-    list(APPEND MODULE_FILES ${base}.mod)
-    install(FILES ${base}.mod DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/flang")
-
-    # If a module has been compiled into an object file, add the file to
-    # the link line for the flang_rt.runtime library.
-    if(include_in_link)
-      list(APPEND module_objects ${object_output})
-    endif()
-  endforeach()
-
-  # Set a CACHE variable that is visible to the CMakeLists.txt in runtime/, so that
-  # the compiled Fortran modules can be added to the link line of the flang_rt.runtime
-  # library.
-  set(FORTRAN_MODULE_OBJECTS ${module_objects} CACHE INTERNAL "" FORCE)
-
-  # Special case for omp_lib.mod, because its source comes from openmp/runtime/src/include.
-  # It also produces two module files: omp_lib.mod and omp_lib_kinds.mod.  Compile these
-  # files only if OpenMP support has been configured.
-  if (LLVM_TOOL_OPENMP_BUILD)
-    message(STATUS "OpenMP runtime support enabled via LLVM_ENABLE_PROJECTS, building omp_lib.mod")
-    set(base ${FLANG_INTRINSIC_MODULES_DIR}/omp_lib)
-    add_custom_command(OUTPUT ${base}.mod ${base}_kinds.mod
-      COMMAND ${CMAKE_COMMAND} -E make_directory ${FLANG_INTRINSIC_MODULES_DIR}
-      COMMAND flang -cpp -fsyntax-only ${opts} -module-dir ${FLANG_INTRINSIC_MODULES_DIR}
-        ${CMAKE_BINARY_DIR}/projects/openmp/runtime/src/omp_lib.F90
-      DEPENDS flang ${FLANG_INTRINSIC_MODULES_DIR}/iso_c_binding.mod ${CMAKE_BINARY_DIR}/projects/openmp/runtime/src/omp_lib.F90 ${depends}
-    )
-    add_custom_command(OUTPUT ${base}.f18.mod
-      DEPENDS ${base}.mod
-      COMMAND ${CMAKE_COMMAND} -E copy ${base}.mod ${base}.f18.mod)
-      add_custom_command(OUTPUT ${base}_kinds.f18.mod
-        DEPENDS ${base}.mod
-        COMMAND ${CMAKE_COMMAND} -E copy ${base}_kinds.mod ${base}_kinds.f18.mod)
-    list(APPEND MODULE_FILES ${base}.mod ${base}.f18.mod ${base}_kinds.mod ${base}_kinds.f18.mod)
-    install(FILES ${base}.mod ${base}.f18.mod ${base}_kinds.mod ${base}_kinds.f18.mod DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/flang")
-  elseif ("openmp" IN_LIST LLVM_ENABLE_RUNTIMES)
-    message(STATUS "OpenMP runtime support enabled via LLVM_ENABLE_RUNTIMES, assuming omp_lib.mod is built there")
-  else()
-    message(WARNING "Not building omp_lib.mod, no OpenMP runtime in either LLVM_ENABLE_PROJECTS or LLVM_ENABLE_RUNTIMES")
-  endif()
-endif()
-
-add_custom_target(module_files ALL DEPENDS ${MODULE_FILES})
-set_target_properties(module_files PROPERTIES FOLDER "Flang/Resources")
-
-# TODO Move this to a more suitable location
-# Copy the generated omp_lib.h header file, if OpenMP support has been configured.
-if (LLVM_TOOL_OPENMP_BUILD)
-  message(STATUS "OpenMP runtime support enabled via LLVM_ENABLE_PROJECTS, building omp_lib.h")
-  file(COPY ${CMAKE_BINARY_DIR}/projects/openmp/runtime/src/omp_lib.h DESTINATION "${CMAKE_BINARY_DIR}/include/flang/OpenMP/" FILE_PERMISSIONS OWNER_READ OWNER_WRITE)
-  install(FILES ${CMAKE_BINARY_DIR}/include/flang/OpenMP/omp_lib.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/flang/OpenMP")
-elseif ("openmp" IN_LIST LLVM_ENABLE_RUNTIMES)
-  message(STATUS "OpenMP runtime support enabled via LLVM_ENABLE_RUNTIMES, assuming omp_lib.h is built there")
-else()
-  message(STATUS "Not copying omp_lib.h, no OpenMP runtime in either LLVM_ENABLE_PROJECTS or LLVM_ENABLE_RUNTIMES")
-endif()
diff --git a/flang/tools/f18/dump.cpp b/flang/tools/f18/dump.cpp
deleted file mode 100644
index f11b5aedf4c6a..0000000000000
--- a/flang/tools/f18/dump.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-//===-- tools/f18/dump.cpp ------------------------------------------------===//
-//
-// 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
-//
-//===----------------------------------------------------------------------===//
-
-// This file defines Dump routines available for calling from the debugger.
-// Each is based on operator<< for that type. There are overloadings for
-// reference and pointer, and for dumping to a provided raw_ostream or errs().
-
-#ifdef DEBUGF18
-
-#include "llvm/Support/raw_ostream.h"
-
-#define DEFINE_DUMP(ns, name) \
-  namespace ns { \
-  class name; \
-  llvm::raw_ostream &operator<<(llvm::raw_ostream &, const name &); \
-  } \
-  void Dump(llvm::raw_ostream &os, const ns::name &x) { os << x << '\n'; } \
-  void Dump(llvm::raw_ostream &os, const ns::name *x) { \
-    if (x == nullptr) \
-      os << "null\n"; \
-    else \
-      Dump(os, *x); \
-  } \
-  void Dump(const ns::name &x) { Dump(llvm::errs(), x); } \
-  void Dump(const ns::name *x) { Dump(llvm::errs(), *x); }
-
-namespace Fortran {
-DEFINE_DUMP(parser, Name)
-DEFINE_DUMP(parser, CharBlock)
-DEFINE_DUMP(semantics, Symbol)
-DEFINE_DUMP(semantics, Scope)
-DEFINE_DUMP(semantics, IntrinsicTypeSpec)
-DEFINE_DUMP(semantics, DerivedTypeSpec)
-DEFINE_DUMP(semantics, DeclTypeSpec)
-} // namespace Fortran
-
-#endif
diff --git a/llvm/runtimes/CMakeLists.txt b/llvm/runtimes/CMakeLists.txt
index 136099dc48ab8..00ff669ffe415 100644
--- a/llvm/runtimes/CMakeLists.txt
+++ b/llvm/runtimes/CMakeLists.txt
@@ -524,7 +524,7 @@ if(build_runtimes)
       # built before "openmp" is built as a runtime project.  Besides "flang"
       # to build the compiler, we also need to add "module_files" to make sure
       # that all .mod files are also properly build.
-      list(APPEND extra_deps "flang" "module_files")
+      list(APPEND extra_deps "flang")
     endif()
     foreach(dep opt llvm-link llvm-extract clang clang-offload-packager)
       if(TARGET ${dep})

>From d7605533fd2027d68b50f8b0d2a830c27b102548 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Mon, 17 Mar 2025 22:53:49 +0100
Subject: [PATCH 05/13] Compiling all .mod files

---
 flang-rt/lib/runtime/CMakeLists.txt         | 14 +++-
 flang-rt/lib/runtime/__fortran_builtins.f90 |  2 +-
 flang-rt/lib/runtime/mma.f90                | 85 ++++++++++++++-------
 3 files changed, 69 insertions(+), 32 deletions(-)

diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index ae1260b290a38..08f8122f449ef 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -70,13 +70,13 @@ set(supported_sources
 )
 
 # List of source not used for GPU offloading.
+set(CMAKE_Fortran_MODULE_DIRECTORY "${LLVM_LIBRARY_OUTPUT_INTDIR}/../include/flang")
 set(host_sources
   __cuda_builtins.f90
   __cuda_device.f90
   __fortran_builtins.f90
   __fortran_ieee_exceptions.f90
   __fortran_type_info.f90
-  __ppc_types.f90
   cudadevice.f90
   ieee_arithmetic.f90
   ieee_exceptions.f90
@@ -84,7 +84,6 @@ set(host_sources
   iso_c_binding.f90
   iso_fortran_env_impl.f90
   iso_fortran_env.f90
-  mma.f90
 
   command.cpp
   complex-powi.cpp
@@ -102,16 +101,25 @@ set(host_sources
   unit-map.cpp
 )
 
+set_source_files_properties(cudadevice.f90
+  PROPERTIES COMPILE_OPTIONS "-xcuda"
+)
+set_source_files_properties(mma.f90
+  PROPERTIES Fortran_PREPROCESS OFF
+)
+
 message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
 message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
 if  (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
   list(APPEND host_source
+    __ppc_types.f90
     __ppc_intrinsics.f90
+    mma.f90
   )
 endif ()
 
 add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
-set(CMAKE_Fortran_PREPROCESS FALSE)
+#set(CMAKE_Fortran_PREPROCESS FALSE)
 #add_compile_options(-mllvm -ignore-missing-type-desc)
 
 file(GLOB_RECURSE public_headers
diff --git a/flang-rt/lib/runtime/__fortran_builtins.f90 b/flang-rt/lib/runtime/__fortran_builtins.f90
index 4d134fa4b62b1..7bb078c0b428e 100644
--- a/flang-rt/lib/runtime/__fortran_builtins.f90
+++ b/flang-rt/lib/runtime/__fortran_builtins.f90
@@ -6,7 +6,7 @@
 !
 !===------------------------------------------------------------------------===!
 
-#include '../include/flang/Runtime/magic-numbers.h'
+#include '../../../flang/include/flang/Runtime/magic-numbers.h'
 
 ! These naming shenanigans prevent names from Fortran intrinsic modules
 ! from being usable on INTRINSIC statements, and force the program
diff --git a/flang-rt/lib/runtime/mma.f90 b/flang-rt/lib/runtime/mma.f90
index 4c41822e000a3..2957d39c8e61f 100644
--- a/flang-rt/lib/runtime/mma.f90
+++ b/flang-rt/lib/runtime/mma.f90
@@ -55,9 +55,16 @@ pure __vector_pair function func_vpi0vp(arg1, arg2); \
     !dir$ ignore_tkr(r) arg2; \
   end function;
 
-  FUNC_VPI0VI(1) FUNC_VPI0VI(2) FUNC_VPI0VI(4) FUNC_VPI0VI(8)
-  FUNC_VPI0VU(1) FUNC_VPI0VU(2) FUNC_VPI0VU(4) FUNC_VPI0VU(8)
-  FUNC_VPI0VR(4) FUNC_VPI0VR(8)
+  FUNC_VPI0VI(1)
+  FUNC_VPI0VI(2)
+  FUNC_VPI0VI(4)
+  FUNC_VPI0VI(8)
+  FUNC_VPI0VU(1)
+  FUNC_VPI0VU(2)
+  FUNC_VPI0VU(4)
+  FUNC_VPI0VU(8)
+  FUNC_VPI0VR(4)
+  FUNC_VPI0VR(8)
   FUNC_VPI0VP
 
 #undef FUNC_VPI0VP
@@ -68,11 +75,12 @@ pure __vector_pair function func_vpi0vp(arg1, arg2); \
 !! ========== 3 arguments subroutine interface ===============================!!
 !! __vector_pair subroutine s(vp, integer, vector(i))
 #define SUB_VPI0VI(VKIND) \
-  pure subroutine sub_vpi0vi##VKIND(arg1, arg2, arg3); \
+  pure subroutine sub_vpi0vi##VKIND(arg1, argg2, arg3); \
     __vector_pair, intent(in) :: arg1; \
-    integer(8), intent(in) :: arg2; \
+    integer(8), intent(in) :: argg2; \
     !dir$ ignore_tkr(k) arg2; \
-    vector(integer(VKIND)), intent(out) :: arg3; \
+    vector(integer(VKIND)), \
+      intent(out) :: arg3; \
     !dir$ ignore_tkr(r) arg3; \
   end subroutine;
 
@@ -144,14 +152,28 @@ elemental subroutine sub_vpvr##VKIND##vr##VKIND(pair, arg1, arg2); \
     vector(real(VKIND)), intent(in) :: arg1, arg2; \
   end subroutine ;
 
-  ELEM_SUB_VPVIVI(1) ELEM_SUB_VPVIVI(2)
-  ELEM_SUB_VPVIVI(4) ELEM_SUB_VPVIVI(8)
-  ELEM_SUB_VPVUVU(1) ELEM_SUB_VPVUVU(2)
-  ELEM_SUB_VPVUVU(4) ELEM_SUB_VPVUVU(8)
-  ELEM_SUB_VPVRVR(4) ELEM_SUB_VPVRVR(8)
-  SUB_VPI0VI(1) SUB_VPI0VI(2) SUB_VPI0VI(4) SUB_VPI0VI(8)
-  SUB_VPI0VU(1) SUB_VPI0VU(2) SUB_VPI0VU(4) SUB_VPI0VU(8)
-  SUB_VPI0VR(4) SUB_VPI0VR(8)
+  ELEM_SUB_VPVIVI(1)
+  ELEM_SUB_VPVIVI(2)
+  ELEM_SUB_VPVIVI(4)
+  ELEM_SUB_VPVIVI(8)
+  ELEM_SUB_VPVUVU(1)
+  ELEM_SUB_VPVUVU(2)
+  ELEM_SUB_VPVUVU(4)
+  ELEM_SUB_VPVUVU(8)
+  ELEM_SUB_VPVRVR(4)
+  ELEM_SUB_VPVRVR(8)
+
+  SUB_VPI0VI(1)
+
+!!  SUB_VPI0VI(2)
+!!  SUB_VPI0VI(4)
+!!  SUB_VPI0VI(8)
+!!  SUB_VPI0VU(1)
+!!  SUB_VPI0VU(2)
+!!  SUB_VPI0VU(4)
+!!  SUB_VPI0VU(8)
+!!  SUB_VPI0VR(4)
+!!  SUB_VPI0VR(8)
 
 #undef ELEM_SUB_VPVIVI
 #undef ELEM_SUB_VPVUVU
@@ -181,10 +203,12 @@ elemental subroutine sub_vq##INTENT##vr##VKIND##vr##VKIND(acc, a, b); \
     vector(real(VKIND)), intent(in) :: a, b; \
   end subroutine ;
 
-  ELEM_SUB_VQVIVI(inout,1) ELEM_SUB_VQVIVI(inout,2)
+  ELEM_SUB_VQVIVI(inout,1)
+  ELEM_SUB_VQVIVI(inout,2)
   ELEM_SUB_VQVUVU(inout,1)
   ELEM_SUB_VQVRVR(inout,4)
-  ELEM_SUB_VQVIVI(out,1) ELEM_SUB_VQVIVI(out,2)
+  ELEM_SUB_VQVIVI(out,1)
+  ELEM_SUB_VQVIVI(out,2)
   ELEM_SUB_VQVUVU(out,1)
   ELEM_SUB_VQVRVR(out,4)
 
@@ -238,11 +262,16 @@ elemental subroutine sub_vqvr##VKIND##vr##VKIND##vr##VKIND##vr##VKIND(acc, arg1,
     vector(real(VKIND)), intent(in) :: arg1, arg2, arg3, arg4; \
   end subroutine ;
 
-  ELEM_SUB_VQVIVIVIVI(1) ELEM_SUB_VQVIVIVIVI(2)
-  ELEM_SUB_VQVIVIVIVI(4) ELEM_SUB_VQVIVIVIVI(8)
-  ELEM_SUB_VQVUVUVUVU(1) ELEM_SUB_VQVUVUVUVU(2)
-  ELEM_SUB_VQVUVUVUVU(4) ELEM_SUB_VQVUVUVUVU(8)
-  ELEM_SUB_VQVRVRVRVR(4) ELEM_SUB_VQVRVRVRVR(8)
+  ELEM_SUB_VQVIVIVIVI(1)
+  ELEM_SUB_VQVIVIVIVI(2)
+  ELEM_SUB_VQVIVIVIVI(4)
+  ELEM_SUB_VQVIVIVIVI(8)
+  ELEM_SUB_VQVUVUVUVU(1)
+  ELEM_SUB_VQVUVUVUVU(2)
+  ELEM_SUB_VQVUVUVUVU(4)
+  ELEM_SUB_VQVUVUVUVU(8)
+  ELEM_SUB_VQVRVRVRVR(4)
+  ELEM_SUB_VQVRVRVRVR(8)
 
 #undef ELEM_SUB_VQVRVRVRVR
 #undef ELEM_SUB_VQVUVUVUVU
@@ -250,21 +279,21 @@ elemental subroutine sub_vqvr##VKIND##vr##VKIND##vr##VKIND##vr##VKIND(acc, arg1,
 
 !! subroutine s(__vector_quad, vector(u), vector(u), integer, integer)
 #define ELEM_SUB_VQVUVUII(INTENT, VKIND) \
-  elemental subroutine sub_vq##INTENT##vu##VKIND##vu##VKIND##ii(acc, a, b, xmask, ymask); \
+  elemental subroutine sub_vq##INTENT##vu##VKIND##vu##VKIND##ii(acc, a, b, xmaskkkk, ymaskk); \
     __vector_quad, intent(INTENT) :: acc; \
     vector(unsigned(VKIND)), intent(in) :: a, b; \
-    integer(8), intent(in) :: xmask, ymask; \
-    !dir$ ignore_tkr(k) xmask; \
-    !dir$ ignore_tkr(k) ymask; \
+    integer(8), intent(in) :: xmaskkkk, ymaskk; \
+    !dir$ ignore_tkr(k) xmaskkkk; \
+    !dir$ ignore_tkr(k) ymaskk; \
   end subroutine ;
 
 !! subroutine s(__vector_quad, vector(r), vector(r), integer, integer)
 #define ELEM_SUB_VQVRVRII(INTENT, VKIND) \
-  elemental subroutine sub_vq##INTENT##vr##VKIND##vr##VKIND##ii(acc, a, b, xmask, ymask); \
+  elemental subroutine sub_vq##INTENT##vr##VKIND##vr##VKIND##ii(acc, a, b, xmaskkkk, ymask); \
     __vector_quad, intent(INTENT) :: acc; \
     vector(real(VKIND)), intent(in) :: a, b; \
-    integer(8), intent(in) :: xmask, ymask; \
-    !dir$ ignore_tkr(k) xmask; \
+    integer(8), intent(in) :: xmaskkkk, ymask; \
+    !dir$ ignore_tkr(k) xmaskkkk; \
     !dir$ ignore_tkr(k) ymask; \
   end subroutine ;
 

>From 412ec3bab2df613852dc86bf43aa483859cef761 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Wed, 19 Mar 2025 11:43:09 +0100
Subject: [PATCH 06/13] build fix

---
 flang-rt/lib/runtime/CMakeLists.txt |   4 +-
 llvm/runtimes/CMakeLists.txt        |   2 +
 openmp/runtime/src/CMakeLists.txt   | 111 +++++++++++++++-------------
 3 files changed, 65 insertions(+), 52 deletions(-)

diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index 08f8122f449ef..9341fd08a9053 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -104,7 +104,9 @@ set(host_sources
 set_source_files_properties(cudadevice.f90
   PROPERTIES COMPILE_OPTIONS "-xcuda"
 )
-set_source_files_properties(mma.f90
+set_source_files_properties(
+  mma.f90
+  cudadevice.f90
   PROPERTIES Fortran_PREPROCESS OFF
 )
 
diff --git a/llvm/runtimes/CMakeLists.txt b/llvm/runtimes/CMakeLists.txt
index 00ff669ffe415..0dc6c5862cb63 100644
--- a/llvm/runtimes/CMakeLists.txt
+++ b/llvm/runtimes/CMakeLists.txt
@@ -388,6 +388,7 @@ function(runtime_register_target name)
           list(APPEND ${name}_extra_args "-D${new_name}=${new_value}")
         endif()
       endif()
+      message("${name}_extra_args: ${${name}_extra_args}")
     endforeach()
     foreach(variable_name ${${name}_extra_args})
       string(FIND "${variable_name}" "-DRUNTIMES_${extra_name}_" out)
@@ -396,6 +397,7 @@ function(runtime_register_target name)
         string(REPLACE ";" "|" new_value "${new_name}")
         list(APPEND ${name}_extra_args "-D${new_value}")
       endif()
+      message("${name}_extra_args: ${${name}_extra_args}")
     endforeach()
   endforeach()
 
diff --git a/openmp/runtime/src/CMakeLists.txt b/openmp/runtime/src/CMakeLists.txt
index 698e185d9c4dd..fd8a464c29c1b 100644
--- a/openmp/runtime/src/CMakeLists.txt
+++ b/openmp/runtime/src/CMakeLists.txt
@@ -364,49 +364,58 @@ if(WIN32)
 endif()
 
 # Building the Fortran module files
-# One compilation step creates both omp_lib.mod and omp_lib_kinds.mod
 configure_file(${LIBOMP_INC_DIR}/omp_lib.h.var omp_lib.h @ONLY)
 configure_file(${LIBOMP_INC_DIR}/omp_lib.F90.var omp_lib.F90 @ONLY)
 
-set(BUILD_FORTRAN_MODULES False)
-if (NOT ${LIBOMP_FORTRAN_MODULES_COMPILER} STREQUAL "")
-  # If libomp is built as an LLVM runtime and the flang compiler is available,
-  # compile the Fortran module files.
-  message(STATUS "configuring openmp to build Fortran module files using ${LIBOMP_FORTRAN_MODULES_COMPILER}")
-  set(LIBOMP_FORTRAN_SOURCE_FILE omp_lib.F90)
-  add_custom_target(libomp-mod ALL DEPENDS omp_lib.mod omp_lib_kinds.mod)
-  add_custom_command(
-    OUTPUT omp_lib.mod omp_lib_kinds.mod
-    COMMAND ${LIBOMP_FORTRAN_MODULES_COMPILER} -cpp -fsyntax-only ${LIBOMP_FORTRAN_SOURCE_FILE}
-    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${LIBOMP_FORTRAN_SOURCE_FILE}
-      ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.h
-  )
-  set(BUILD_FORTRAN_MODULES True)
-elseif(${LIBOMP_FORTRAN_MODULES})
-  # The following requests explicit building of the Fortran module files
-  # Workaround for gfortran to build modules with the
-  # omp_sched_monotonic integer parameter
-  if (CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
-    set(ADDITIONAL_Fortran_FLAGS "-fno-range-check")
-  endif()
-  add_custom_target(libomp-mod ALL DEPENDS omp_lib.mod omp_lib_kinds.mod)
-  set_target_properties(libomp-mod PROPERTIES FOLDER "OpenMP/Misc")
-  libomp_get_fflags(LIBOMP_CONFIGURED_FFLAGS)
-  if(CMAKE_Fortran_COMPILER_SUPPORTS_F90)
-    set(LIBOMP_FORTRAN_SOURCE_FILE omp_lib.F90)
-  else()
-    message(FATAL_ERROR "Fortran module build requires Fortran 90 compiler")
-  endif()
-  add_custom_command(
-    OUTPUT omp_lib.mod omp_lib_kinds.mod
-    COMMAND ${CMAKE_Fortran_COMPILER} -c ${ADDITIONAL_Fortran_FLAGS}
-            ${LIBOMP_CONFIGURED_FFLAGS} ${LIBOMP_FORTRAN_SOURCE_FILE}
-    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${LIBOMP_FORTRAN_SOURCE_FILE}
-      ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.h
+#set(BUILD_FORTRAN_MODULES False)
+#if (NOT ${LIBOMP_FORTRAN_MODULES_COMPILER} STREQUAL "")
+#  # If libomp is built as an LLVM runtime and the flang compiler is available,
+#  # compile the Fortran module files.
+#  message(STATUS "configuring openmp to build Fortran module files using ${LIBOMP_FORTRAN_MODULES_COMPILER}")
+#  set(LIBOMP_FORTRAN_SOURCE_FILE omp_lib.F90)
+#  add_custom_target(libomp-mod ALL DEPENDS omp_lib.mod omp_lib_kinds.mod)
+#  add_custom_command(
+#    OUTPUT omp_lib.mod omp_lib_kinds.mod
+#    COMMAND ${LIBOMP_FORTRAN_MODULES_COMPILER} -cpp -fsyntax-only ${LIBOMP_FORTRAN_SOURCE_FILE}
+#    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${LIBOMP_FORTRAN_SOURCE_FILE}
+#      ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.h
+#  )
+#  set(BUILD_FORTRAN_MODULES True)
+#elseif(${LIBOMP_FORTRAN_MODULES})
+#  # The following requests explicit building of the Fortran module files
+#  # Workaround for gfortran to build modules with the
+#  # omp_sched_monotonic integer parameter
+#  if (CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
+#    set(ADDITIONAL_Fortran_FLAGS "-fno-range-check")
+#  endif()
+#  add_custom_target(libomp-mod ALL DEPENDS omp_lib.mod omp_lib_kinds.mod)
+#  set_target_properties(libomp-mod PROPERTIES FOLDER "OpenMP/Misc")
+#  libomp_get_fflags(LIBOMP_CONFIGURED_FFLAGS)
+#  if(CMAKE_Fortran_COMPILER_SUPPORTS_F90)
+#    set(LIBOMP_FORTRAN_SOURCE_FILE omp_lib.F90)
+#  else()
+#    message(FATAL_ERROR "Fortran module build requires Fortran 90 compiler")
+#  endif()
+#  add_custom_command(
+#    OUTPUT omp_lib.mod omp_lib_kinds.mod
+#    COMMAND ${CMAKE_Fortran_COMPILER} -c ${ADDITIONAL_Fortran_FLAGS}
+#            ${LIBOMP_CONFIGURED_FFLAGS} ${LIBOMP_FORTRAN_SOURCE_FILE}
+#    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${LIBOMP_FORTRAN_SOURCE_FILE}
+#      ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.h
+#  )
+#  set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES omp_lib${CMAKE_C_OUTPUT_EXTENSION})
+#  set(BUILD_FORTRAN_MODULES True)
+#endif()
+
+include(CheckLanguage)
+check_language(Fortran)
+if(CMAKE_Fortran_COMPILER)
+  enable_language(Fortran)
+  add_library(libomp-mod OBJECT 
+    omp_lib.F90
   )
-  set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES omp_lib${CMAKE_C_OUTPUT_EXTENSION})
-  set(BUILD_FORTRAN_MODULES True)
-endif()
+endif ()
+
 
 # Move files to exports/ directory if requested
 if(${LIBOMP_COPY_EXPORTS})
@@ -482,15 +491,15 @@ if(${LIBOMP_OMPT_SUPPORT})
   install(FILES ${LIBOMP_HEADERS_INTDIR}/omp-tools.h DESTINATION ${LIBOMP_HEADERS_INSTALL_PATH} RENAME ompt.h)
   set(LIBOMP_OMP_TOOLS_INCLUDE_DIR ${CMAKE_CURRENT_BINARY_DIR} PARENT_SCOPE)
 endif()
-if(${BUILD_FORTRAN_MODULES})
-  set (destination ${LIBOMP_HEADERS_INSTALL_PATH})
-  if (NOT ${LIBOMP_MODULES_INSTALL_PATH} STREQUAL "")
-    set (destination ${LIBOMP_MODULES_INSTALL_PATH})
-  endif()
-  install(FILES
-    ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.h
-    ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.mod
-    ${CMAKE_CURRENT_BINARY_DIR}/omp_lib_kinds.mod
-    DESTINATION ${destination}
-  )
-endif()
+#if(${BUILD_FORTRAN_MODULES})
+#  set (destination ${LIBOMP_HEADERS_INSTALL_PATH})
+#  if (NOT ${LIBOMP_MODULES_INSTALL_PATH} STREQUAL "")
+#    set (destination ${LIBOMP_MODULES_INSTALL_PATH})
+#  endif()
+#  install(FILES
+#    ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.h
+#    ${CMAKE_CURRENT_BINARY_DIR}/omp_lib.mod
+#    ${CMAKE_CURRENT_BINARY_DIR}/omp_lib_kinds.mod
+#    DESTINATION ${destination}
+#  )
+#endif()

>From 9f3b9d756d957f1cb81d8ce321449e9fb9b750a6 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Thu, 20 Mar 2025 12:39:07 +0100
Subject: [PATCH 07/13] Progress getting builtin modules compile on Windows

---
 clang/include/clang/Driver/Options.td     | 10 ++++++++++
 flang-rt/lib/runtime/CMakeLists.txt       | 15 ++++++++++++--
 flang-rt/lib/runtime/cudadevice.f90       |  1 +
 flang/include/flang/Parser/options.h      |  4 ++--
 flang/include/flang/Parser/provenance.h   |  2 +-
 flang/include/flang/Semantics/semantics.h |  2 +-
 flang/lib/Frontend/CMakeLists.txt         | 14 ++++++-------
 flang/lib/Frontend/CompilerInvocation.cpp | 24 ++++++++++++++++++-----
 flang/lib/Frontend/FrontendAction.cpp     |  4 ++--
 flang/lib/Parser/parsing.cpp              |  2 +-
 flang/lib/Parser/provenance.cpp           |  8 ++++++++
 flang/lib/Semantics/mod-file.cpp          |  9 +++++++++
 flang/lib/Semantics/resolve-names.cpp     |  7 ++++++-
 flang/lib/Semantics/semantics.cpp         | 13 ++++++++----
 14 files changed, 89 insertions(+), 26 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td
index 66ae8f1c7f064..562a7a2f275e3 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3971,6 +3971,16 @@ def fsyntax_only : Flag<["-"], "fsyntax-only">,
   Visibility<[ClangOption, CLOption, DXCOption, CC1Option, FC1Option, FlangOption]>,
   Group<Action_Group>,
   HelpText<"Run the preprocessor, parser and semantic analysis stages">;
+
+
+def fno_builtin_modules : Flag<["-"], "fno-builtin-modules">,
+  Visibility<[FC1Option]>,
+  HelpText<"Do not implicitly use builtin modules (for internal use only)">;
+def fbuiltin_modules_path : Joined<["--"], "fbuiltin-modules-path=">, 
+  Visibility<[FlangOption, FC1Option]>,
+  HelpText<"Specify where Flang finds its builtin modules">;
+
+
 def ftabstop_EQ : Joined<["-"], "ftabstop=">, Group<f_Group>;
 def ftemplate_depth_EQ : Joined<["-"], "ftemplate-depth=">, Group<f_Group>,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index 9341fd08a9053..d166725da5071 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -77,7 +77,7 @@ set(host_sources
   __fortran_builtins.f90
   __fortran_ieee_exceptions.f90
   __fortran_type_info.f90
-  cudadevice.f90
+#  cudadevice.f90
   ieee_arithmetic.f90
   ieee_exceptions.f90
   ieee_features.f90
@@ -101,6 +101,13 @@ set(host_sources
   unit-map.cpp
 )
 
+
+# Stop CMake from ignoring dependencies between builtin-modules. CMake added this just for (classic) Flang.
+# Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
+set(Fortran_BUILDING_INTRINSIC_MODULES TRUE)
+set(Fortran_BUILDING_INSTRINSIC_MODULES TRUE)
+
+
 set_source_files_properties(cudadevice.f90
   PROPERTIES COMPILE_OPTIONS "-xcuda"
 )
@@ -110,9 +117,11 @@ set_source_files_properties(
   PROPERTIES Fortran_PREPROCESS OFF
 )
 
+#add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mllvm=-flang-intrinsics-mode>)
+
 message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
 message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
-if  (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
+if (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
   list(APPEND host_source
     __ppc_types.f90
     __ppc_intrinsics.f90
@@ -184,12 +193,14 @@ else()
 
   function (add_win_flangrt_runtime libtype suffix msvc_lib)
     set(name "flang_rt.runtime.${suffix}")
+    #include_directories("${CMAKE_CURRENT_BINARY_DIR}/module.${suffix}")
     add_flangrt_library(${name} ${libtype}
         ${sources}
         ${ARGN}
         LINK_LIBRARIES ${Backtrace_LIBRARY}
         ADDITIONAL_HEADERS ${public_headers} ${private_headers}
       )
+    target_compile_options(${name} PRIVATE "-fintrinsic-modules-path=${CMAKE_CURRENT_BINARY_DIR}/module.${suffix}")
 
     if (msvc_lib)
       set_target_properties(${name}
diff --git a/flang-rt/lib/runtime/cudadevice.f90 b/flang-rt/lib/runtime/cudadevice.f90
index baaa112f5d8c2..8c13fbcc907e7 100644
--- a/flang-rt/lib/runtime/cudadevice.f90
+++ b/flang-rt/lib/runtime/cudadevice.f90
@@ -9,6 +9,7 @@
 ! CUDA Fortran procedures available in device subprogram
 
 module cudadevice
+  use __cuda_builtins
   use __cuda_device
   use, intrinsic :: __fortran_builtins, only: dim3 => __builtin_dim3
   use, intrinsic :: __fortran_builtins, only: c_devptr => __builtin_c_devptr
diff --git a/flang/include/flang/Parser/options.h b/flang/include/flang/Parser/options.h
index dc363acb7c28a..57d9bbc10ce45 100644
--- a/flang/include/flang/Parser/options.h
+++ b/flang/include/flang/Parser/options.h
@@ -23,11 +23,11 @@ struct Options {
 
   using Predefinition = std::pair<std::string, std::optional<std::string>>;
 
-  bool isFixedForm{false};
+  bool isFixedForm{false}; bool isIntrinsicMode{false};
   int fixedFormColumns{72};
   common::LanguageFeatureControl features;
   std::vector<std::string> searchDirectories;
-  std::vector<std::string> intrinsicModuleDirectories;
+  std::vector<std::string> intrinsicModuleDirectories; 
   std::vector<Predefinition> predefinitions;
   bool instrumentedParse{false};
   bool isModuleFile{false};
diff --git a/flang/include/flang/Parser/provenance.h b/flang/include/flang/Parser/provenance.h
index a9224b727fd05..dda83fb4fbc3a 100644
--- a/flang/include/flang/Parser/provenance.h
+++ b/flang/include/flang/Parser/provenance.h
@@ -188,7 +188,7 @@ class AllSources {
   ProvenanceRange IntersectionWithSourceFiles(ProvenanceRange) const;
   llvm::raw_ostream &Dump(llvm::raw_ostream &) const;
 
-private:
+public:
   struct Inclusion {
     const SourceFile &source;
     bool isModule{false};
diff --git a/flang/include/flang/Semantics/semantics.h b/flang/include/flang/Semantics/semantics.h
index 730513dbe3232..84978e37af89f 100644
--- a/flang/include/flang/Semantics/semantics.h
+++ b/flang/include/flang/Semantics/semantics.h
@@ -363,7 +363,7 @@ class Semantics {
   void EmitMessages(llvm::raw_ostream &);
   void DumpSymbols(llvm::raw_ostream &);
   void DumpSymbolsSources(llvm::raw_ostream &) const;
-
+  bool intrinsicsMode_ = false;
 private:
   SemanticsContext &context_;
   parser::Program &program_;
diff --git a/flang/lib/Frontend/CMakeLists.txt b/flang/lib/Frontend/CMakeLists.txt
index e8a098613e26f..cf5f44fae9c9e 100644
--- a/flang/lib/Frontend/CMakeLists.txt
+++ b/flang/lib/Frontend/CMakeLists.txt
@@ -73,10 +73,10 @@ add_flang_library(flangFrontend
   clangDriver
 )
 
-target_precompile_headers(flangFrontend PRIVATE
-  [["flang/Parser/parsing.h"]]
-  [["flang/Parser/parse-tree.h"]]
-  [["flang/Parser/dump-parse-tree.h"]]
-  [["flang/Lower/PFTBuilder.h"]]
-  [["flang/Lower/Bridge.h"]]
-)
+#target_precompile_headers(flangFrontend PRIVATE
+#  [["flang/Parser/parsing.h"]]
+#  [["flang/Parser/parse-tree.h"]]
+#  [["flang/Parser/dump-parse-tree.h"]]
+#  [["flang/Lower/PFTBuilder.h"]]
+#  [["flang/Lower/Bridge.h"]]
+#)
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp
index edf738785fb97..341f6c4ff74bd 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -39,6 +39,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/TargetParser/Host.h"
 #include "llvm/TargetParser/Triple.h"
 #include <algorithm>
@@ -47,6 +48,9 @@
 #include <optional>
 
 using namespace Fortran::frontend;
+namespace llvm {
+ cl::opt<bool> FlangIntrinsicsMode("flang-intrinsics-mode",  cl::desc("Use when compiling intrinsic modules"));
+ }
 
 //===----------------------------------------------------------------------===//
 // Initialization.
@@ -815,7 +819,7 @@ static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
 }
 
 // Generate the path to look for intrinsic modules
-static std::string getIntrinsicDir(const char *argv) {
+static std::string getIntrinsicDir(const char *argv) { // MK: To modify this
   // TODO: Find a system independent API
   llvm::SmallString<128> driverPath;
   driverPath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
@@ -823,7 +827,7 @@ static std::string getIntrinsicDir(const char *argv) {
   driverPath.append("/../include/flang/");
   return std::string(driverPath);
 }
-
+ 
 // Generate the path to look for OpenMP headers
 static std::string getOpenMPHeadersDir(const char *argv) {
   llvm::SmallString<128> includePath;
@@ -1547,9 +1551,12 @@ void CompilerInvocation::setDefaultFortranOpts() {
   fortranOptions.searchDirectories.emplace_back(
       getOpenMPHeadersDir(getArgv0()));
 
-  fortranOptions.isFixedForm = false;
+  fortranOptions.isFixedForm = false;  
+  fortranOptions.isIntrinsicMode = llvm::FlangIntrinsicsMode;
 }
 
+
+
 // TODO: When expanding this method, consider creating a dedicated API for
 // this. Also at some point we will need to differentiate between different
 // targets and add dedicated predefines for each.
@@ -1622,14 +1629,21 @@ void CompilerInvocation::setFortranOpts() {
       preprocessorOptions.searchDirectoriesFromDashI.end());
 
   // Add the ordered list of -intrinsic-modules-path
+  #if 0
   fortranOptions.searchDirectories.insert(
       fortranOptions.searchDirectories.end(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
+#endif 
 
   //  Add the default intrinsic module directory
-  fortranOptions.intrinsicModuleDirectories.emplace_back(
-      getIntrinsicDir(getArgv0()));
+  fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir(getArgv0()));
+// llvm::append_range(     fortranOptions.intrinsicModuleDirectories,    preprocessorOptions.searchDirectoriesFromIntrModPath );
+    fortranOptions.intrinsicModuleDirectories.insert(
+      fortranOptions.intrinsicModuleDirectories.end(),
+      preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
+      preprocessorOptions.searchDirectoriesFromIntrModPath.end());
+
 
   // Add the directory supplied through -J/-module-dir to the list of search
   // directories
diff --git a/flang/lib/Frontend/FrontendAction.cpp b/flang/lib/Frontend/FrontendAction.cpp
index ab77d143fa4b6..1d06dc75d1cd9 100644
--- a/flang/lib/Frontend/FrontendAction.cpp
+++ b/flang/lib/Frontend/FrontendAction.cpp
@@ -190,12 +190,12 @@ bool FrontendAction::runSemanticChecks() {
   // Prepare semantics
   ci.setSemantics(std::make_unique<Fortran::semantics::Semantics>(semanticsCtx,
                                                                   *parseTree));
-  auto &semantics = ci.getSemantics();
+  auto &semantics = ci.getSemantics();semantics.intrinsicsMode_ = ci.getInvocation().getFortranOpts().isIntrinsicMode;
   semantics.set_hermeticModuleFileOutput(
       ci.getInvocation().getHermeticModuleFileOutput());
 
   // Run semantic checks
-  semantics.Perform();
+  semantics.Perform(); 
 
   if (reportFatalSemanticErrors()) {
     return false;
diff --git a/flang/lib/Parser/parsing.cpp b/flang/lib/Parser/parsing.cpp
index 8fcac7b3cacb1..bba87a912d6f3 100644
--- a/flang/lib/Parser/parsing.cpp
+++ b/flang/lib/Parser/parsing.cpp
@@ -23,7 +23,7 @@ Parsing::~Parsing() {}
 const SourceFile *Parsing::Prescan(const std::string &path, Options options) {
   options_ = options;
   AllSources &allSources{allCooked_.allSources()};
-  allSources.ClearSearchPath();
+  allSources.ClearSearchPath(); llvm::errs() << "Prescan('" << path  << "', "  << options.isModuleFile << ")\n";
   if (options.isModuleFile) {
     for (const auto &path : options.searchDirectories) {
       allSources.AppendSearchPathDirectory(path);
diff --git a/flang/lib/Parser/provenance.cpp b/flang/lib/Parser/provenance.cpp
index fe92aa7f64fb1..7be5a49a3f805 100644
--- a/flang/lib/Parser/provenance.cpp
+++ b/flang/lib/Parser/provenance.cpp
@@ -186,7 +186,15 @@ const SourceFile *AllSources::Open(std::string path, llvm::raw_ostream &error,
     // INCLUDE statements.
     searchPath_.emplace_front(std::move(*prependPath));
   }
+
+    llvm::errs() << "Open('" << path << "', '" << prependPath << "')\n";
+  for (auto &&sp : searchPath_) {
+        llvm::errs() << "  " << sp << "\n";
+  }
+          llvm::errs() << "\n";
   std::optional<std::string> found{LocateSourceFile(path, searchPath_)};
+      llvm::errs() << "Found = '" << found << "')\n";
+
   if (prependPath) {
     searchPath_.pop_front();
   }
diff --git a/flang/lib/Semantics/mod-file.cpp b/flang/lib/Semantics/mod-file.cpp
index c3b46261228df..a7ec6f3034bfc 100644
--- a/flang/lib/Semantics/mod-file.cpp
+++ b/flang/lib/Semantics/mod-file.cpp
@@ -20,12 +20,17 @@
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/CommandLine.h"
 #include <algorithm>
 #include <fstream>
 #include <set>
 #include <string_view>
 #include <vector>
 
+namespace llvm {
+ extern llvm::cl::opt<bool> FlangIntrinsicsMode;
+ }
+
 namespace Fortran::semantics {
 
 using namespace parser::literals;
@@ -1345,6 +1350,10 @@ Scope *ModFileReader::Read(SourceName name, std::optional<bool> isIntrinsic,
     }
     ancestorName = ancestor->GetName().value().ToString();
   }
+
+  if (llvm::FlangIntrinsicsMode)
+    isIntrinsic = false;
+
   auto requiredHash{context_.moduleDependences().GetRequiredHash(
       name.ToString(), isIntrinsic.value_or(false))};
   if (!isIntrinsic.value_or(false) && !ancestor) {
diff --git a/flang/lib/Semantics/resolve-names.cpp b/flang/lib/Semantics/resolve-names.cpp
index fcd4ba6a51907..8feeb3ced02de 100644
--- a/flang/lib/Semantics/resolve-names.cpp
+++ b/flang/lib/Semantics/resolve-names.cpp
@@ -13,6 +13,7 @@
 #include "resolve-directives.h"
 #include "resolve-names-utils.h"
 #include "rewrite-parse-tree.h"
+#include "llvm/Support/CommandLine.h"
 #include "flang/Common/indirection.h"
 #include "flang/Common/restorer.h"
 #include "flang/Common/visit.h"
@@ -44,6 +45,10 @@
 #include <set>
 #include <stack>
 
+namespace llvm {
+ extern cl::opt<bool> FlangIntrinsicsMode;
+ }
+
 namespace Fortran::semantics {
 
 using namespace parser::literals;
@@ -3901,7 +3906,7 @@ void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) {
 // If an error occurs, report it and return nullptr.
 Scope *ModuleVisitor::FindModule(const parser::Name &name,
     std::optional<bool> isIntrinsic, Scope *ancestor) {
-  ModFileReader reader{context()};
+  ModFileReader reader{context()}; 
   Scope *scope{
       reader.Read(name.source, isIntrinsic, ancestor, /*silent=*/false)};
   if (scope) {
diff --git a/flang/lib/Semantics/semantics.cpp b/flang/lib/Semantics/semantics.cpp
index 10a01039ea0ae..b2c2e718f00f5 100644
--- a/flang/lib/Semantics/semantics.cpp
+++ b/flang/lib/Semantics/semantics.cpp
@@ -607,13 +607,18 @@ parser::Program &SemanticsContext::SaveParseTree(parser::Program &&tree) {
   return modFileParseTrees_.emplace_back(std::move(tree));
 }
 
-bool Semantics::Perform() {
+bool Semantics::Perform() {  
+  const auto *frontModule{std::get_if<common::Indirection<parser::Module>>(&program_.v.front().u)};
+  auto &&source = std::get<parser::Statement<parser::ModuleStmt>>(frontModule->value().t)   .statement.v.source;
+
+
+
   // Implicitly USE the __Fortran_builtins module so that special types
   // (e.g., __builtin_team_type) are available to semantics, esp. for
   // intrinsic checking.
-  if (!program_.v.empty()) {
-    const auto *frontModule{std::get_if<common::Indirection<parser::Module>>(
-        &program_.v.front().u)};
+    if (intrinsicsMode_) {
+      int a = 0;
+    } else   if (!program_.v.empty()) {
     if (frontModule &&
         (std::get<parser::Statement<parser::ModuleStmt>>(frontModule->value().t)
                     .statement.v.source == "__fortran_builtins" ||

>From 9d6578a51c4270452769113e8cecec6a793068c0 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Thu, 20 Mar 2025 13:56:43 +0100
Subject: [PATCH 08/13] trying fixing tests

---
 flang-rt/lib/runtime/CMakeLists.txt         | 10 +++++++---
 flang-rt/lib/runtime/cudadevice.f90         |  2 ++
 flang/lib/Frontend/CompilerInvocation.cpp   | 19 ++++++++++---------
 flang/lib/Frontend/FrontendAction.cpp       |  5 +++--
 flang/lib/Parser/parsing.cpp                |  6 +++++-
 flang/lib/Parser/provenance.cpp             | 11 +++++++----
 flang/lib/Semantics/resolve-names.cpp       |  2 +-
 flang/lib/Semantics/semantics.cpp           | 15 +++++++++------
 flang/test/Driver/intrinsic-module-path.f90 |  4 ++++
 9 files changed, 48 insertions(+), 26 deletions(-)

diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index d166725da5071..caa5b0d0a95f9 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -77,7 +77,7 @@ set(host_sources
   __fortran_builtins.f90
   __fortran_ieee_exceptions.f90
   __fortran_type_info.f90
-#  cudadevice.f90
+  cudadevice.f90
   ieee_arithmetic.f90
   ieee_exceptions.f90
   ieee_features.f90
@@ -117,7 +117,7 @@ set_source_files_properties(
   PROPERTIES Fortran_PREPROCESS OFF
 )
 
-#add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mllvm=-flang-intrinsics-mode>)
+
 
 message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
 message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
@@ -130,6 +130,8 @@ if (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
 endif ()
 
 add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
+
+#add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mllvm=-flang-intrinsics-mode>)
 #set(CMAKE_Fortran_PREPROCESS FALSE)
 #add_compile_options(-mllvm -ignore-missing-type-desc)
 
@@ -200,7 +202,9 @@ else()
         LINK_LIBRARIES ${Backtrace_LIBRARY}
         ADDITIONAL_HEADERS ${public_headers} ${private_headers}
       )
-    target_compile_options(${name} PRIVATE "-fintrinsic-modules-path=${CMAKE_CURRENT_BINARY_DIR}/module.${suffix}")
+# "$<$<COMPILE_LANGUAGE:Fortran>:-Xflang>"
+#TODO: Better as -fintrinsic-modules-path, need added option
+    target_compile_options(${name} PRIVATE  "$<$<COMPILE_LANGUAGE:Fortran>:SHELL:-fintrinsic-modules-path>" "$<$<COMPILE_LANGUAGE:Fortran>:${CMAKE_CURRENT_BINARY_DIR}/module.${suffix}>")
 
     if (msvc_lib)
       set_target_properties(${name}
diff --git a/flang-rt/lib/runtime/cudadevice.f90 b/flang-rt/lib/runtime/cudadevice.f90
index 8c13fbcc907e7..79f3b598590c3 100644
--- a/flang-rt/lib/runtime/cudadevice.f90
+++ b/flang-rt/lib/runtime/cudadevice.f90
@@ -8,6 +8,8 @@
 
 ! CUDA Fortran procedures available in device subprogram
 
+! MK: rename to cudadevice.cuf ?
+
 module cudadevice
   use __cuda_builtins
   use __cuda_device
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp
index 341f6c4ff74bd..83306a4747858 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -48,9 +48,10 @@
 #include <optional>
 
 using namespace Fortran::frontend;
+
 namespace llvm {
- cl::opt<bool> FlangIntrinsicsMode("flang-intrinsics-mode",  cl::desc("Use when compiling intrinsic modules"));
- }
+  extern cl::opt<bool> FlangIntrinsicsMode;
+}
 
 //===----------------------------------------------------------------------===//
 // Initialization.
@@ -827,7 +828,7 @@ static std::string getIntrinsicDir(const char *argv) { // MK: To modify this
   driverPath.append("/../include/flang/");
   return std::string(driverPath);
 }
- 
+
 // Generate the path to look for OpenMP headers
 static std::string getOpenMPHeadersDir(const char *argv) {
   llvm::SmallString<128> includePath;
@@ -1555,8 +1556,6 @@ void CompilerInvocation::setDefaultFortranOpts() {
   fortranOptions.isIntrinsicMode = llvm::FlangIntrinsicsMode;
 }
 
-
-
 // TODO: When expanding this method, consider creating a dedicated API for
 // this. Also at some point we will need to differentiate between different
 // targets and add dedicated predefines for each.
@@ -1629,7 +1628,8 @@ void CompilerInvocation::setFortranOpts() {
       preprocessorOptions.searchDirectoriesFromDashI.end());
 
   // Add the ordered list of -intrinsic-modules-path
-  #if 0
+#if 1
+  // Legacy
   fortranOptions.searchDirectories.insert(
       fortranOptions.searchDirectories.end(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
@@ -1637,13 +1637,14 @@ void CompilerInvocation::setFortranOpts() {
 #endif 
 
   //  Add the default intrinsic module directory
-  fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir(getArgv0()));
-// llvm::append_range(     fortranOptions.intrinsicModuleDirectories,    preprocessorOptions.searchDirectoriesFromIntrModPath );
+#if 1
+     // MK Contradicts description of the option which says "if not found"
     fortranOptions.intrinsicModuleDirectories.insert(
       fortranOptions.intrinsicModuleDirectories.end(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
-
+#endif 
+  fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir(getArgv0()));
 
   // Add the directory supplied through -J/-module-dir to the list of search
   // directories
diff --git a/flang/lib/Frontend/FrontendAction.cpp b/flang/lib/Frontend/FrontendAction.cpp
index 1d06dc75d1cd9..0a1a3d6ac9d5e 100644
--- a/flang/lib/Frontend/FrontendAction.cpp
+++ b/flang/lib/Frontend/FrontendAction.cpp
@@ -190,12 +190,13 @@ bool FrontendAction::runSemanticChecks() {
   // Prepare semantics
   ci.setSemantics(std::make_unique<Fortran::semantics::Semantics>(semanticsCtx,
                                                                   *parseTree));
-  auto &semantics = ci.getSemantics();semantics.intrinsicsMode_ = ci.getInvocation().getFortranOpts().isIntrinsicMode;
+  auto &semantics = ci.getSemantics();
+  semantics.intrinsicsMode_ = ci.getInvocation().getFortranOpts().isIntrinsicMode;
   semantics.set_hermeticModuleFileOutput(
       ci.getInvocation().getHermeticModuleFileOutput());
 
   // Run semantic checks
-  semantics.Perform(); 
+  semantics.Perform();
 
   if (reportFatalSemanticErrors()) {
     return false;
diff --git a/flang/lib/Parser/parsing.cpp b/flang/lib/Parser/parsing.cpp
index bba87a912d6f3..63b3e876a5303 100644
--- a/flang/lib/Parser/parsing.cpp
+++ b/flang/lib/Parser/parsing.cpp
@@ -14,6 +14,9 @@
 #include "flang/Parser/provenance.h"
 #include "flang/Parser/source.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "flang"
 
 namespace Fortran::parser {
 
@@ -23,7 +26,8 @@ Parsing::~Parsing() {}
 const SourceFile *Parsing::Prescan(const std::string &path, Options options) {
   options_ = options;
   AllSources &allSources{allCooked_.allSources()};
-  allSources.ClearSearchPath(); llvm::errs() << "Prescan('" << path  << "', "  << options.isModuleFile << ")\n";
+  allSources.ClearSearchPath(); 
+  LLVM_DEBUG(llvm::dbgs() << "Prescan('" << path  << "', "  << options.isModuleFile << ")\n");
   if (options.isModuleFile) {
     for (const auto &path : options.searchDirectories) {
       allSources.AppendSearchPathDirectory(path);
diff --git a/flang/lib/Parser/provenance.cpp b/flang/lib/Parser/provenance.cpp
index 7be5a49a3f805..3e8fcd5d06a30 100644
--- a/flang/lib/Parser/provenance.cpp
+++ b/flang/lib/Parser/provenance.cpp
@@ -9,10 +9,13 @@
 #include "flang/Parser/provenance.h"
 #include "flang/Common/idioms.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/Debug.h"
 #include <algorithm>
 #include <set>
 #include <utility>
 
+#define DEBUG_TYPE "flang"
+
 namespace Fortran::parser {
 
 ProvenanceRangeToOffsetMappings::ProvenanceRangeToOffsetMappings() {}
@@ -187,13 +190,13 @@ const SourceFile *AllSources::Open(std::string path, llvm::raw_ostream &error,
     searchPath_.emplace_front(std::move(*prependPath));
   }
 
-    llvm::errs() << "Open('" << path << "', '" << prependPath << "')\n";
+ LLVM_DEBUG(   llvm::errs() << "Open('" << path << "', '" << prependPath << "')\n");
   for (auto &&sp : searchPath_) {
-        llvm::errs() << "  " << sp << "\n";
+        LLVM_DEBUG(    llvm::errs() << "  " << sp << "\n");
   }
-          llvm::errs() << "\n";
+        LLVM_DEBUG(      llvm::errs() << "\n");
   std::optional<std::string> found{LocateSourceFile(path, searchPath_)};
-      llvm::errs() << "Found = '" << found << "')\n";
+     LLVM_DEBUG(     llvm::errs() << "Found = '" << found << "')\n");
 
   if (prependPath) {
     searchPath_.pop_front();
diff --git a/flang/lib/Semantics/resolve-names.cpp b/flang/lib/Semantics/resolve-names.cpp
index 8feeb3ced02de..bd40fac52830a 100644
--- a/flang/lib/Semantics/resolve-names.cpp
+++ b/flang/lib/Semantics/resolve-names.cpp
@@ -3906,7 +3906,7 @@ void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) {
 // If an error occurs, report it and return nullptr.
 Scope *ModuleVisitor::FindModule(const parser::Name &name,
     std::optional<bool> isIntrinsic, Scope *ancestor) {
-  ModFileReader reader{context()}; 
+  ModFileReader reader{context()};
   Scope *scope{
       reader.Read(name.source, isIntrinsic, ancestor, /*silent=*/false)};
   if (scope) {
diff --git a/flang/lib/Semantics/semantics.cpp b/flang/lib/Semantics/semantics.cpp
index b2c2e718f00f5..19e775faf00cf 100644
--- a/flang/lib/Semantics/semantics.cpp
+++ b/flang/lib/Semantics/semantics.cpp
@@ -44,9 +44,15 @@
 #include "flang/Semantics/symbol.h"
 #include "flang/Support/default-kinds.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/TargetParser/Host.h"
 #include "llvm/TargetParser/Triple.h"
 
+
+namespace llvm {
+ cl::opt<bool> FlangIntrinsicsMode("flang-intrinsics-mode",  cl::desc("Use when compiling intrinsic modules"));
+ }
+
 namespace Fortran::semantics {
 
 using NameToSymbolMap = std::multimap<parser::CharBlock, SymbolRef>;
@@ -607,18 +613,15 @@ parser::Program &SemanticsContext::SaveParseTree(parser::Program &&tree) {
   return modFileParseTrees_.emplace_back(std::move(tree));
 }
 
-bool Semantics::Perform() {  
-  const auto *frontModule{std::get_if<common::Indirection<parser::Module>>(&program_.v.front().u)};
-  auto &&source = std::get<parser::Statement<parser::ModuleStmt>>(frontModule->value().t)   .statement.v.source;
-
-
-
+bool Semantics::Perform() {
   // Implicitly USE the __Fortran_builtins module so that special types
   // (e.g., __builtin_team_type) are available to semantics, esp. for
   // intrinsic checking.
     if (intrinsicsMode_) {
       int a = 0;
     } else   if (!program_.v.empty()) {
+        const auto *frontModule{std::get_if<common::Indirection<parser::Module>>(&program_.v.front().u)};
+  auto &&source = std::get<parser::Statement<parser::ModuleStmt>>(frontModule->value().t)   .statement.v.source;
     if (frontModule &&
         (std::get<parser::Statement<parser::ModuleStmt>>(frontModule->value().t)
                     .statement.v.source == "__fortran_builtins" ||
diff --git a/flang/test/Driver/intrinsic-module-path.f90 b/flang/test/Driver/intrinsic-module-path.f90
index 8fe486cf61c83..5e1ce487bc113 100644
--- a/flang/test/Driver/intrinsic-module-path.f90
+++ b/flang/test/Driver/intrinsic-module-path.f90
@@ -8,6 +8,10 @@
 !-----------------------------------------
 ! RUN: %flang_fc1 -fsyntax-only %s  2>&1 | FileCheck %s --allow-empty --check-prefix=WITHOUT
 ! RUN: not %flang_fc1 -fsyntax-only -fintrinsic-modules-path %S/Inputs/ %s  2>&1 | FileCheck %s --check-prefix=GIVEN
+! RUNx: %flang_fc1 -fsyntax-only -fintrinsic-modules-path %S/Inputs/ %s  2>&1 | FileCheck %s --check-prefix=GIVEN
+! RUNx: %flang_fc1 -fsyntax-only -fintrinsic-modules-path %S/Inputs/ %s  2>&1 > %S/out.log
+! RUNx: FileCheck %s --check-prefix=GIVEN --input-file=%S/out.log
+! RUNx: false
 
 ! WITHOUT-NOT: 'ieee_arithmetic.mod' was not found
 ! WITHOUT-NOT: 'iso_fortran_env.mod' was not found

>From 770973955e9c4dcfa72c1137fef778155da36c62 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Thu, 20 Mar 2025 15:10:14 +0100
Subject: [PATCH 09/13] Adapt to real 16

---
 flang-rt/lib/runtime/CMakeLists.txt | 20 ++++++++++++++++++++
 runtimes/CMakeLists.txt             |  2 +-
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index caa5b0d0a95f9..b16d8ef64837f 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -13,6 +13,26 @@ set(HAVE_BACKTRACE ${Backtrace_FOUND})
 set(BACKTRACE_HEADER ${Backtrace_HEADER})
 
 
+include(CheckFortranSourceCompiles)
+include(CMakePushCheckState)
+
+cmake_push_check_state(RESET)
+set(CMAKE_REQUIRED_FLAGS "-ffree-form")
+check_fortran_source_compiles([[
+    program quadmath
+      real(16) :: var1
+      print *, 'Hello'
+    end
+  ]]
+  FORTRAN_SUPPORTS_REAL16
+)
+cmake_pop_check_state()
+
+message("FORTRAN_SUPPORTS_REAL16: ${FORTRAN_SUPPORTS_REAL16}")
+if  (FORTRAN_SUPPORTS_REAL16)
+  add_compile_definitions(FLANG_SUPPORT_R16=1)
+endif ()
+
 # List of files that are buildable for all devices.
 set(supported_sources
   ${FLANG_SOURCE_DIR}/lib/Decimal/binary-to-decimal.cpp
diff --git a/runtimes/CMakeLists.txt b/runtimes/CMakeLists.txt
index 7f1e2ae065d6c..74ed9695d83a9 100644
--- a/runtimes/CMakeLists.txt
+++ b/runtimes/CMakeLists.txt
@@ -144,7 +144,7 @@ if (CXX_SUPPORTS_UNWINDLIB_EQ_NONE_FLAG)
   # below.
   check_c_compiler_flag("--start-no-unused-arguments" C_SUPPORTS_START_NO_UNUSED_ARGUMENTS)
   if (C_SUPPORTS_START_NO_UNUSED_ARGUMENTS)
-    set(CMAKE_REQUIRED_FLAGS "${ORIG_CMAKE_REQUIRED_FLAGS} --start-no-unused-arguments --unwindlib=none --end-no-unused-arguments")
+    set(CMAKE_REQUIRED_FLAGS "${ORIG_CMAKE_REQUIRED_FLAGS} --start-no-unused-arguments> --unwindlib=none --end-no-unused-arguments")
   endif()
 endif()
 

>From 2eb56e4293b3018a6425d92b52ca606414f0097a Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Fri, 21 Mar 2025 10:11:40 +0100
Subject: [PATCH 10/13] WIP

---
 flang-rt/lib/runtime/CMakeLists.txt      | 11 +++++++----
 flang-rt/lib/runtime/__cuda_builtins.f90 |  2 +-
 flang-rt/lib/runtime/cudadevice.f90      |  5 +----
 flang/lib/Semantics/resolve-names.cpp    |  8 +++++++-
 4 files changed, 16 insertions(+), 10 deletions(-)

diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index b16d8ef64837f..2db421f74aa05 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -122,18 +122,21 @@ set(host_sources
 )
 
 
-# Stop CMake from ignoring dependencies between builtin-modules. CMake added this just for (classic) Flang.
+# Stop CMake from ignoring dependencies between builtin-modules. CMake added this feature for (classic) Flang.
 # Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
 set(Fortran_BUILDING_INTRINSIC_MODULES TRUE)
 set(Fortran_BUILDING_INSTRINSIC_MODULES TRUE)
 
 
-set_source_files_properties(cudadevice.f90
-  PROPERTIES COMPILE_OPTIONS "-xcuda"
+set_source_files_properties(
+  __cuda_device.f90
+  cudadevice.f90
+  PROPERTIES COMPILE_OPTIONS "-xcuda;-fsyntax-only"
 )
 set_source_files_properties(
+  __ppc_types.f90
+  __ppc_intrinsics.f90
   mma.f90
-  cudadevice.f90
   PROPERTIES Fortran_PREPROCESS OFF
 )
 
diff --git a/flang-rt/lib/runtime/__cuda_builtins.f90 b/flang-rt/lib/runtime/__cuda_builtins.f90
index 63a661e565e41..68c67fa756fe2 100644
--- a/flang-rt/lib/runtime/__cuda_builtins.f90
+++ b/flang-rt/lib/runtime/__cuda_builtins.f90
@@ -28,4 +28,4 @@
     blockIdx, &
     gridDim, &
     warpsize
-end module
+end module
\ No newline at end of file
diff --git a/flang-rt/lib/runtime/cudadevice.f90 b/flang-rt/lib/runtime/cudadevice.f90
index 79f3b598590c3..fa6185d012f21 100644
--- a/flang-rt/lib/runtime/cudadevice.f90
+++ b/flang-rt/lib/runtime/cudadevice.f90
@@ -8,10 +8,7 @@
 
 ! CUDA Fortran procedures available in device subprogram
 
-! MK: rename to cudadevice.cuf ?
-
 module cudadevice
-  use __cuda_builtins
   use __cuda_device
   use, intrinsic :: __fortran_builtins, only: dim3 => __builtin_dim3
   use, intrinsic :: __fortran_builtins, only: c_devptr => __builtin_c_devptr
@@ -1591,4 +1588,4 @@ attributes(device) integer function match_any_syncjd(mask, val)
     end subroutine
   end interface
 
-end module
+end module
\ No newline at end of file
diff --git a/flang/lib/Semantics/resolve-names.cpp b/flang/lib/Semantics/resolve-names.cpp
index bd40fac52830a..03810a5aae6f3 100644
--- a/flang/lib/Semantics/resolve-names.cpp
+++ b/flang/lib/Semantics/resolve-names.cpp
@@ -40,11 +40,14 @@
 #include "flang/Support/Fortran.h"
 #include "flang/Support/default-kinds.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/Debug.h"
 #include <list>
 #include <map>
 #include <set>
 #include <stack>
 
+#define DEBUG_TYPE "flang"
+
 namespace llvm {
  extern cl::opt<bool> FlangIntrinsicsMode;
  }
@@ -3900,12 +3903,15 @@ void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) {
   prevAccessStmt_ = std::nullopt;
 }
 
-// Find a module or submodule by name and return its scope.
+// Find a module or submodule by name and return its scope. 
 // If ancestor is present, look for a submodule of that ancestor module.
 // May have to read a .mod file to find it.
 // If an error occurs, report it and return nullptr.
 Scope *ModuleVisitor::FindModule(const parser::Name &name,
     std::optional<bool> isIntrinsic, Scope *ancestor) {
+ //LLVM_DEBUG( 
+   llvm::errs() << "FindModule(" << name.ToString() << ", " << isIntrinsic << ")\n";
+// );
   ModFileReader reader{context()};
   Scope *scope{
       reader.Read(name.source, isIntrinsic, ancestor, /*silent=*/false)};

>From 8fc3ba2e959d6ecb6fc92ebeb7d2d5fe0a5a1c39 Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Fri, 21 Mar 2025 13:30:52 +0100
Subject: [PATCH 11/13] CUDA-Fortran only

---
 flang-rt/lib/runtime/CMakeLists.txt       | 59 +++++++++++-----
 flang-rt/lib/runtime/__cuda_builtins.f90  |  2 +-
 flang-rt/lib/runtime/__ppc_intrinsics.f90 | 75 +++++---------------
 flang-rt/lib/runtime/cudadevice.f90       |  2 +-
 flang-rt/lib/runtime/mma.f90              | 85 ++++++++---------------
 flang/include/flang/Parser/parse-tree.h   | 22 +++++-
 flang/lib/Semantics/resolve-names.cpp     |  6 +-
 7 files changed, 111 insertions(+), 140 deletions(-)

diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index 2db421f74aa05..63d086da9b8af 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -92,12 +92,9 @@ set(supported_sources
 # List of source not used for GPU offloading.
 set(CMAKE_Fortran_MODULE_DIRECTORY "${LLVM_LIBRARY_OUTPUT_INTDIR}/../include/flang")
 set(host_sources
-  __cuda_builtins.f90
-  __cuda_device.f90
   __fortran_builtins.f90
   __fortran_ieee_exceptions.f90
   __fortran_type_info.f90
-  cudadevice.f90
   ieee_arithmetic.f90
   ieee_exceptions.f90
   ieee_features.f90
@@ -122,35 +119,46 @@ set(host_sources
 )
 
 
-# Stop CMake from ignoring dependencies between builtin-modules. CMake added this feature for (classic) Flang.
-# Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
-set(Fortran_BUILDING_INTRINSIC_MODULES TRUE)
-set(Fortran_BUILDING_INSTRINSIC_MODULES TRUE)
 
+message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
+message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
+if (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
+  list(APPEND host_source
+    __ppc_types.f90
+    __ppc_intrinsics.f90
+    mma.f90
+  )
+endif ()
+
+if (FLANG_RT_EXPERIMENTAL_OFFLOAD_SUPPORT STREQUAL "CUDA")
+  list(APPEND supported_sources
+    __cuda_builtins.f90
+    __cuda_device.f90
+    cudadevice.f90
+    mma.f90
+  )
 
+# FIXME: Has CMake support for CUDA-Fortran?
+# Open question: __cuda_builtins.f90 does not need -xcuda?
 set_source_files_properties(
   __cuda_device.f90
   cudadevice.f90
-  PROPERTIES COMPILE_OPTIONS "-xcuda;-fsyntax-only"
+  PROPERTIES COMPILE_OPTIONS "-xcuda"
 )
+endif ()
+
+
+
+# Flang is not always able to consume its own preprocessor output
 set_source_files_properties(
-  __ppc_types.f90
-  __ppc_intrinsics.f90
   mma.f90
+  cudadevice.f90
   PROPERTIES Fortran_PREPROCESS OFF
 )
 
 
 
-message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
-message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
-if (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
-  list(APPEND host_source
-    __ppc_types.f90
-    __ppc_intrinsics.f90
-    mma.f90
-  )
-endif ()
+
 
 add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
 
@@ -197,12 +205,22 @@ endif ()
 set(sources ${supported_sources} ${host_sources} ${f128_sources})
 
 
+# Stop CMake from ignoring dependencies between builtin-modules. CMake added this feature for (classic) Flang.
+# Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
+set(Fortran_BUILDING_INTRINSIC_MODULES TRUE)
+set(Fortran_BUILDING_INSTRINSIC_MODULES TRUE)
+
+
 if (NOT WIN32)
   add_flangrt_library(flang_rt.runtime STATIC SHARED
     ${sources}
     LINK_LIBRARIES ${Backtrace_LIBRARY}
     INSTALL_WITH_TOOLCHAIN
     ADDITIONAL_HEADERS ${public_headers} ${private_headers}
+    TARGET_PROPERTIES
+      # Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
+      Fortran_BUILDING_INTRINSIC_MODULES TRUE
+      Fortran_BUILDING_INSTRINSIC_MODULES TRUE
   )
 
   enable_cuda_compilation(flang_rt.runtime "${supported_sources}")
@@ -224,6 +242,9 @@ else()
         ${ARGN}
         LINK_LIBRARIES ${Backtrace_LIBRARY}
         ADDITIONAL_HEADERS ${public_headers} ${private_headers}
+        TARGET_PROPERTIES
+          Fortran_BUILDING_INTRINSIC_MODULES TRUE
+          Fortran_BUILDING_INSTRINSIC_MODULES TRUE
       )
 # "$<$<COMPILE_LANGUAGE:Fortran>:-Xflang>"
 #TODO: Better as -fintrinsic-modules-path, need added option
diff --git a/flang-rt/lib/runtime/__cuda_builtins.f90 b/flang-rt/lib/runtime/__cuda_builtins.f90
index 68c67fa756fe2..63a661e565e41 100644
--- a/flang-rt/lib/runtime/__cuda_builtins.f90
+++ b/flang-rt/lib/runtime/__cuda_builtins.f90
@@ -28,4 +28,4 @@
     blockIdx, &
     gridDim, &
     warpsize
-end module
\ No newline at end of file
+end module
diff --git a/flang-rt/lib/runtime/__ppc_intrinsics.f90 b/flang-rt/lib/runtime/__ppc_intrinsics.f90
index 1ec134261c2ed..b3ff33b0619ff 100644
--- a/flang-rt/lib/runtime/__ppc_intrinsics.f90
+++ b/flang-rt/lib/runtime/__ppc_intrinsics.f90
@@ -55,24 +55,13 @@ elemental vector(real(VKIND)) function elem_func_vr##VKIND##r##VKIND(arg1); \
     real(VKIND), intent(in) :: arg1; \
   end function ;
 
-  ELEM_FUNC_VIVI(1)
-  ELEM_FUNC_VIVI(2)
-  ELEM_FUNC_VIVI(4)
-  ELEM_FUNC_VIVI(8)
+  ELEM_FUNC_VIVI(1) ELEM_FUNC_VIVI(2) ELEM_FUNC_VIVI(4) ELEM_FUNC_VIVI(8)
   ELEM_FUNC_VUVU(1)
-  ELEM_FUNC_VRVR_2(4,8)
-  ELEM_FUNC_VRVR_2(8,4)
-  ELEM_FUNC_VRVR(4)
-  ELEM_FUNC_VRVR(8)
-  ELEM_FUNC_VII_2(4,1)
-  ELEM_FUNC_VII_2(4,2)
-  ELEM_FUNC_VII_2(4,8)
-  ELEM_FUNC_VII(1)
-  ELEM_FUNC_VII(2)
-  ELEM_FUNC_VII(4)
-  ELEM_FUNC_VII(8)
-  ELEM_FUNC_VRR(4)
-  ELEM_FUNC_VRR(8)
+  ELEM_FUNC_VRVR_2(4,8) ELEM_FUNC_VRVR_2(8,4)
+  ELEM_FUNC_VRVR(4) ELEM_FUNC_VRVR(8)
+  ELEM_FUNC_VII_2(4,1) ELEM_FUNC_VII_2(4,2) ELEM_FUNC_VII_2(4,8)
+  ELEM_FUNC_VII(1) ELEM_FUNC_VII(2) ELEM_FUNC_VII(4) ELEM_FUNC_VII(8)
+  ELEM_FUNC_VRR(4) ELEM_FUNC_VRR(8)
 
 #undef ELEM_FUNC_VRR
 #undef ELEM_FUNC_VII
@@ -333,16 +322,9 @@ pure vector(real(VKIND)) function func_vec_convert_vr##VKIND##vi##vr##VKIND(v, m
     !dir$ ignore_tkr(r) mold; \
   end function ;
 
-  FUNC_VEC_CONVERT_VIVIVI(1)
-  FUNC_VEC_CONVERT_VIVIVI(2)
-  FUNC_VEC_CONVERT_VIVIVI(4)
-  FUNC_VEC_CONVERT_VIVIVI(8)
-  FUNC_VEC_CONVERT_VUVIVU(1)
-  FUNC_VEC_CONVERT_VUVIVU(2)
-  FUNC_VEC_CONVERT_VUVIVU(4)
-  FUNC_VEC_CONVERT_VUVIVU(8)
-  FUNC_VEC_CONVERT_VRVIVR(4)
-  FUNC_VEC_CONVERT_VRVIVR(8)
+  FUNC_VEC_CONVERT_VIVIVI(1) FUNC_VEC_CONVERT_VIVIVI(2) FUNC_VEC_CONVERT_VIVIVI(4) FUNC_VEC_CONVERT_VIVIVI(8)
+  FUNC_VEC_CONVERT_VUVIVU(1) FUNC_VEC_CONVERT_VUVIVU(2) FUNC_VEC_CONVERT_VUVIVU(4) FUNC_VEC_CONVERT_VUVIVU(8)
+  FUNC_VEC_CONVERT_VRVIVR(4) FUNC_VEC_CONVERT_VRVIVR(8)
   ELEM_FUNC_IVII(1) ELEM_FUNC_IVII(2) ELEM_FUNC_IVII(4) ELEM_FUNC_IVII(8)
   ELEM_FUNC_RVRI(4) ELEM_FUNC_RVRI(8)
   ELEM_FUNC_VIVIVI(1) ELEM_FUNC_VIVIVI(2) ELEM_FUNC_VIVIVI(4) ELEM_FUNC_VIVIVI(8)
@@ -629,36 +611,15 @@ pure subroutine sub_vpi0r0(arg1, arg2, arg3)
     !dir$ ignore_tkr(kr) arg3
   end subroutine
 
-  SUB_VIIVI(1)
-  SUB_VIIVI(2)
-  SUB_VIIVI(4)
-  SUB_VIIVI(8)
-  SUB_VUIVU(1)
-  SUB_VUIVU(2)
-  SUB_VUIVU(4)
-  SUB_VUIVU(8)
-  SUB_VRIVR(4)
-  SUB_VRIVR(8)
-  SUB_VIII(1)
-  SUB_VIII(2)
-  SUB_VIII(4)
-  SUB_VIII(8)
-  SUB_VUII(1)
-  SUB_VUII(2)
-  SUB_VUII(4)
-  SUB_VUII(8)
-  SUB_VRIR(4)
-  SUB_VRIR(8)
-  SUB_VPI0VI(1)
-  SUB_VPI0VI(2)
-  SUB_VPI0VI(4)
-  SUB_VPI0VI(8)
-  SUB_VPI0VU(1)
-  SUB_VPI0VU(2)
-  SUB_VPI0VU(4)
-  SUB_VPI0VU(8)
-  SUB_VPI0VR(4)
-  SUB_VPI0VR(8)
+  SUB_VIIVI(1) SUB_VIIVI(2) SUB_VIIVI(4) SUB_VIIVI(8)
+  SUB_VUIVU(1) SUB_VUIVU(2) SUB_VUIVU(4) SUB_VUIVU(8)
+  SUB_VRIVR(4) SUB_VRIVR(8)
+  SUB_VIII(1) SUB_VIII(2) SUB_VIII(4) SUB_VIII(8)
+  SUB_VUII(1) SUB_VUII(2) SUB_VUII(4) SUB_VUII(8)
+  SUB_VRIR(4) SUB_VRIR(8)
+  SUB_VPI0VI(1) SUB_VPI0VI(2) SUB_VPI0VI(4) SUB_VPI0VI(8)
+  SUB_VPI0VU(1) SUB_VPI0VU(2) SUB_VPI0VU(4) SUB_VPI0VU(8)
+  SUB_VPI0VR(4) SUB_VPI0VR(8)
 
 #undef SUB_VPI0VR
 #undef SUB_VPI0VU
diff --git a/flang-rt/lib/runtime/cudadevice.f90 b/flang-rt/lib/runtime/cudadevice.f90
index fa6185d012f21..baaa112f5d8c2 100644
--- a/flang-rt/lib/runtime/cudadevice.f90
+++ b/flang-rt/lib/runtime/cudadevice.f90
@@ -1588,4 +1588,4 @@ attributes(device) integer function match_any_syncjd(mask, val)
     end subroutine
   end interface
 
-end module
\ No newline at end of file
+end module
diff --git a/flang-rt/lib/runtime/mma.f90 b/flang-rt/lib/runtime/mma.f90
index 2957d39c8e61f..4c41822e000a3 100644
--- a/flang-rt/lib/runtime/mma.f90
+++ b/flang-rt/lib/runtime/mma.f90
@@ -55,16 +55,9 @@ pure __vector_pair function func_vpi0vp(arg1, arg2); \
     !dir$ ignore_tkr(r) arg2; \
   end function;
 
-  FUNC_VPI0VI(1)
-  FUNC_VPI0VI(2)
-  FUNC_VPI0VI(4)
-  FUNC_VPI0VI(8)
-  FUNC_VPI0VU(1)
-  FUNC_VPI0VU(2)
-  FUNC_VPI0VU(4)
-  FUNC_VPI0VU(8)
-  FUNC_VPI0VR(4)
-  FUNC_VPI0VR(8)
+  FUNC_VPI0VI(1) FUNC_VPI0VI(2) FUNC_VPI0VI(4) FUNC_VPI0VI(8)
+  FUNC_VPI0VU(1) FUNC_VPI0VU(2) FUNC_VPI0VU(4) FUNC_VPI0VU(8)
+  FUNC_VPI0VR(4) FUNC_VPI0VR(8)
   FUNC_VPI0VP
 
 #undef FUNC_VPI0VP
@@ -75,12 +68,11 @@ pure __vector_pair function func_vpi0vp(arg1, arg2); \
 !! ========== 3 arguments subroutine interface ===============================!!
 !! __vector_pair subroutine s(vp, integer, vector(i))
 #define SUB_VPI0VI(VKIND) \
-  pure subroutine sub_vpi0vi##VKIND(arg1, argg2, arg3); \
+  pure subroutine sub_vpi0vi##VKIND(arg1, arg2, arg3); \
     __vector_pair, intent(in) :: arg1; \
-    integer(8), intent(in) :: argg2; \
+    integer(8), intent(in) :: arg2; \
     !dir$ ignore_tkr(k) arg2; \
-    vector(integer(VKIND)), \
-      intent(out) :: arg3; \
+    vector(integer(VKIND)), intent(out) :: arg3; \
     !dir$ ignore_tkr(r) arg3; \
   end subroutine;
 
@@ -152,28 +144,14 @@ elemental subroutine sub_vpvr##VKIND##vr##VKIND(pair, arg1, arg2); \
     vector(real(VKIND)), intent(in) :: arg1, arg2; \
   end subroutine ;
 
-  ELEM_SUB_VPVIVI(1)
-  ELEM_SUB_VPVIVI(2)
-  ELEM_SUB_VPVIVI(4)
-  ELEM_SUB_VPVIVI(8)
-  ELEM_SUB_VPVUVU(1)
-  ELEM_SUB_VPVUVU(2)
-  ELEM_SUB_VPVUVU(4)
-  ELEM_SUB_VPVUVU(8)
-  ELEM_SUB_VPVRVR(4)
-  ELEM_SUB_VPVRVR(8)
-
-  SUB_VPI0VI(1)
-
-!!  SUB_VPI0VI(2)
-!!  SUB_VPI0VI(4)
-!!  SUB_VPI0VI(8)
-!!  SUB_VPI0VU(1)
-!!  SUB_VPI0VU(2)
-!!  SUB_VPI0VU(4)
-!!  SUB_VPI0VU(8)
-!!  SUB_VPI0VR(4)
-!!  SUB_VPI0VR(8)
+  ELEM_SUB_VPVIVI(1) ELEM_SUB_VPVIVI(2)
+  ELEM_SUB_VPVIVI(4) ELEM_SUB_VPVIVI(8)
+  ELEM_SUB_VPVUVU(1) ELEM_SUB_VPVUVU(2)
+  ELEM_SUB_VPVUVU(4) ELEM_SUB_VPVUVU(8)
+  ELEM_SUB_VPVRVR(4) ELEM_SUB_VPVRVR(8)
+  SUB_VPI0VI(1) SUB_VPI0VI(2) SUB_VPI0VI(4) SUB_VPI0VI(8)
+  SUB_VPI0VU(1) SUB_VPI0VU(2) SUB_VPI0VU(4) SUB_VPI0VU(8)
+  SUB_VPI0VR(4) SUB_VPI0VR(8)
 
 #undef ELEM_SUB_VPVIVI
 #undef ELEM_SUB_VPVUVU
@@ -203,12 +181,10 @@ elemental subroutine sub_vq##INTENT##vr##VKIND##vr##VKIND(acc, a, b); \
     vector(real(VKIND)), intent(in) :: a, b; \
   end subroutine ;
 
-  ELEM_SUB_VQVIVI(inout,1)
-  ELEM_SUB_VQVIVI(inout,2)
+  ELEM_SUB_VQVIVI(inout,1) ELEM_SUB_VQVIVI(inout,2)
   ELEM_SUB_VQVUVU(inout,1)
   ELEM_SUB_VQVRVR(inout,4)
-  ELEM_SUB_VQVIVI(out,1)
-  ELEM_SUB_VQVIVI(out,2)
+  ELEM_SUB_VQVIVI(out,1) ELEM_SUB_VQVIVI(out,2)
   ELEM_SUB_VQVUVU(out,1)
   ELEM_SUB_VQVRVR(out,4)
 
@@ -262,16 +238,11 @@ elemental subroutine sub_vqvr##VKIND##vr##VKIND##vr##VKIND##vr##VKIND(acc, arg1,
     vector(real(VKIND)), intent(in) :: arg1, arg2, arg3, arg4; \
   end subroutine ;
 
-  ELEM_SUB_VQVIVIVIVI(1)
-  ELEM_SUB_VQVIVIVIVI(2)
-  ELEM_SUB_VQVIVIVIVI(4)
-  ELEM_SUB_VQVIVIVIVI(8)
-  ELEM_SUB_VQVUVUVUVU(1)
-  ELEM_SUB_VQVUVUVUVU(2)
-  ELEM_SUB_VQVUVUVUVU(4)
-  ELEM_SUB_VQVUVUVUVU(8)
-  ELEM_SUB_VQVRVRVRVR(4)
-  ELEM_SUB_VQVRVRVRVR(8)
+  ELEM_SUB_VQVIVIVIVI(1) ELEM_SUB_VQVIVIVIVI(2)
+  ELEM_SUB_VQVIVIVIVI(4) ELEM_SUB_VQVIVIVIVI(8)
+  ELEM_SUB_VQVUVUVUVU(1) ELEM_SUB_VQVUVUVUVU(2)
+  ELEM_SUB_VQVUVUVUVU(4) ELEM_SUB_VQVUVUVUVU(8)
+  ELEM_SUB_VQVRVRVRVR(4) ELEM_SUB_VQVRVRVRVR(8)
 
 #undef ELEM_SUB_VQVRVRVRVR
 #undef ELEM_SUB_VQVUVUVUVU
@@ -279,21 +250,21 @@ elemental subroutine sub_vqvr##VKIND##vr##VKIND##vr##VKIND##vr##VKIND(acc, arg1,
 
 !! subroutine s(__vector_quad, vector(u), vector(u), integer, integer)
 #define ELEM_SUB_VQVUVUII(INTENT, VKIND) \
-  elemental subroutine sub_vq##INTENT##vu##VKIND##vu##VKIND##ii(acc, a, b, xmaskkkk, ymaskk); \
+  elemental subroutine sub_vq##INTENT##vu##VKIND##vu##VKIND##ii(acc, a, b, xmask, ymask); \
     __vector_quad, intent(INTENT) :: acc; \
     vector(unsigned(VKIND)), intent(in) :: a, b; \
-    integer(8), intent(in) :: xmaskkkk, ymaskk; \
-    !dir$ ignore_tkr(k) xmaskkkk; \
-    !dir$ ignore_tkr(k) ymaskk; \
+    integer(8), intent(in) :: xmask, ymask; \
+    !dir$ ignore_tkr(k) xmask; \
+    !dir$ ignore_tkr(k) ymask; \
   end subroutine ;
 
 !! subroutine s(__vector_quad, vector(r), vector(r), integer, integer)
 #define ELEM_SUB_VQVRVRII(INTENT, VKIND) \
-  elemental subroutine sub_vq##INTENT##vr##VKIND##vr##VKIND##ii(acc, a, b, xmaskkkk, ymask); \
+  elemental subroutine sub_vq##INTENT##vr##VKIND##vr##VKIND##ii(acc, a, b, xmask, ymask); \
     __vector_quad, intent(INTENT) :: acc; \
     vector(real(VKIND)), intent(in) :: a, b; \
-    integer(8), intent(in) :: xmaskkkk, ymask; \
-    !dir$ ignore_tkr(k) xmaskkkk; \
+    integer(8), intent(in) :: xmask, ymask; \
+    !dir$ ignore_tkr(k) xmask; \
     !dir$ ignore_tkr(k) ymask; \
   end subroutine ;
 
diff --git a/flang/include/flang/Parser/parse-tree.h b/flang/include/flang/Parser/parse-tree.h
index 1b1d4125464e3..db37b1a474ee1 100644
--- a/flang/include/flang/Parser/parse-tree.h
+++ b/flang/include/flang/Parser/parse-tree.h
@@ -3353,9 +3353,27 @@ struct StmtFunctionStmt {
 // !DIR$ UNROLL_AND_JAM [N]
 // !DIR$ <anything else>
 struct CompilerDirective {
-  UNION_CLASS_BOILERPLATE(CompilerDirective);
+  template <typename A, typename = common::NoLvalue<A>>
+  CompilerDirective(A &&x) : u(std::move(x)) {
+  int a = 0;
+  }
+  using UnionTrait = std::true_type;
+  CompilerDirective(CompilerDirective &&) = default;
+  CompilerDirective &operator=(CompilerDirective &&) = default;
+  CompilerDirective(const CompilerDirective &) = delete;
+  CompilerDirective &operator=(const CompilerDirective &) = delete;
+  CompilerDirective() = delete;
   struct IgnoreTKR {
-    TUPLE_CLASS_BOILERPLATE(IgnoreTKR);
+    template <typename... Ts, typename = common::NoLvalue<Ts...>>
+    IgnoreTKR(Ts &&...args) : t(std::move(args)...) {
+    int b = 0;
+    }
+    using TupleTrait = std::true_type;
+    IgnoreTKR(IgnoreTKR &&) = default;
+    IgnoreTKR &operator=(IgnoreTKR &&) = default;
+    IgnoreTKR(const IgnoreTKR &) = delete;
+    IgnoreTKR &operator=(const IgnoreTKR &) = delete;
+    IgnoreTKR() = delete;
     std::tuple<std::optional<std::list<const char *>>, Name> t;
   };
   struct LoopCount {
diff --git a/flang/lib/Semantics/resolve-names.cpp b/flang/lib/Semantics/resolve-names.cpp
index 03810a5aae6f3..8a017b533d9aa 100644
--- a/flang/lib/Semantics/resolve-names.cpp
+++ b/flang/lib/Semantics/resolve-names.cpp
@@ -3909,9 +3909,9 @@ void ModuleVisitor::BeginModule(const parser::Name &name, bool isSubmodule) {
 // If an error occurs, report it and return nullptr.
 Scope *ModuleVisitor::FindModule(const parser::Name &name,
     std::optional<bool> isIntrinsic, Scope *ancestor) {
- //LLVM_DEBUG( 
-   llvm::errs() << "FindModule(" << name.ToString() << ", " << isIntrinsic << ")\n";
-// );
+ LLVM_DEBUG( 
+   llvm::errs() << "FindModule(" << name.ToString() << ", " << isIntrinsic << ")\n"
+ );
   ModFileReader reader{context()};
   Scope *scope{
       reader.Read(name.source, isIntrinsic, ancestor, /*silent=*/false)};

>From 299d18b1f79d5a5cd1afb8074fec7171603ba16e Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Sat, 22 Mar 2025 00:04:47 +0100
Subject: [PATCH 12/13] Leftovers

---
 flang-rt/cmake/modules/AddFlangRT.cmake      |  1 +
 flang-rt/lib/runtime/CMakeLists.txt          | 19 ++++++++++++++-----
 flang-rt/lib/runtime/__fortran_builtins.f90  |  2 +-
 flang-rt/lib/runtime/__fortran_type_info.f90 |  7 +++++--
 4 files changed, 21 insertions(+), 8 deletions(-)

diff --git a/flang-rt/cmake/modules/AddFlangRT.cmake b/flang-rt/cmake/modules/AddFlangRT.cmake
index 41c8240172ff1..d08cc9a4ef788 100644
--- a/flang-rt/cmake/modules/AddFlangRT.cmake
+++ b/flang-rt/cmake/modules/AddFlangRT.cmake
@@ -320,6 +320,7 @@ function (add_flangrt_library name)
     endif ()
 
     if (ARG_TARGET_PROPERTIES)
+message("Setting target properties of ${tgtname}: ${ARG_TARGET_PROPERTIES}" )
       set_target_properties(${tgtname} PROPERTIES ${ARG_TARGET_PROPERTIES})
     endif ()
 
diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index 63d086da9b8af..f79c02eef39eb 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -120,6 +120,10 @@ set(host_sources
 
 
 
+#set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "/home/meinersbur/build/llvm-project-flangrt/release_bootstrap/llvm_flang_runtimes/./lib/../include/flang/__fortran_builtins.mod")
+set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "flang-rt/lib/runtime/CMakeFiles/flang_rt.runtime.static.dir/__fortran_builtins.f90.o")
+#set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "/home/meinersbur/build/llvm-project-flangrt/release_bootstrap/llvm_flang_runtimes/./lib/../include/flang/__fortran_builtins.mod")
+
 message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
 message("CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
 if (CMAKE_SYSTEM_PROCESSOR STREQUAL "powerpc")
@@ -139,11 +143,12 @@ if (FLANG_RT_EXPERIMENTAL_OFFLOAD_SUPPORT STREQUAL "CUDA")
   )
 
 # FIXME: Has CMake support for CUDA-Fortran?
-# Open question: __cuda_builtins.f90 does not need -xcuda?
+# FIXME: __cuda_builtins.f90 does not need -xcuda?
 set_source_files_properties(
-  __cuda_device.f90
-  cudadevice.f90
-  PROPERTIES COMPILE_OPTIONS "-xcuda"
+    __cuda_device.f90
+    cudadevice.f90
+  PROPERTIES
+    COMPILE_OPTIONS "-xcuda"
 )
 endif ()
 
@@ -166,6 +171,9 @@ add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:F
 #set(CMAKE_Fortran_PREPROCESS FALSE)
 #add_compile_options(-mllvm -ignore-missing-type-desc)
 
+set(CMAKE_Fortran_BUILDING_INTRINSIC_MODULES TRUE)
+set(CMAKE_Fortran_BUILDING_INSTRINSIC_MODULES TRUE)
+
 file(GLOB_RECURSE public_headers
   "${FLANG_RT_SOURCE_DIR}/include/flang_rt/*.h"
   "${FLANG_SOURCE_DIR}/include/flang/Common/*.h"
@@ -219,6 +227,7 @@ if (NOT WIN32)
     ADDITIONAL_HEADERS ${public_headers} ${private_headers}
     TARGET_PROPERTIES
       # Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
+      # Supported only since CMake 3.22
       Fortran_BUILDING_INTRINSIC_MODULES TRUE
       Fortran_BUILDING_INSTRINSIC_MODULES TRUE
   )
@@ -248,7 +257,7 @@ else()
       )
 # "$<$<COMPILE_LANGUAGE:Fortran>:-Xflang>"
 #TODO: Better as -fintrinsic-modules-path, need added option
-    target_compile_options(${name} PRIVATE  "$<$<COMPILE_LANGUAGE:Fortran>:SHELL:-fintrinsic-modules-path>" "$<$<COMPILE_LANGUAGE:Fortran>:${CMAKE_CURRENT_BINARY_DIR}/module.${suffix}>")
+    target_compile_options(${name} PRIVATE "$<$<COMPILE_LANGUAGE:Fortran>:SHELL:-fintrinsic-modules-path>" "$<$<COMPILE_LANGUAGE:Fortran>:${CMAKE_CURRENT_BINARY_DIR}/module.${suffix}>")
 
     if (msvc_lib)
       set_target_properties(${name}
diff --git a/flang-rt/lib/runtime/__fortran_builtins.f90 b/flang-rt/lib/runtime/__fortran_builtins.f90
index 7bb078c0b428e..d5e55b5d95020 100644
--- a/flang-rt/lib/runtime/__fortran_builtins.f90
+++ b/flang-rt/lib/runtime/__fortran_builtins.f90
@@ -12,7 +12,7 @@
 ! from being usable on INTRINSIC statements, and force the program
 ! to USE the standard intrinsic modules in order to access the
 ! standard names of the procedures.
-module __fortran_builtins
+module    __fortran_builtins
   implicit none
 
   ! Set PRIVATE by default to explicitly only export what is meant
diff --git a/flang-rt/lib/runtime/__fortran_type_info.f90 b/flang-rt/lib/runtime/__fortran_type_info.f90
index b30a6bf697563..d1cfc09ed67dc 100644
--- a/flang-rt/lib/runtime/__fortran_type_info.f90
+++ b/flang-rt/lib/runtime/__fortran_type_info.f90
@@ -12,8 +12,11 @@
 ! in order to generate description tables for all other derived types.
 
 module __fortran_type_info
-
-  use, intrinsic :: __fortran_builtins, &
+#if 0
+  use       __fortran_builtins, &
+#else
+  use, intrinsic ::    __fortran_builtins, &
+#endif
     only: __builtin_c_ptr, __builtin_c_devptr, __builtin_c_funptr
   implicit none
 

>From 6991afb61f2f625b6e7060d3556033a1f24ed27f Mon Sep 17 00:00:00 2001
From: Michael Kruse <llvm-project at meinersbur.de>
Date: Tue, 1 Apr 2025 16:18:03 +0200
Subject: [PATCH 13/13] Leftovers

---
 clang/include/clang/Driver/ToolChain.h        | 13 ++++
 clang/lib/Driver/ToolChain.cpp                | 22 ++++++
 clang/lib/Driver/ToolChains/Flang.cpp         |  8 +++
 flang-rt/CMakeLists.txt                       | 13 +++-
 flang-rt/cmake/modules/AddFlangRT.cmake       |  1 +
 flang-rt/cmake/modules/GetToolchainDirs.cmake | 10 +++
 flang-rt/lib/runtime/CMakeLists.txt           | 32 ++++++---
 .../flang/Frontend/CompilerInvocation.h       |  2 +
 .../flang/Frontend/PreprocessorOptions.h      |  1 +
 flang/lib/Frontend/CompilerInvocation.cpp     | 26 +++++--
 flang/lib/Semantics/check-omp-structure.cpp   | 71 ++++++++++---------
 11 files changed, 153 insertions(+), 46 deletions(-)

diff --git a/clang/include/clang/Driver/ToolChain.h b/clang/include/clang/Driver/ToolChain.h
index 90004c64a694a..62ccad5172764 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -157,6 +157,9 @@ class ToolChain {
   /// The list of toolchain specific path prefixes to search for programs.
   path_list ProgramPaths;
 
+    path_list ModulePaths;
+        path_list IntrinsicModulePaths;
+
   mutable std::unique_ptr<Tool> Clang;
   mutable std::unique_ptr<Tool> Flang;
   mutable std::unique_ptr<Tool> Assemble;
@@ -297,6 +300,12 @@ class ToolChain {
   path_list &getProgramPaths() { return ProgramPaths; }
   const path_list &getProgramPaths() const { return ProgramPaths; }
 
+      path_list &getModulePaths() { return ModulePaths; }
+  const path_list &getModulePaths() const { return ModulePaths; }
+
+    path_list &getIntrinsicModulePaths() { return IntrinsicModulePaths; }
+  const path_list &getIntrinsicModulePaths() const { return IntrinsicModulePaths; }
+
   const MultilibSet &getMultilibs() const { return Multilibs; }
 
   const llvm::SmallVector<Multilib> &getSelectedMultilibs() const {
@@ -528,6 +537,10 @@ class ToolChain {
   // Returns target specific standard library include path if it exists.
   std::optional<std::string> getStdlibIncludePath() const;
 
+
+  path_list getDefaultIntrinsicModulePaths() const;
+
+
   // Returns <ResourceDir>/lib/<OSName>/<arch> or <ResourceDir>/lib/<triple>.
   // This is used by runtimes (such as OpenMP) to find arch-specific libraries.
   virtual path_list getArchSpecificLibPaths() const;
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 5f75d004eede0..9891d7019bed2 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -102,6 +102,10 @@ ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
     getFilePaths().push_back(*Path);
   for (const auto &Path : getArchSpecificLibPaths())
     addIfExists(getFilePaths(), Path);
+
+  if (D.IsFlangMode()) {
+    getIntrinsicModulePaths().append(getIntrinsicModulePaths());
+  }
 }
 
 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
@@ -928,6 +932,24 @@ std::optional<std::string> ToolChain::getStdlibIncludePath() const {
   return getTargetSubDirPath(P);
 }
 
+ ToolChain:: path_list ToolChain:: getDefaultIntrinsicModulePaths() const{
+    SmallString<128> P(D.ResourceDir);
+  llvm::sys::path::append(P, "finclude");
+
+  // TOOD: If there are multiple valid names for the target triple, prefer to add all of them instead probing which are existing.
+   ToolChain:: path_list Result;
+   if (std::optional<std::string> PerTargetPath = getTargetSubDirPath(P))
+   Result.push_back(*PerTargetPath);
+
+   // flang used this in the past
+     SmallString<128> CompatIntrModPath(D.Dir);
+  llvm::sys::path::append(CompatIntrModPath, "..", "include", "flang");
+     Result.push_back(std::string(CompatIntrModPath));
+
+  return Result ;
+  }
+
+
 ToolChain::path_list ToolChain::getArchSpecificLibPaths() const {
   path_list Paths;
 
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp
index 5dbc5cbe77d0a..54561fb9cb42c 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -914,6 +914,14 @@ void Flang::ConstructJob(Compilation &C, const JobAction &JA,
   CmdArgs.push_back("-resource-dir");
   CmdArgs.push_back(D.ResourceDir.c_str());
 
+  // Must be added after any user-provided -fintrinsic-modules-path
+  for (auto && IntrModPath : TC.getIntrinsicModulePaths()) {
+    CmdArgs.push_back("-fintrinsic-modules-path");
+    CmdArgs.push_back(IntrModPath.c_str());
+  }
+
+
+
   // Offloading related options
   addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
 
diff --git a/flang-rt/CMakeLists.txt b/flang-rt/CMakeLists.txt
index b10398a5ea897..1e8e634dba730 100644
--- a/flang-rt/CMakeLists.txt
+++ b/flang-rt/CMakeLists.txt
@@ -87,6 +87,7 @@ set(LLVM_TOOLS_DIR "${LLVM_BINARY_DIR}/bin")
 # The build path is absolute, but the install dir is relative, CMake's install
 # command has to apply CMAKE_INSTALL_PREFIX itself.
 get_toolchain_library_subdir(toolchain_lib_subdir)
+get_toolchain_module_subdir(toolchain_mod_subdir)
 if (LLVM_TREE_AVAILABLE)
   # In a bootstrap build emit the libraries into a default search path in the
   # build directory of the just-built compiler. This allows using the
@@ -99,6 +100,7 @@ if (LLVM_TREE_AVAILABLE)
   get_clang_resource_dir(FLANG_RT_INSTALL_RESOURCE_PATH_DEFAULT)
 
   extend_path(FLANG_RT_OUTPUT_RESOURCE_LIB_DIR "${FLANG_RT_OUTPUT_RESOURCE_DIR}" "${toolchain_lib_subdir}")
+  extend_path(FLANG_RT_OUTPUT_RESOURCE_MOD_DIR "${FLANG_RT_OUTPUT_RESOURCE_DIR}" "${toolchain_mod_subdir}")
 else ()
   # In a standalone runtimes build, do not write into LLVM_BINARY_DIR. It may be
   # read-only and/or shared by multiple runtimes with different build
@@ -111,10 +113,12 @@ else ()
   set(FLANG_RT_INSTALL_RESOURCE_PATH_DEFAULT "lib${LLVM_LIBDIR_SUFFIX}/clang/${LLVM_VERSION_MAJOR}")
 
   extend_path(FLANG_RT_OUTPUT_RESOURCE_LIB_DIR "${FLANG_RT_OUTPUT_RESOURCE_DIR}" "lib${LLVM_LIBDIR_SUFFIX}")
+  extend_path(FLANG_RT_OUTPUT_RESOURCE_MOD_DIR "${FLANG_RT_OUTPUT_RESOURCE_DIR}" "finclude")
 endif ()
 set(FLANG_RT_INSTALL_RESOURCE_PATH "${FLANG_RT_INSTALL_RESOURCE_PATH_DEFAULT}"
     CACHE PATH "Path to install runtime libraries to (default: clang resource dir)")
 extend_path(FLANG_RT_INSTALL_RESOURCE_LIB_PATH "${FLANG_RT_INSTALL_RESOURCE_PATH}" "${toolchain_lib_subdir}")
+extend_path(FLANG_RT_INSTALL_RESOURCE_MOD_PATH "${FLANG_RT_INSTALL_RESOURCE_PATH}" "${toolchain_mod_subdir}")
 cmake_path(NORMAL_PATH FLANG_RT_OUTPUT_RESOURCE_DIR)
 cmake_path(NORMAL_PATH FLANG_RT_INSTALL_RESOURCE_PATH)
 # FIXME: For the libflang_rt.so, the toolchain resource lib dir is not a good
@@ -128,6 +132,13 @@ cmake_path(NORMAL_PATH FLANG_RT_INSTALL_RESOURCE_PATH)
 #        the only reliable location.
 cmake_path(NORMAL_PATH FLANG_RT_OUTPUT_RESOURCE_LIB_DIR)
 cmake_path(NORMAL_PATH FLANG_RT_INSTALL_RESOURCE_LIB_PATH)
+cmake_path(NORMAL_PATH FLANG_RT_OUTPUT_RESOURCE_MOD_DIR)
+cmake_path(NORMAL_PATH FLANG_RT_INSTALL_RESOURCE_MOD_PATH)
+
+message("toolchain_mod_subdir: ${toolchain_mod_subdir}")
+message("FLANG_RT_OUTPUT_RESOURCE_MOD_DIR: ${FLANG_RT_OUTPUT_RESOURCE_MOD_DIR}")
+message("FLANG_RT_INSTALL_RESOURCE_MOD_PATH: ${FLANG_RT_INSTALL_RESOURCE_MOD_PATH}")
+
 
 
 #################
@@ -306,7 +317,7 @@ if (CMAKE_C_BYTE_ORDER STREQUAL "BIG_ENDIAN")
 elseif (CMAKE_C_BYTE_ORDER STREQUAL "LITTLE_ENDIAN")
   add_compile_definitions(FLANG_LITTLE_ENDIAN=1)
 else ()
-  #message(SEND_ERROR "Cannot determine endian '${CMAKE_C_BYTE_ORDER}' '${CMAKE_CXX_BYTE_ORDER}'")
+  message(SEND_ERROR "Cannot determine endian '${CMAKE_C_BYTE_ORDER}' '${CMAKE_CXX_BYTE_ORDER}'")
 endif ()
 
 
diff --git a/flang-rt/cmake/modules/AddFlangRT.cmake b/flang-rt/cmake/modules/AddFlangRT.cmake
index d08cc9a4ef788..5e4013a3c6fef 100644
--- a/flang-rt/cmake/modules/AddFlangRT.cmake
+++ b/flang-rt/cmake/modules/AddFlangRT.cmake
@@ -311,6 +311,7 @@ function (add_flangrt_library name)
         PROPERTIES
           ARCHIVE_OUTPUT_DIRECTORY "${FLANG_RT_OUTPUT_RESOURCE_LIB_DIR}"
           LIBRARY_OUTPUT_DIRECTORY "${FLANG_RT_OUTPUT_RESOURCE_LIB_DIR}"
+          Fortran_MODULE_DIRECTORY "${FLANG_RT_OUTPUT_RESOURCE_MOD_DIR}"
         )
 
       install(TARGETS ${tgtname}
diff --git a/flang-rt/cmake/modules/GetToolchainDirs.cmake b/flang-rt/cmake/modules/GetToolchainDirs.cmake
index 8b384180bcc31..da86923f61131 100644
--- a/flang-rt/cmake/modules/GetToolchainDirs.cmake
+++ b/flang-rt/cmake/modules/GetToolchainDirs.cmake
@@ -48,6 +48,16 @@ function (get_toolchain_library_subdir outvar)
 endfunction ()
 
 
+function (get_toolchain_module_subdir outvar)
+  set(outval "finclude")
+
+  get_toolchain_arch_dirname(arch_dirname)
+  set(outval "${outval}/${arch_dirname}")
+
+  set(${outvar} "${outval}" PARENT_SCOPE)
+endfunction ()
+
+
 # Corresponds to Clang's ToolChain::getOSLibName(). Adapted from Compiler-RT.
 function (get_toolchain_os_dirname outvar)
   if (ANDROID)
diff --git a/flang-rt/lib/runtime/CMakeLists.txt b/flang-rt/lib/runtime/CMakeLists.txt
index f79c02eef39eb..258b9a3868429 100644
--- a/flang-rt/lib/runtime/CMakeLists.txt
+++ b/flang-rt/lib/runtime/CMakeLists.txt
@@ -92,7 +92,6 @@ set(supported_sources
 # List of source not used for GPU offloading.
 set(CMAKE_Fortran_MODULE_DIRECTORY "${LLVM_LIBRARY_OUTPUT_INTDIR}/../include/flang")
 set(host_sources
-  __fortran_builtins.f90
   __fortran_ieee_exceptions.f90
   __fortran_type_info.f90
   ieee_arithmetic.f90
@@ -118,10 +117,14 @@ set(host_sources
   unit-map.cpp
 )
 
+# Module sources that are required by other modules
+set(intrinsics_sources
+  __fortran_builtins.f90
+)
 
 
 #set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "/home/meinersbur/build/llvm-project-flangrt/release_bootstrap/llvm_flang_runtimes/./lib/../include/flang/__fortran_builtins.mod")
-set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "flang-rt/lib/runtime/CMakeFiles/flang_rt.runtime.static.dir/__fortran_builtins.f90.o")
+#set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "flang-rt/lib/runtime/CMakeFiles/flang_rt.runtime.static.dir/__fortran_builtins.f90.o")
 #set_property(SOURCE "__fortran_type_info.f90" APPEND PROPERTY OBJECT_DEPENDS  "/home/meinersbur/build/llvm-project-flangrt/release_bootstrap/llvm_flang_runtimes/./lib/../include/flang/__fortran_builtins.mod")
 
 message("CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
@@ -155,17 +158,18 @@ endif ()
 
 
 # Flang is not always able to consume its own preprocessor output
-set_source_files_properties(
-  mma.f90
-  cudadevice.f90
-  PROPERTIES Fortran_PREPROCESS OFF
-)
+#set_source_files_properties(
+#  mma.f90
+#  cudadevice.f90
+#  PROPERTIES Fortran_PREPROCESS OFF
+#)
 
 
 
 
 
-add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
+add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:SHELL:-mmlir> $<$<COMPILE_LANGUAGE:Fortran>:-ignore-missing-type-desc>)
+add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:SHELL:-Xflang> $<$<COMPILE_LANGUAGE:Fortran>:-fno-reformat>)
 
 #add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:-mllvm=-flang-intrinsics-mode>)
 #set(CMAKE_Fortran_PREPROCESS FALSE)
@@ -219,12 +223,24 @@ set(Fortran_BUILDING_INTRINSIC_MODULES TRUE)
 set(Fortran_BUILDING_INSTRINSIC_MODULES TRUE)
 
 
+
+
+#add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:SHELL:-module-dir> $<$<COMPILE_LANGUAGE:Fortran>:"${FLANG_RT_OUTPUT_RESOURCE_MOD_DIR}">)
+add_compile_options($<$<COMPILE_LANGUAGE:Fortran>:SHELL:"-fintrinsic-modules-path"> $<$<COMPILE_LANGUAGE:Fortran>:"${FLANG_RT_OUTPUT_RESOURCE_MOD_DIR}">)
+
 if (NOT WIN32)
+  # Not a real library
+  add_flangrt_library(flang_rt.intrinsics OBJECT
+    ${intrinsics_sources}
+  )
+
   add_flangrt_library(flang_rt.runtime STATIC SHARED
     ${sources}
+  #  $<TARGET_OBJECTS:flang_rt.intrinsics>
     LINK_LIBRARIES ${Backtrace_LIBRARY}
     INSTALL_WITH_TOOLCHAIN
     ADDITIONAL_HEADERS ${public_headers} ${private_headers}
+    LINK_LIBRARIES flang_rt.intrinsics
     TARGET_PROPERTIES
       # Two spellings for the same thing: https://cmake.org/cmake/help/latest/prop_tgt/Fortran_BUILDING_INSTRINSIC_MODULES.html
       # Supported only since CMake 3.22
diff --git a/flang/include/flang/Frontend/CompilerInvocation.h b/flang/include/flang/Frontend/CompilerInvocation.h
index d6ee1511cdb4b..e1a4058d87518 100644
--- a/flang/include/flang/Frontend/CompilerInvocation.h
+++ b/flang/include/flang/Frontend/CompilerInvocation.h
@@ -92,6 +92,8 @@ class CompilerInvocation : public CompilerInvocationBase {
   // intrinsic of iso_fortran_env.
   std::string allCompilerInvocOpts;
 
+  std::string resourceDir;
+
   /// Semantic options
   // TODO: Merge with or translate to frontendOpts. We shouldn't need two sets
   // of options.
diff --git a/flang/include/flang/Frontend/PreprocessorOptions.h b/flang/include/flang/Frontend/PreprocessorOptions.h
index 2de9dabb1b372..73346b5a7023d 100644
--- a/flang/include/flang/Frontend/PreprocessorOptions.h
+++ b/flang/include/flang/Frontend/PreprocessorOptions.h
@@ -45,6 +45,7 @@ struct PreprocessorOptions {
   // consider collecting them in a separate aggregate. For now we keep it here
   // as there is no point creating a class for just one field.
   std::vector<std::string> searchDirectoriesFromDashI;
+  std::vector<std::string> searchDirectoriesFromDashJ;
   // Search directories specified by the user with -fintrinsic-modules-path
   std::vector<std::string> searchDirectoriesFromIntrModPath;
 
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp
index a0ddadff882b6..e73a6cde51025 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -819,6 +819,8 @@ static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
   return diags.getNumErrors() == numErrorsBefore;
 }
 
+// MK: Keep for compatibility?
+#if 0
 // Generate the path to look for intrinsic modules
 static std::string getIntrinsicDir(const char *argv) { // MK: To modify this
   // TODO: Find a system independent API
@@ -828,6 +830,7 @@ static std::string getIntrinsicDir(const char *argv) { // MK: To modify this
   driverPath.append("/../include/flang/");
   return std::string(driverPath);
 }
+#endif
 
 // Generate the path to look for OpenMP headers
 static std::string getOpenMPHeadersDir(const char *argv) {
@@ -859,6 +862,10 @@ static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
 
+  // Add the ordered list of -J's.
+  for (const auto *currentArg : args.filtered(clang::driver::options::OPT_J))
+    opts.searchDirectoriesFromDashJ.emplace_back(currentArg->getValue());
+
   // Prepend the ordered list of -intrinsic-modules-path
   // to the default location to search.
   for (const auto *currentArg :
@@ -1405,6 +1412,13 @@ bool CompilerInvocation::createFromArgs(
     success = false;
   }
 
+  // Default resource dir
+  invoc.resourceDir = clang::driver::Driver::GetResourcesPath(argv0);
+
+  if (const llvm::opt::Arg *a =
+          args.getLastArg(clang::driver::options::OPT_resource_dir))
+    invoc.resourceDir = a->getValue();
+
   // -flang-experimental-hlfir
   if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) ||
       args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
@@ -1637,13 +1651,17 @@ void CompilerInvocation::setFortranOpts() {
 
   //  Add the default intrinsic module directory
 #if 1
-     // MK Contradicts description of the option which says "if not found"
-    fortranOptions.intrinsicModuleDirectories.insert(
+  // gfortran prepends this path to the usual intrinsics dir
+  fortranOptions.intrinsicModuleDirectories.insert(
       fortranOptions.intrinsicModuleDirectories.end(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
-#endif 
-  fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir(getArgv0()));
+#endif
+
+  //   llvm::SmallString<128> intrinsicsDir { resourceDir };
+  //   llvm::sys::path::append(intrinsicsDir, "finclude", triple);
+  //    fortranOptions.intrinsicModuleDirectories.emplace_back(intrinsicsDir);
+  // fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir(getArgv0()));
 
   // Add the directory supplied through -J/-module-dir to the list of search
   // directories
diff --git a/flang/lib/Semantics/check-omp-structure.cpp b/flang/lib/Semantics/check-omp-structure.cpp
index 4df889ea8b83c..3d4b0c2e77c7e 100644
--- a/flang/lib/Semantics/check-omp-structure.cpp
+++ b/flang/lib/Semantics/check-omp-structure.cpp
@@ -3645,39 +3645,44 @@ void OmpStructureChecker::CheckSharedBindingInOuterContext(
   //  TODO: Verify the assumption here that the immediately enclosing region is
   //  the parallel region to which the worksharing construct having reduction
   //  binds to.
-  if (auto *enclosingContext{GetEnclosingDirContext()}) {
-    for (auto it : enclosingContext->clauseInfo) {
-      llvmOmpClause type = it.first;
-      const auto *clause = it.second;
-      if (llvm::omp::privateReductionSet.test(type)) {
-        if (const auto *objList{GetOmpObjectList(*clause)}) {
-          for (const auto &ompObject : objList->v) {
-            if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
-              if (const auto *symbol{name->symbol}) {
-                for (const auto &redOmpObject : redObjectList.v) {
-                  if (const auto *rname{
-                          parser::Unwrap<parser::Name>(redOmpObject)}) {
-                    if (const auto *rsymbol{rname->symbol}) {
-                      if (rsymbol->name() == symbol->name()) {
-                        context_.Say(GetContext().clauseSource,
-                            "%s variable '%s' is %s in outer context must"
-                            " be shared in the parallel regions to which any"
-                            " of the worksharing regions arising from the "
-                            "worksharing construct bind."_err_en_US,
-                            parser::ToUpperCaseLetters(
-                                getClauseName(llvm::omp::Clause::OMPC_reduction)
-                                    .str()),
-                            symbol->name(),
-                            parser::ToUpperCaseLetters(
-                                getClauseName(type).str()));
-                      }
-                    }
-                  }
-                }
-              }
-            }
-          }
-        }
+  auto enclosingContext{GetEnclosingDirContext()};
+  if (!enclosingContext)
+    return;
+
+  for (auto [type, clause] : enclosingContext->clauseInfo) {
+    if (!llvm::omp::privateReductionSet.test(type))
+      continue;
+
+    const auto *objList{GetOmpObjectList(*clause)};
+    for (const auto &ompObject : objList->v) {
+      const auto *name{parser::Unwrap<parser::Name>(ompObject)};
+      if (!name)
+        continue;
+
+      const auto *symbol{name->symbol};
+      if (!symbol)
+        continue;
+
+      for (const auto &redOmpObject : redObjectList.v) {
+        const auto *rname{parser::Unwrap<parser::Name>(redOmpObject)};
+        if (!rname)
+          continue;
+
+        const auto *rsymbol{rname->symbol};
+        if (!rsymbol)
+          continue;
+
+        if (rsymbol->name() != symbol->name())
+          continue;
+
+        context_.Say(GetContext().clauseSource,
+            "%s variable '%s' is %s in outer context must be shared in the "
+            "parallel regions to which any of the worksharing regions arising "
+            "from the worksharing construct bind."_err_en_US,
+            parser::ToUpperCaseLetters(
+                getClauseName(llvm::omp::Clause::OMPC_reduction).str()),
+            symbol->name(),
+            parser::ToUpperCaseLetters(getClauseName(type).str()));
       }
     }
   }



More information about the Openmp-commits mailing list