skatrak updated this revision to Diff 527354.
skatrak added a comment.

Rebase and address reviewer's comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D147218/new/

https://reviews.llvm.org/D147218

Files:
  flang/include/flang/Lower/OpenMP.h
  flang/lib/Lower/Bridge.cpp
  flang/lib/Lower/OpenMP.cpp
  flang/test/Lower/OpenMP/requires-notarget.f90
  flang/test/Lower/OpenMP/requires.f90

Index: flang/test/Lower/OpenMP/requires.f90
===================================================================
--- /dev/null
+++ flang/test/Lower/OpenMP/requires.f90
@@ -0,0 +1,13 @@
+! RUN: %flang_fc1 -emit-fir -fopenmp %s -o - | FileCheck %s
+
+! This test checks the lowering of requires into MLIR
+
+!CHECK:      module attributes {
+!CHECK-SAME: omp.requires = #omp<clause_requires reverse_offload|unified_shared_memory>
+program requires
+  !$omp requires unified_shared_memory reverse_offload atomic_default_mem_order(seq_cst)
+end program requires
+
+subroutine f
+  !$omp declare target
+end subroutine f
Index: flang/test/Lower/OpenMP/requires-notarget.f90
===================================================================
--- /dev/null
+++ flang/test/Lower/OpenMP/requires-notarget.f90
@@ -0,0 +1,11 @@
+! RUN: %flang_fc1 -emit-fir -fopenmp %s -o - | FileCheck %s
+
+! This test checks that requires lowering into MLIR skips creating the
+! omp.requires attribute with target-related clauses if there are no device
+! functions in the compilation unit
+
+!CHECK:      module attributes {
+!CHECK-NOT:  omp.requires
+program requires
+  !$omp requires unified_shared_memory reverse_offload atomic_default_mem_order(seq_cst)
+end program requires
Index: flang/lib/Lower/OpenMP.cpp
===================================================================
--- flang/lib/Lower/OpenMP.cpp
+++ flang/lib/Lower/OpenMP.cpp
@@ -2494,14 +2494,14 @@
   converter.bindSymbol(sym, symThreadprivateExv);
 }
 
-void handleDeclareTarget(Fortran::lower::AbstractConverter &converter,
-                         Fortran::lower::pft::Evaluation &eval,
-                         const Fortran::parser::OpenMPDeclareTargetConstruct
-                             &declareTargetConstruct) {
-  llvm::SmallVector<std::pair<mlir::omp::DeclareTargetCaptureClause,
-                              Fortran::semantics::Symbol>,
-                    0>
-      symbolAndClause;
+/// Extract the list of function and variable symbols affected by the given
+/// 'declare target' directive and return the intended device type for them.
+static mlir::omp::DeclareTargetDeviceType getDeclareTargetInfo(
+    Fortran::lower::pft::Evaluation &eval,
+    const Fortran::parser::OpenMPDeclareTargetConstruct &declareTargetConstruct,
+    SmallVectorImpl<std::pair<mlir::omp::DeclareTargetCaptureClause,
+                              Fortran::semantics::Symbol>> &symbolAndClause) {
+  // Gather the symbols and clauses
   auto findFuncAndVarSyms = [&](const Fortran::parser::OmpObjectList &objList,
                                 mlir::omp::DeclareTargetCaptureClause clause) {
     for (const auto &ompObject : objList.v) {
@@ -2521,12 +2521,11 @@
     }
   };
 
+  // The default capture type
+  auto deviceType{Fortran::parser::OmpDeviceTypeClause::Type::Any};
   const auto &spec{std::get<Fortran::parser::OmpDeclareTargetSpecifier>(
       declareTargetConstruct.t)};
-  auto mod = converter.getFirOpBuilder().getModule();
 
-  // The default capture type
-  auto deviceType = Fortran::parser::OmpDeviceTypeClause::Type::Any;
   if (const auto *objectList{
           Fortran::parser::Unwrap<Fortran::parser::OmpObjectList>(spec.u)}) {
     // Case: declare target(func, var1, var2)
@@ -2562,6 +2561,28 @@
     }
   }
 
+  switch (deviceType) {
+  case Fortran::parser::OmpDeviceTypeClause::Type::Any:
+    return mlir::omp::DeclareTargetDeviceType::any;
+  case Fortran::parser::OmpDeviceTypeClause::Type::Host:
+    return mlir::omp::DeclareTargetDeviceType::host;
+  case Fortran::parser::OmpDeviceTypeClause::Type::Nohost:
+    return mlir::omp::DeclareTargetDeviceType::nohost;
+  }
+}
+
+void genDeclareTarget(Fortran::lower::AbstractConverter &converter,
+                      Fortran::lower::pft::Evaluation &eval,
+                      const Fortran::parser::OpenMPDeclareTargetConstruct
+                          &declareTargetConstruct) {
+  llvm::SmallVector<std::pair<mlir::omp::DeclareTargetCaptureClause,
+                              Fortran::semantics::Symbol>,
+                    0>
+      symbolAndClause;
+  mlir::omp::DeclareTargetDeviceType deviceType =
+      getDeclareTargetInfo(eval, declareTargetConstruct, symbolAndClause);
+
+  mlir::ModuleOp mod = converter.getFirOpBuilder().getModule();
   for (auto sym : symbolAndClause) {
     auto *op = mod.lookupSymbol(converter.mangleName(std::get<1>(sym)));
 
@@ -2571,32 +2592,19 @@
           converter.getCurrentLocation(),
           "Attempt to apply declare target on unsupproted operation");
 
-    mlir::omp::DeclareTargetDeviceType newDeviceType;
-    switch (deviceType) {
-    case Fortran::parser::OmpDeviceTypeClause::Type::Nohost:
-      newDeviceType = mlir::omp::DeclareTargetDeviceType::nohost;
-      break;
-    case Fortran::parser::OmpDeviceTypeClause::Type::Host:
-      newDeviceType = mlir::omp::DeclareTargetDeviceType::host;
-      break;
-    case Fortran::parser::OmpDeviceTypeClause::Type::Any:
-      newDeviceType = mlir::omp::DeclareTargetDeviceType::any;
-      break;
-    }
-
     // The function or global already has a declare target applied to it,
     // very likely through implicit capture (usage in another declare
     // target function/subroutine). It should be marked as any if it has
     // been assigned both host and nohost, else we skip, as there is no
     // change
     if (declareTargetOp.isDeclareTarget()) {
-      if (declareTargetOp.getDeclareTargetDeviceType() != newDeviceType)
+      if (declareTargetOp.getDeclareTargetDeviceType() != deviceType)
         declareTargetOp.setDeclareTarget(
             mlir::omp::DeclareTargetDeviceType::any, std::get<0>(sym));
       continue;
     }
 
-    declareTargetOp.setDeclareTarget(newDeviceType, std::get<0>(sym));
+    declareTargetOp.setDeclareTarget(deviceType, std::get<0>(sym));
   }
 }
 
@@ -2622,11 +2630,15 @@
           },
           [&](const Fortran::parser::OpenMPDeclareTargetConstruct
                   &declareTargetConstruct) {
-            handleDeclareTarget(converter, eval, declareTargetConstruct);
+            genDeclareTarget(converter, eval, declareTargetConstruct);
           },
           [&](const Fortran::parser::OpenMPRequiresConstruct
                   &requiresConstruct) {
-            TODO(converter.getCurrentLocation(), "OpenMPRequiresConstruct");
+            // Requires directives are analyzed before any statements are
+            // lowered. Then, the result of combining the set of clauses of all
+            // requires directives present in the compilation unit is used to
+            // emit code, so no code is emitted independently for each
+            // "requires" instance.
           },
           [&](const Fortran::parser::OpenMPThreadprivate &threadprivate) {
             // The directive is lowered when instantiating the variable to
@@ -2848,3 +2860,84 @@
     }
   }
 }
+
+std::optional<mlir::omp::DeclareTargetDeviceType>
+Fortran::lower::getOpenMPDeclareTargetFunctionDevice(
+    Fortran::lower::AbstractConverter &converter,
+    Fortran::lower::pft::Evaluation &eval,
+    const Fortran::parser::OpenMPDeclareTargetConstruct
+        &declareTargetConstruct) {
+  llvm::SmallVector<std::pair<mlir::omp::DeclareTargetCaptureClause,
+                              Fortran::semantics::Symbol>,
+                    0>
+      symbolAndClause;
+  mlir::omp::DeclareTargetDeviceType deviceType =
+      getDeclareTargetInfo(eval, declareTargetConstruct, symbolAndClause);
+
+  // Return the device type only if at least one of the targets for the
+  // directive is a function or subroutine
+  mlir::ModuleOp mod = converter.getFirOpBuilder().getModule();
+  for (std::pair<mlir::omp::DeclareTargetCaptureClause,
+                 Fortran::semantics::Symbol>
+           sym : symbolAndClause) {
+    mlir::Operation *op =
+        mod.lookupSymbol(converter.mangleName(std::get<1>(sym)));
+
+    if (mlir::isa<mlir::func::FuncOp>(op))
+      return deviceType;
+  }
+
+  return std::nullopt;
+}
+
+bool Fortran::lower::isOpenMPTargetConstruct(
+    const Fortran::parser::OpenMPConstruct &omp) {
+  if (const auto *blockDir =
+          std::get_if<Fortran::parser::OpenMPBlockConstruct>(&omp.u)) {
+    const auto &beginBlockDir{
+        std::get<Fortran::parser::OmpBeginBlockDirective>(blockDir->t)};
+    const auto &beginDir{
+        std::get<Fortran::parser::OmpBlockDirective>(beginBlockDir.t)};
+
+    switch (beginDir.v) {
+    case llvm::omp::Directive::OMPD_target:
+    case llvm::omp::Directive::OMPD_target_parallel:
+    case llvm::omp::Directive::OMPD_target_parallel_do:
+    case llvm::omp::Directive::OMPD_target_parallel_do_simd:
+    case llvm::omp::Directive::OMPD_target_simd:
+    case llvm::omp::Directive::OMPD_target_teams:
+    case llvm::omp::Directive::OMPD_target_teams_distribute:
+    case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
+      return true;
+    default:
+      break;
+    }
+  }
+
+  return false;
+}
+
+omp::ClauseRequires Fortran::lower::extractOpenMPRequiresClauses(
+    const Fortran::parser::OmpClauseList &clauseList) {
+  using omp::ClauseRequires, Fortran::parser::OmpClause;
+  auto requiresFlags = ClauseRequires::none;
+
+  for (const OmpClause &clause : clauseList.v) {
+    if (std::get_if<OmpClause::DynamicAllocators>(&clause.u))
+      requiresFlags = requiresFlags | ClauseRequires::dynamic_allocators;
+    else if (std::get_if<OmpClause::ReverseOffload>(&clause.u))
+      requiresFlags = requiresFlags | ClauseRequires::reverse_offload;
+    else if (std::get_if<OmpClause::UnifiedAddress>(&clause.u))
+      requiresFlags = requiresFlags | ClauseRequires::unified_address;
+    else if (std::get_if<OmpClause::UnifiedSharedMemory>(&clause.u))
+      requiresFlags = requiresFlags | ClauseRequires::unified_shared_memory;
+  }
+
+  return requiresFlags;
+}
+
+void Fortran::lower::genOpenMPRequires(Operation *mod,
+                                       omp::ClauseRequires flags) {
+  if (auto offloadMod = llvm::dyn_cast<mlir::omp::OffloadModuleInterface>(mod))
+    offloadMod.setRequires(flags);
+}
Index: flang/lib/Lower/Bridge.cpp
===================================================================
--- flang/lib/Lower/Bridge.cpp
+++ flang/lib/Lower/Bridge.cpp
@@ -267,7 +267,8 @@
 public:
   explicit FirConverter(Fortran::lower::LoweringBridge &bridge)
       : Fortran::lower::AbstractConverter(bridge.getLoweringOptions()),
-        bridge{bridge}, foldingContext{bridge.createFoldingContext()} {}
+        bridge{bridge}, foldingContext{bridge.createFoldingContext()},
+        ompRequiresFlags{mlir::omp::ClauseRequires::none} {}
   virtual ~FirConverter() = default;
 
   /// Convert the PFT to FIR.
@@ -344,6 +345,11 @@
         fir::runtime::genEnvironmentDefaults(*builder, toLocation(),
                                              bridge.getEnvironmentDefaults());
       });
+
+    // Set the module attribute related to OpenMP requires directives
+    if (ompDeviceCodeFound)
+      Fortran::lower::genOpenMPRequires(getModuleOp().getOperation(),
+                                        ompRequiresFlags);
   }
 
   /// Declare a function.
@@ -2218,10 +2224,44 @@
 
     localSymbols.popScope();
     builder->restoreInsertionPoint(insertPt);
+
+    // Register if a target region was found
+    ompDeviceCodeFound =
+        ompDeviceCodeFound || Fortran::lower::isOpenMPTargetConstruct(omp);
+  }
+
+  /// Extract information from OpenMP declarative constructs
+  void analyzeOpenMPDeclarative(
+      const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) {
+    std::visit(
+        Fortran::common::visitors{
+            [&](const Fortran::parser::OpenMPRequiresConstruct &ompReq) {
+              mlir::omp::ClauseRequires requiresFlags =
+                  Fortran::lower::extractOpenMPRequiresClauses(
+                      std::get<Fortran::parser::OmpClauseList>(ompReq.t));
+
+              if (requiresFlags != mlir::omp::ClauseRequires::none)
+                ompRequiresFlags = ompRequiresFlags | requiresFlags;
+            },
+            [&](const Fortran::parser::OpenMPDeclareTargetConstruct &ompReq) {
+              std::optional<mlir::omp::DeclareTargetDeviceType> targetType =
+                  Fortran::lower::getOpenMPDeclareTargetFunctionDevice(
+                      *this, getEval(), ompReq);
+
+              ompDeviceCodeFound =
+                  ompDeviceCodeFound ||
+                  (targetType &&
+                   *targetType != mlir::omp::DeclareTargetDeviceType::host);
+            },
+            // Add other OpenMP declarative constructs currently skipped
+            [&](const auto &) {},
+        },
+        ompDecl.u);
   }
 
   void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) {
     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
+    analyzeOpenMPDeclarative(ompDecl);
     genOpenMPDeclarativeConstruct(*this, getEval(), ompDecl);
     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
       genFIR(e);
@@ -4547,6 +4587,13 @@
 
   /// A counter for uniquing names in `literalNamesMap`.
   std::uint64_t uniqueLitId = 0;
+
+  /// OpenMP Requires flags
+  mlir::omp::ClauseRequires ompRequiresFlags;
+
+  /// Whether an OpenMP target region or declare target function/subroutine
+  /// intended for device offloading has been detected
+  bool ompDeviceCodeFound = false;
 };
 
 } // namespace
Index: flang/include/flang/Lower/OpenMP.h
===================================================================
--- flang/include/flang/Lower/OpenMP.h
+++ flang/include/flang/Lower/OpenMP.h
@@ -13,13 +13,9 @@
 #ifndef FORTRAN_LOWER_OPENMP_H
 #define FORTRAN_LOWER_OPENMP_H
 
+#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
 #include <cinttypes>
 
-namespace mlir {
-class Value;
-class Operation;
-} // namespace mlir
-
 namespace fir {
 class FirOpBuilder;
 class ConvertOp;
@@ -29,6 +25,7 @@
 namespace parser {
 struct OpenMPConstruct;
 struct OpenMPDeclarativeConstruct;
+struct OpenMPDeclareTargetConstruct;
 struct OmpEndLoopDirective;
 struct OmpClauseList;
 } // namespace parser
@@ -56,6 +53,17 @@
 void updateReduction(mlir::Operation *, fir::FirOpBuilder &, mlir::Value,
                      mlir::Value, fir::ConvertOp * = nullptr);
 void removeStoreOp(mlir::Operation *, mlir::Value);
+
+std::optional<mlir::omp::DeclareTargetDeviceType>
+getOpenMPDeclareTargetFunctionDevice(
+    Fortran::lower::AbstractConverter &, Fortran::lower::pft::Evaluation &,
+    const Fortran::parser::OpenMPDeclareTargetConstruct &);
+bool isOpenMPTargetConstruct(const parser::OpenMPConstruct &);
+
+mlir::omp::ClauseRequires
+extractOpenMPRequiresClauses(const Fortran::parser::OmpClauseList &);
+void genOpenMPRequires(mlir::Operation *, mlir::omp::ClauseRequires);
+
 } // namespace lower
 } // namespace Fortran
 
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to