1 //===-- OpenMP.cpp -- Open MP directive lowering --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Lower/OpenMP.h"
14 #include "flang/Common/idioms.h"
15 #include "flang/Lower/Bridge.h"
16 #include "flang/Lower/PFTBuilder.h"
17 #include "flang/Lower/StatementContext.h"
18 #include "flang/Lower/Todo.h"
19 #include "flang/Optimizer/Builder/BoxValue.h"
20 #include "flang/Optimizer/Builder/FIRBuilder.h"
21 #include "flang/Parser/parse-tree.h"
22 #include "flang/Semantics/tools.h"
23 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
24 #include "llvm/Frontend/OpenMP/OMPConstants.h"
25 
26 using namespace mlir;
27 
28 static const Fortran::parser::Name *
29 getDesignatorNameIfDataRef(const Fortran::parser::Designator &designator) {
30   const auto *dataRef = std::get_if<Fortran::parser::DataRef>(&designator.u);
31   return dataRef ? std::get_if<Fortran::parser::Name>(&dataRef->u) : nullptr;
32 }
33 
34 template <typename T>
35 static void createPrivateVarSyms(Fortran::lower::AbstractConverter &converter,
36                                  const T *clause) {
37   Fortran::semantics::Symbol *sym = nullptr;
38   const Fortran::parser::OmpObjectList &ompObjectList = clause->v;
39   for (const Fortran::parser::OmpObject &ompObject : ompObjectList.v) {
40     std::visit(
41         Fortran::common::visitors{
42             [&](const Fortran::parser::Designator &designator) {
43               if (const Fortran::parser::Name *name =
44                       getDesignatorNameIfDataRef(designator)) {
45                 sym = name->symbol;
46               }
47             },
48             [&](const Fortran::parser::Name &name) { sym = name.symbol; }},
49         ompObject.u);
50 
51     // Privatization for symbols which are pre-determined (like loop index
52     // variables) happen separately, for everything else privatize here
53     if constexpr (std::is_same_v<T, Fortran::parser::OmpClause::Firstprivate>) {
54       converter.copyHostAssociateVar(*sym);
55     } else {
56       bool success = converter.createHostAssociateVarClone(*sym);
57       (void)success;
58       assert(success && "Privatization failed due to existing binding");
59     }
60   }
61 }
62 
63 static void privatizeVars(Fortran::lower::AbstractConverter &converter,
64                           const Fortran::parser::OmpClauseList &opClauseList) {
65   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
66   auto insPt = firOpBuilder.saveInsertionPoint();
67   firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
68   for (const Fortran::parser::OmpClause &clause : opClauseList.v) {
69     if (const auto &privateClause =
70             std::get_if<Fortran::parser::OmpClause::Private>(&clause.u)) {
71       createPrivateVarSyms(converter, privateClause);
72     } else if (const auto &firstPrivateClause =
73                    std::get_if<Fortran::parser::OmpClause::Firstprivate>(
74                        &clause.u)) {
75       createPrivateVarSyms(converter, firstPrivateClause);
76     }
77   }
78   firOpBuilder.restoreInsertionPoint(insPt);
79 }
80 
81 static void genObjectList(const Fortran::parser::OmpObjectList &objectList,
82                           Fortran::lower::AbstractConverter &converter,
83                           llvm::SmallVectorImpl<Value> &operands) {
84   auto addOperands = [&](Fortran::lower::SymbolRef sym) {
85     const mlir::Value variable = converter.getSymbolAddress(sym);
86     if (variable) {
87       operands.push_back(variable);
88     } else {
89       if (const auto *details =
90               sym->detailsIf<Fortran::semantics::HostAssocDetails>()) {
91         operands.push_back(converter.getSymbolAddress(details->symbol()));
92         converter.copySymbolBinding(details->symbol(), sym);
93       }
94     }
95   };
96   for (const Fortran::parser::OmpObject &ompObject : objectList.v) {
97     std::visit(Fortran::common::visitors{
98                    [&](const Fortran::parser::Designator &designator) {
99                      if (const Fortran::parser::Name *name =
100                              getDesignatorNameIfDataRef(designator)) {
101                        addOperands(*name->symbol);
102                      }
103                    },
104                    [&](const Fortran::parser::Name &name) {
105                      addOperands(*name.symbol);
106                    }},
107                ompObject.u);
108   }
109 }
110 
111 template <typename Op>
112 static void
113 createBodyOfOp(Op &op, Fortran::lower::AbstractConverter &converter,
114                mlir::Location &loc,
115                const Fortran::parser::OmpClauseList *clauses = nullptr,
116                bool outerCombined = false) {
117   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
118   firOpBuilder.createBlock(&op.getRegion());
119   auto &block = op.getRegion().back();
120   firOpBuilder.setInsertionPointToStart(&block);
121   // Ensure the block is well-formed.
122   firOpBuilder.create<mlir::omp::TerminatorOp>(loc);
123   // Reset the insertion point to the start of the first block.
124   firOpBuilder.setInsertionPointToStart(&block);
125   // Handle privatization. Do not privatize if this is the outer operation.
126   if (clauses && !outerCombined)
127     privatizeVars(converter, *clauses);
128 }
129 
130 static void genOMP(Fortran::lower::AbstractConverter &converter,
131                    Fortran::lower::pft::Evaluation &eval,
132                    const Fortran::parser::OpenMPSimpleStandaloneConstruct
133                        &simpleStandaloneConstruct) {
134   const auto &directive =
135       std::get<Fortran::parser::OmpSimpleStandaloneDirective>(
136           simpleStandaloneConstruct.t);
137   switch (directive.v) {
138   default:
139     break;
140   case llvm::omp::Directive::OMPD_barrier:
141     converter.getFirOpBuilder().create<mlir::omp::BarrierOp>(
142         converter.getCurrentLocation());
143     break;
144   case llvm::omp::Directive::OMPD_taskwait:
145     converter.getFirOpBuilder().create<mlir::omp::TaskwaitOp>(
146         converter.getCurrentLocation());
147     break;
148   case llvm::omp::Directive::OMPD_taskyield:
149     converter.getFirOpBuilder().create<mlir::omp::TaskyieldOp>(
150         converter.getCurrentLocation());
151     break;
152   case llvm::omp::Directive::OMPD_target_enter_data:
153     TODO(converter.getCurrentLocation(), "OMPD_target_enter_data");
154   case llvm::omp::Directive::OMPD_target_exit_data:
155     TODO(converter.getCurrentLocation(), "OMPD_target_exit_data");
156   case llvm::omp::Directive::OMPD_target_update:
157     TODO(converter.getCurrentLocation(), "OMPD_target_update");
158   case llvm::omp::Directive::OMPD_ordered:
159     TODO(converter.getCurrentLocation(), "OMPD_ordered");
160   }
161 }
162 
163 static void
164 genAllocateClause(Fortran::lower::AbstractConverter &converter,
165                   const Fortran::parser::OmpAllocateClause &ompAllocateClause,
166                   SmallVector<Value> &allocatorOperands,
167                   SmallVector<Value> &allocateOperands) {
168   auto &firOpBuilder = converter.getFirOpBuilder();
169   auto currentLocation = converter.getCurrentLocation();
170   Fortran::lower::StatementContext stmtCtx;
171 
172   mlir::Value allocatorOperand;
173   const Fortran::parser::OmpObjectList &ompObjectList =
174       std::get<Fortran::parser::OmpObjectList>(ompAllocateClause.t);
175   const auto &allocatorValue =
176       std::get<std::optional<Fortran::parser::OmpAllocateClause::Allocator>>(
177           ompAllocateClause.t);
178   // Check if allocate clause has allocator specified. If so, add it
179   // to list of allocators, otherwise, add default allocator to
180   // list of allocators.
181   if (allocatorValue) {
182     allocatorOperand = fir::getBase(converter.genExprValue(
183         *Fortran::semantics::GetExpr(allocatorValue->v), stmtCtx));
184     allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(),
185                              allocatorOperand);
186   } else {
187     allocatorOperand = firOpBuilder.createIntegerConstant(
188         currentLocation, firOpBuilder.getI32Type(), 1);
189     allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(),
190                              allocatorOperand);
191   }
192   genObjectList(ompObjectList, converter, allocateOperands);
193 }
194 
195 static void
196 genOMP(Fortran::lower::AbstractConverter &converter,
197        Fortran::lower::pft::Evaluation &eval,
198        const Fortran::parser::OpenMPStandaloneConstruct &standaloneConstruct) {
199   std::visit(
200       Fortran::common::visitors{
201           [&](const Fortran::parser::OpenMPSimpleStandaloneConstruct
202                   &simpleStandaloneConstruct) {
203             genOMP(converter, eval, simpleStandaloneConstruct);
204           },
205           [&](const Fortran::parser::OpenMPFlushConstruct &flushConstruct) {
206             SmallVector<Value, 4> operandRange;
207             if (const auto &ompObjectList =
208                     std::get<std::optional<Fortran::parser::OmpObjectList>>(
209                         flushConstruct.t))
210               genObjectList(*ompObjectList, converter, operandRange);
211             const auto &memOrderClause = std::get<std::optional<
212                 std::list<Fortran::parser::OmpMemoryOrderClause>>>(
213                 flushConstruct.t);
214             if (memOrderClause.has_value() && memOrderClause->size() > 0)
215               TODO(converter.getCurrentLocation(),
216                    "Handle OmpMemoryOrderClause");
217             converter.getFirOpBuilder().create<mlir::omp::FlushOp>(
218                 converter.getCurrentLocation(), operandRange);
219           },
220           [&](const Fortran::parser::OpenMPCancelConstruct &cancelConstruct) {
221             TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
222           },
223           [&](const Fortran::parser::OpenMPCancellationPointConstruct
224                   &cancellationPointConstruct) {
225             TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
226           },
227       },
228       standaloneConstruct.u);
229 }
230 
231 static void
232 genOMP(Fortran::lower::AbstractConverter &converter,
233        Fortran::lower::pft::Evaluation &eval,
234        const Fortran::parser::OpenMPBlockConstruct &blockConstruct) {
235   const auto &beginBlockDirective =
236       std::get<Fortran::parser::OmpBeginBlockDirective>(blockConstruct.t);
237   const auto &blockDirective =
238       std::get<Fortran::parser::OmpBlockDirective>(beginBlockDirective.t);
239   const auto &endBlockDirective =
240       std::get<Fortran::parser::OmpEndBlockDirective>(blockConstruct.t);
241   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
242   mlir::Location currentLocation = converter.getCurrentLocation();
243 
244   Fortran::lower::StatementContext stmtCtx;
245   llvm::ArrayRef<mlir::Type> argTy;
246   mlir::Value ifClauseOperand, numThreadsClauseOperand;
247   mlir::omp::ClauseProcBindKindAttr procBindKindAttr;
248   SmallVector<Value> allocateOperands, allocatorOperands;
249   mlir::UnitAttr nowaitAttr;
250 
251   const auto &opClauseList =
252       std::get<Fortran::parser::OmpClauseList>(beginBlockDirective.t);
253   for (const auto &clause : opClauseList.v) {
254     if (const auto &ifClause =
255             std::get_if<Fortran::parser::OmpClause::If>(&clause.u)) {
256       auto &expr = std::get<Fortran::parser::ScalarLogicalExpr>(ifClause->v.t);
257       ifClauseOperand = fir::getBase(
258           converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx));
259     } else if (const auto &numThreadsClause =
260                    std::get_if<Fortran::parser::OmpClause::NumThreads>(
261                        &clause.u)) {
262       // OMPIRBuilder expects `NUM_THREAD` clause as a `Value`.
263       numThreadsClauseOperand = fir::getBase(converter.genExprValue(
264           *Fortran::semantics::GetExpr(numThreadsClause->v), stmtCtx));
265     } else if (const auto &procBindClause =
266                    std::get_if<Fortran::parser::OmpClause::ProcBind>(
267                        &clause.u)) {
268       omp::ClauseProcBindKind pbKind;
269       switch (procBindClause->v.v) {
270       case Fortran::parser::OmpProcBindClause::Type::Master:
271         pbKind = omp::ClauseProcBindKind::Master;
272         break;
273       case Fortran::parser::OmpProcBindClause::Type::Close:
274         pbKind = omp::ClauseProcBindKind::Close;
275         break;
276       case Fortran::parser::OmpProcBindClause::Type::Spread:
277         pbKind = omp::ClauseProcBindKind::Spread;
278         break;
279       case Fortran::parser::OmpProcBindClause::Type::Primary:
280         pbKind = omp::ClauseProcBindKind::Primary;
281         break;
282       }
283       procBindKindAttr =
284           omp::ClauseProcBindKindAttr::get(firOpBuilder.getContext(), pbKind);
285     } else if (const auto &allocateClause =
286                    std::get_if<Fortran::parser::OmpClause::Allocate>(
287                        &clause.u)) {
288       genAllocateClause(converter, allocateClause->v, allocatorOperands,
289                         allocateOperands);
290     } else if (std::get_if<Fortran::parser::OmpClause::Private>(&clause.u) ||
291                std::get_if<Fortran::parser::OmpClause::Firstprivate>(
292                    &clause.u)) {
293       // Privatisation clauses are handled elsewhere.
294       continue;
295     } else if (std::get_if<Fortran::parser::OmpClause::Threads>(&clause.u)) {
296       // Nothing needs to be done for threads clause.
297       continue;
298     } else {
299       TODO(currentLocation, "OpenMP Block construct clauses");
300     }
301   }
302 
303   for (const auto &clause :
304        std::get<Fortran::parser::OmpClauseList>(endBlockDirective.t).v) {
305     if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u))
306       nowaitAttr = firOpBuilder.getUnitAttr();
307   }
308 
309   if (blockDirective.v == llvm::omp::OMPD_parallel) {
310     // Create and insert the operation.
311     auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>(
312         currentLocation, argTy, ifClauseOperand, numThreadsClauseOperand,
313         allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(),
314         /*reductions=*/nullptr, procBindKindAttr);
315     createBodyOfOp<omp::ParallelOp>(parallelOp, converter, currentLocation,
316                                     &opClauseList, /*isCombined=*/false);
317   } else if (blockDirective.v == llvm::omp::OMPD_master) {
318     auto masterOp =
319         firOpBuilder.create<mlir::omp::MasterOp>(currentLocation, argTy);
320     createBodyOfOp<omp::MasterOp>(masterOp, converter, currentLocation);
321   } else if (blockDirective.v == llvm::omp::OMPD_single) {
322     auto singleOp = firOpBuilder.create<mlir::omp::SingleOp>(
323         currentLocation, allocateOperands, allocatorOperands, nowaitAttr);
324     createBodyOfOp<omp::SingleOp>(singleOp, converter, currentLocation);
325   } else if (blockDirective.v == llvm::omp::OMPD_ordered) {
326     auto orderedOp = firOpBuilder.create<mlir::omp::OrderedRegionOp>(
327         currentLocation, /*simd=*/nullptr);
328     createBodyOfOp<omp::OrderedRegionOp>(orderedOp, converter, currentLocation);
329   } else {
330     TODO(converter.getCurrentLocation(), "Unhandled block directive");
331   }
332 }
333 
334 static void
335 genOMP(Fortran::lower::AbstractConverter &converter,
336        Fortran::lower::pft::Evaluation &eval,
337        const Fortran::parser::OpenMPCriticalConstruct &criticalConstruct) {
338   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
339   mlir::Location currentLocation = converter.getCurrentLocation();
340   std::string name;
341   const Fortran::parser::OmpCriticalDirective &cd =
342       std::get<Fortran::parser::OmpCriticalDirective>(criticalConstruct.t);
343   if (std::get<std::optional<Fortran::parser::Name>>(cd.t).has_value()) {
344     name =
345         std::get<std::optional<Fortran::parser::Name>>(cd.t).value().ToString();
346   }
347 
348   uint64_t hint = 0;
349   const auto &clauseList = std::get<Fortran::parser::OmpClauseList>(cd.t);
350   for (const Fortran::parser::OmpClause &clause : clauseList.v)
351     if (auto hintClause =
352             std::get_if<Fortran::parser::OmpClause::Hint>(&clause.u)) {
353       const auto *expr = Fortran::semantics::GetExpr(hintClause->v);
354       hint = *Fortran::evaluate::ToInt64(*expr);
355       break;
356     }
357 
358   mlir::omp::CriticalOp criticalOp = [&]() {
359     if (name.empty()) {
360       return firOpBuilder.create<mlir::omp::CriticalOp>(currentLocation,
361                                                         FlatSymbolRefAttr());
362     } else {
363       mlir::ModuleOp module = firOpBuilder.getModule();
364       mlir::OpBuilder modBuilder(module.getBodyRegion());
365       auto global = module.lookupSymbol<mlir::omp::CriticalDeclareOp>(name);
366       if (!global)
367         global = modBuilder.create<mlir::omp::CriticalDeclareOp>(
368             currentLocation, name, hint);
369       return firOpBuilder.create<mlir::omp::CriticalOp>(
370           currentLocation, mlir::FlatSymbolRefAttr::get(
371                                firOpBuilder.getContext(), global.sym_name()));
372     }
373   }();
374   createBodyOfOp<omp::CriticalOp>(criticalOp, converter, currentLocation);
375 }
376 
377 static void
378 genOMP(Fortran::lower::AbstractConverter &converter,
379        Fortran::lower::pft::Evaluation &eval,
380        const Fortran::parser::OpenMPSectionConstruct &sectionConstruct) {
381 
382   auto &firOpBuilder = converter.getFirOpBuilder();
383   auto currentLocation = converter.getCurrentLocation();
384   mlir::omp::SectionOp sectionOp =
385       firOpBuilder.create<mlir::omp::SectionOp>(currentLocation);
386   createBodyOfOp<omp::SectionOp>(sectionOp, converter, currentLocation);
387 }
388 
389 // TODO: Add support for reduction
390 static void
391 genOMP(Fortran::lower::AbstractConverter &converter,
392        Fortran::lower::pft::Evaluation &eval,
393        const Fortran::parser::OpenMPSectionsConstruct &sectionsConstruct) {
394   auto &firOpBuilder = converter.getFirOpBuilder();
395   auto currentLocation = converter.getCurrentLocation();
396   SmallVector<Value> reductionVars, allocateOperands, allocatorOperands;
397   mlir::UnitAttr noWaitClauseOperand;
398   const auto &sectionsClauseList = std::get<Fortran::parser::OmpClauseList>(
399       std::get<Fortran::parser::OmpBeginSectionsDirective>(sectionsConstruct.t)
400           .t);
401   for (const Fortran::parser::OmpClause &clause : sectionsClauseList.v) {
402 
403     // Reduction Clause
404     if (std::get_if<Fortran::parser::OmpClause::Reduction>(&clause.u)) {
405       TODO(currentLocation, "OMPC_Reduction");
406 
407       // Allocate clause
408     } else if (const auto &allocateClause =
409                    std::get_if<Fortran::parser::OmpClause::Allocate>(
410                        &clause.u)) {
411       genAllocateClause(converter, allocateClause->v, allocatorOperands,
412                         allocateOperands);
413     }
414   }
415   const auto &endSectionsClauseList =
416       std::get<Fortran::parser::OmpEndSectionsDirective>(sectionsConstruct.t);
417   const auto &clauseList =
418       std::get<Fortran::parser::OmpClauseList>(endSectionsClauseList.t);
419   for (const auto &clause : clauseList.v) {
420     // Nowait clause
421     if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u)) {
422       noWaitClauseOperand = firOpBuilder.getUnitAttr();
423     }
424   }
425 
426   llvm::omp::Directive dir =
427       std::get<Fortran::parser::OmpSectionsDirective>(
428           std::get<Fortran::parser::OmpBeginSectionsDirective>(
429               sectionsConstruct.t)
430               .t)
431           .v;
432 
433   // Parallel Sections Construct
434   if (dir == llvm::omp::Directive::OMPD_parallel_sections) {
435     auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>(
436         currentLocation, /*if_expr_var*/ nullptr, /*num_threads_var*/ nullptr,
437         allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(),
438         /*reductions=*/nullptr, /*proc_bind_val*/ nullptr);
439     createBodyOfOp(parallelOp, converter, currentLocation);
440     auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>(
441         currentLocation, /*reduction_vars*/ ValueRange(),
442         /*reductions=*/nullptr, /*allocate_vars*/ ValueRange(),
443         /*allocators_vars*/ ValueRange(), /*nowait=*/nullptr);
444     createBodyOfOp(sectionsOp, converter, currentLocation);
445 
446     // Sections Construct
447   } else if (dir == llvm::omp::Directive::OMPD_sections) {
448     auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>(
449         currentLocation, reductionVars, /*reductions = */ nullptr,
450         allocateOperands, allocatorOperands, noWaitClauseOperand);
451     createBodyOfOp<omp::SectionsOp>(sectionsOp, converter, currentLocation);
452   }
453 }
454 
455 void Fortran::lower::genOpenMPConstruct(
456     Fortran::lower::AbstractConverter &converter,
457     Fortran::lower::pft::Evaluation &eval,
458     const Fortran::parser::OpenMPConstruct &ompConstruct) {
459 
460   std::visit(
461       common::visitors{
462           [&](const Fortran::parser::OpenMPStandaloneConstruct
463                   &standaloneConstruct) {
464             genOMP(converter, eval, standaloneConstruct);
465           },
466           [&](const Fortran::parser::OpenMPSectionsConstruct
467                   &sectionsConstruct) {
468             genOMP(converter, eval, sectionsConstruct);
469           },
470           [&](const Fortran::parser::OpenMPSectionConstruct &sectionConstruct) {
471             genOMP(converter, eval, sectionConstruct);
472           },
473           [&](const Fortran::parser::OpenMPLoopConstruct &loopConstruct) {
474             TODO(converter.getCurrentLocation(), "OpenMPLoopConstruct");
475           },
476           [&](const Fortran::parser::OpenMPDeclarativeAllocate
477                   &execAllocConstruct) {
478             TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate");
479           },
480           [&](const Fortran::parser::OpenMPExecutableAllocate
481                   &execAllocConstruct) {
482             TODO(converter.getCurrentLocation(), "OpenMPExecutableAllocate");
483           },
484           [&](const Fortran::parser::OpenMPBlockConstruct &blockConstruct) {
485             genOMP(converter, eval, blockConstruct);
486           },
487           [&](const Fortran::parser::OpenMPAtomicConstruct &atomicConstruct) {
488             TODO(converter.getCurrentLocation(), "OpenMPAtomicConstruct");
489           },
490           [&](const Fortran::parser::OpenMPCriticalConstruct
491                   &criticalConstruct) {
492             genOMP(converter, eval, criticalConstruct);
493           },
494       },
495       ompConstruct.u);
496 }
497