1 //===-- Bridge.cpp -- bridge to lower to MLIR -----------------------------===//
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/Bridge.h"
14 #include "flang/Lower/Allocatable.h"
15 #include "flang/Lower/CallInterface.h"
16 #include "flang/Lower/Coarray.h"
17 #include "flang/Lower/ConvertExpr.h"
18 #include "flang/Lower/ConvertType.h"
19 #include "flang/Lower/ConvertVariable.h"
20 #include "flang/Lower/HostAssociations.h"
21 #include "flang/Lower/IO.h"
22 #include "flang/Lower/IterationSpace.h"
23 #include "flang/Lower/Mangler.h"
24 #include "flang/Lower/OpenACC.h"
25 #include "flang/Lower/OpenMP.h"
26 #include "flang/Lower/PFTBuilder.h"
27 #include "flang/Lower/Runtime.h"
28 #include "flang/Lower/StatementContext.h"
29 #include "flang/Lower/Support/Utils.h"
30 #include "flang/Optimizer/Builder/BoxValue.h"
31 #include "flang/Optimizer/Builder/Character.h"
32 #include "flang/Optimizer/Builder/FIRBuilder.h"
33 #include "flang/Optimizer/Builder/Runtime/Character.h"
34 #include "flang/Optimizer/Builder/Runtime/Ragged.h"
35 #include "flang/Optimizer/Builder/Todo.h"
36 #include "flang/Optimizer/Dialect/FIRAttr.h"
37 #include "flang/Optimizer/Dialect/FIRDialect.h"
38 #include "flang/Optimizer/Dialect/FIROps.h"
39 #include "flang/Optimizer/Support/FIRContext.h"
40 #include "flang/Optimizer/Support/FatalError.h"
41 #include "flang/Optimizer/Support/InternalNames.h"
42 #include "flang/Optimizer/Transforms/Passes.h"
43 #include "flang/Parser/parse-tree.h"
44 #include "flang/Runtime/iostat.h"
45 #include "flang/Semantics/tools.h"
46 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
47 #include "mlir/IR/PatternMatch.h"
48 #include "mlir/Parser/Parser.h"
49 #include "mlir/Transforms/RegionUtils.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 
54 #define DEBUG_TYPE "flang-lower-bridge"
55 
56 static llvm::cl::opt<bool> dumpBeforeFir(
57     "fdebug-dump-pre-fir", llvm::cl::init(false),
58     llvm::cl::desc("dump the Pre-FIR tree prior to FIR generation"));
59 
60 static llvm::cl::opt<bool> forceLoopToExecuteOnce(
61     "always-execute-loop-body", llvm::cl::init(false),
62     llvm::cl::desc("force the body of a loop to execute at least once"));
63 
64 namespace {
65 /// Information for generating a structured or unstructured increment loop.
66 struct IncrementLoopInfo {
67   template <typename T>
68   explicit IncrementLoopInfo(Fortran::semantics::Symbol &sym, const T &lower,
69                              const T &upper, const std::optional<T> &step,
70                              bool isUnordered = false)
71       : loopVariableSym{sym}, lowerExpr{Fortran::semantics::GetExpr(lower)},
72         upperExpr{Fortran::semantics::GetExpr(upper)},
73         stepExpr{Fortran::semantics::GetExpr(step)}, isUnordered{isUnordered} {}
74 
75   IncrementLoopInfo(IncrementLoopInfo &&) = default;
76   IncrementLoopInfo &operator=(IncrementLoopInfo &&x) { return x; }
77 
78   bool isStructured() const { return !headerBlock; }
79 
80   mlir::Type getLoopVariableType() const {
81     assert(loopVariable && "must be set");
82     return fir::unwrapRefType(loopVariable.getType());
83   }
84 
85   // Data members common to both structured and unstructured loops.
86   const Fortran::semantics::Symbol &loopVariableSym;
87   const Fortran::lower::SomeExpr *lowerExpr;
88   const Fortran::lower::SomeExpr *upperExpr;
89   const Fortran::lower::SomeExpr *stepExpr;
90   const Fortran::lower::SomeExpr *maskExpr = nullptr;
91   bool isUnordered; // do concurrent, forall
92   llvm::SmallVector<const Fortran::semantics::Symbol *> localInitSymList;
93   llvm::SmallVector<const Fortran::semantics::Symbol *> sharedSymList;
94   mlir::Value loopVariable = nullptr;
95   mlir::Value stepValue = nullptr; // possible uses in multiple blocks
96 
97   // Data members for structured loops.
98   fir::DoLoopOp doLoop = nullptr;
99 
100   // Data members for unstructured loops.
101   bool hasRealControl = false;
102   mlir::Value tripVariable = nullptr;
103   mlir::Block *headerBlock = nullptr; // loop entry and test block
104   mlir::Block *maskBlock = nullptr;   // concurrent loop mask block
105   mlir::Block *bodyBlock = nullptr;   // first loop body block
106   mlir::Block *exitBlock = nullptr;   // loop exit target block
107 };
108 
109 /// Helper class to generate the runtime type info global data. This data
110 /// is required to describe the derived type to the runtime so that it can
111 /// operate over it. It must be ensured this data will be generated for every
112 /// derived type lowered in the current translated unit. However, this data
113 /// cannot be generated before FuncOp have been created for functions since the
114 /// initializers may take their address (e.g for type bound procedures). This
115 /// class allows registering all the required runtime type info while it is not
116 /// possible to create globals, and to generate this data after function
117 /// lowering.
118 class RuntimeTypeInfoConverter {
119   /// Store the location and symbols of derived type info to be generated.
120   /// The location of the derived type instantiation is also stored because
121   /// runtime type descriptor symbol are compiler generated and cannot be mapped
122   /// to user code on their own.
123   struct TypeInfoSymbol {
124     Fortran::semantics::SymbolRef symbol;
125     mlir::Location loc;
126   };
127 
128 public:
129   void registerTypeInfoSymbol(Fortran::lower::AbstractConverter &converter,
130                               mlir::Location loc,
131                               Fortran::semantics::SymbolRef typeInfoSym) {
132     if (seen.contains(typeInfoSym))
133       return;
134     seen.insert(typeInfoSym);
135     if (!skipRegistration) {
136       registeredTypeInfoSymbols.emplace_back(TypeInfoSymbol{typeInfoSym, loc});
137       return;
138     }
139     // Once the registration is closed, symbols cannot be added to the
140     // registeredTypeInfoSymbols list because it may be iterated over.
141     // However, after registration is closed, it is safe to directly generate
142     // the globals because all FuncOps whose addresses may be required by the
143     // initializers have been generated.
144     Fortran::lower::createRuntimeTypeInfoGlobal(converter, loc,
145                                                 typeInfoSym.get());
146   }
147 
148   void createTypeInfoGlobals(Fortran::lower::AbstractConverter &converter) {
149     skipRegistration = true;
150     for (const TypeInfoSymbol &info : registeredTypeInfoSymbols)
151       Fortran::lower::createRuntimeTypeInfoGlobal(converter, info.loc,
152                                                   info.symbol.get());
153     registeredTypeInfoSymbols.clear();
154   }
155 
156 private:
157   /// Store the runtime type descriptors that will be required for the
158   /// derived type that have been converted to FIR derived types.
159   llvm::SmallVector<TypeInfoSymbol> registeredTypeInfoSymbols;
160   /// Create derived type runtime info global immediately without storing the
161   /// symbol in registeredTypeInfoSymbols.
162   bool skipRegistration = false;
163   /// Track symbols symbols processed during and after the registration
164   /// to avoid infinite loops between type conversions and global variable
165   /// creation.
166   llvm::SmallSetVector<Fortran::semantics::SymbolRef, 64> seen;
167 };
168 
169 using IncrementLoopNestInfo = llvm::SmallVector<IncrementLoopInfo>;
170 } // namespace
171 
172 //===----------------------------------------------------------------------===//
173 // FirConverter
174 //===----------------------------------------------------------------------===//
175 
176 namespace {
177 
178 /// Traverse the pre-FIR tree (PFT) to generate the FIR dialect of MLIR.
179 class FirConverter : public Fortran::lower::AbstractConverter {
180 public:
181   explicit FirConverter(Fortran::lower::LoweringBridge &bridge)
182       : bridge{bridge}, foldingContext{bridge.createFoldingContext()} {}
183   virtual ~FirConverter() = default;
184 
185   /// Convert the PFT to FIR.
186   void run(Fortran::lower::pft::Program &pft) {
187     // Preliminary translation pass.
188 
189     // - Lower common blocks from the PFT common block list that contains a
190     // consolidated list of the common blocks (with the initialization if any in
191     // the Program, and with the common block biggest size in all its
192     // appearance). This is done before lowering any scope declarations because
193     // it is not know at the local scope level what MLIR type common blocks
194     // should have to suit all its usage in the compilation unit.
195     lowerCommonBlocks(pft.getCommonBlocks());
196 
197     //  - Declare all functions that have definitions so that definition
198     //    signatures prevail over call site signatures.
199     //  - Define module variables and OpenMP/OpenACC declarative construct so
200     //    that they are available before lowering any function that may use
201     //    them.
202     for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
203       std::visit(Fortran::common::visitors{
204                      [&](Fortran::lower::pft::FunctionLikeUnit &f) {
205                        declareFunction(f);
206                      },
207                      [&](Fortran::lower::pft::ModuleLikeUnit &m) {
208                        lowerModuleDeclScope(m);
209                        for (Fortran::lower::pft::FunctionLikeUnit &f :
210                             m.nestedFunctions)
211                          declareFunction(f);
212                      },
213                      [&](Fortran::lower::pft::BlockDataUnit &b) {},
214                      [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {},
215                  },
216                  u);
217     }
218 
219     // Primary translation pass.
220     for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
221       std::visit(
222           Fortran::common::visitors{
223               [&](Fortran::lower::pft::FunctionLikeUnit &f) { lowerFunc(f); },
224               [&](Fortran::lower::pft::ModuleLikeUnit &m) { lowerMod(m); },
225               [&](Fortran::lower::pft::BlockDataUnit &b) {},
226               [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {
227                 setCurrentPosition(
228                     d.get<Fortran::parser::CompilerDirective>().source);
229                 mlir::emitWarning(toLocation(),
230                                   "ignoring all compiler directives");
231               },
232           },
233           u);
234     }
235 
236     /// Once all the code has been translated, create runtime type info
237     /// global data structure for the derived types that have been
238     /// processed.
239     createGlobalOutsideOfFunctionLowering(
240         [&]() { runtimeTypeInfoConverter.createTypeInfoGlobals(*this); });
241   }
242 
243   /// Declare a function.
244   void declareFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
245     setCurrentPosition(funit.getStartingSourceLoc());
246     for (int entryIndex = 0, last = funit.entryPointList.size();
247          entryIndex < last; ++entryIndex) {
248       funit.setActiveEntry(entryIndex);
249       // Calling CalleeInterface ctor will build a declaration
250       // mlir::func::FuncOp with no other side effects.
251       // TODO: when doing some compiler profiling on real apps, it may be worth
252       // to check it's better to save the CalleeInterface instead of recomputing
253       // it later when lowering the body. CalleeInterface ctor should be linear
254       // with the number of arguments, so it is not awful to do it that way for
255       // now, but the linear coefficient might be non negligible. Until
256       // measured, stick to the solution that impacts the code less.
257       Fortran::lower::CalleeInterface{funit, *this};
258     }
259     funit.setActiveEntry(0);
260 
261     // Compute the set of host associated entities from the nested functions.
262     llvm::SetVector<const Fortran::semantics::Symbol *> escapeHost;
263     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
264       collectHostAssociatedVariables(f, escapeHost);
265     funit.setHostAssociatedSymbols(escapeHost);
266 
267     // Declare internal procedures
268     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
269       declareFunction(f);
270   }
271 
272   /// Collects the canonical list of all host associated symbols. These bindings
273   /// must be aggregated into a tuple which can then be added to each of the
274   /// internal procedure declarations and passed at each call site.
275   void collectHostAssociatedVariables(
276       Fortran::lower::pft::FunctionLikeUnit &funit,
277       llvm::SetVector<const Fortran::semantics::Symbol *> &escapees) {
278     const Fortran::semantics::Scope *internalScope =
279         funit.getSubprogramSymbol().scope();
280     assert(internalScope && "internal procedures symbol must create a scope");
281     auto addToListIfEscapee = [&](const Fortran::semantics::Symbol &sym) {
282       const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
283       const auto *namelistDetails =
284           ultimate.detailsIf<Fortran::semantics::NamelistDetails>();
285       if (ultimate.has<Fortran::semantics::ObjectEntityDetails>() ||
286           Fortran::semantics::IsProcedurePointer(ultimate) ||
287           Fortran::semantics::IsDummy(sym) || namelistDetails) {
288         const Fortran::semantics::Scope &ultimateScope = ultimate.owner();
289         if (ultimateScope.kind() ==
290                 Fortran::semantics::Scope::Kind::MainProgram ||
291             ultimateScope.kind() == Fortran::semantics::Scope::Kind::Subprogram)
292           if (ultimateScope != *internalScope &&
293               ultimateScope.Contains(*internalScope)) {
294             if (namelistDetails) {
295               // So far, namelist symbols are processed on the fly in IO and
296               // the related namelist data structure is not added to the symbol
297               // map, so it cannot be passed to the internal procedures.
298               // Instead, all the symbols of the host namelist used in the
299               // internal procedure must be considered as host associated so
300               // that IO lowering can find them when needed.
301               for (const auto &namelistObject : namelistDetails->objects())
302                 escapees.insert(&*namelistObject);
303             } else {
304               escapees.insert(&ultimate);
305             }
306           }
307       }
308     };
309     Fortran::lower::pft::visitAllSymbols(funit, addToListIfEscapee);
310   }
311 
312   //===--------------------------------------------------------------------===//
313   // AbstractConverter overrides
314   //===--------------------------------------------------------------------===//
315 
316   mlir::Value getSymbolAddress(Fortran::lower::SymbolRef sym) override final {
317     return lookupSymbol(sym).getAddr();
318   }
319 
320   fir::ExtendedValue
321   getSymbolExtendedValue(const Fortran::semantics::Symbol &sym) override final {
322     Fortran::lower::SymbolBox sb = localSymbols.lookupSymbol(sym);
323     assert(sb && "symbol box not found");
324     return sb.toExtendedValue();
325   }
326 
327   mlir::Value impliedDoBinding(llvm::StringRef name) override final {
328     mlir::Value val = localSymbols.lookupImpliedDo(name);
329     if (!val)
330       fir::emitFatalError(toLocation(), "ac-do-variable has no binding");
331     return val;
332   }
333 
334   void copySymbolBinding(Fortran::lower::SymbolRef src,
335                          Fortran::lower::SymbolRef target) override final {
336     localSymbols.addSymbol(target, lookupSymbol(src).toExtendedValue());
337   }
338 
339   /// Add the symbol binding to the inner-most level of the symbol map and
340   /// return true if it is not already present. Otherwise, return false.
341   bool bindIfNewSymbol(Fortran::lower::SymbolRef sym,
342                        const fir::ExtendedValue &exval) {
343     if (shallowLookupSymbol(sym))
344       return false;
345     bindSymbol(sym, exval);
346     return true;
347   }
348 
349   void bindSymbol(Fortran::lower::SymbolRef sym,
350                   const fir::ExtendedValue &exval) override final {
351     localSymbols.addSymbol(sym, exval, /*forced=*/true);
352   }
353 
354   bool lookupLabelSet(Fortran::lower::SymbolRef sym,
355                       Fortran::lower::pft::LabelSet &labelSet) override final {
356     Fortran::lower::pft::FunctionLikeUnit &owningProc =
357         *getEval().getOwningProcedure();
358     auto iter = owningProc.assignSymbolLabelMap.find(sym);
359     if (iter == owningProc.assignSymbolLabelMap.end())
360       return false;
361     labelSet = iter->second;
362     return true;
363   }
364 
365   Fortran::lower::pft::Evaluation *
366   lookupLabel(Fortran::lower::pft::Label label) override final {
367     Fortran::lower::pft::FunctionLikeUnit &owningProc =
368         *getEval().getOwningProcedure();
369     auto iter = owningProc.labelEvaluationMap.find(label);
370     if (iter == owningProc.labelEvaluationMap.end())
371       return nullptr;
372     return iter->second;
373   }
374 
375   fir::ExtendedValue genExprAddr(const Fortran::lower::SomeExpr &expr,
376                                  Fortran::lower::StatementContext &context,
377                                  mlir::Location *loc = nullptr) override final {
378     return Fortran::lower::createSomeExtendedAddress(
379         loc ? *loc : toLocation(), *this, expr, localSymbols, context);
380   }
381   fir::ExtendedValue
382   genExprValue(const Fortran::lower::SomeExpr &expr,
383                Fortran::lower::StatementContext &context,
384                mlir::Location *loc = nullptr) override final {
385     return Fortran::lower::createSomeExtendedExpression(
386         loc ? *loc : toLocation(), *this, expr, localSymbols, context);
387   }
388 
389   fir::ExtendedValue
390   genExprBox(mlir::Location loc, const Fortran::lower::SomeExpr &expr,
391              Fortran::lower::StatementContext &stmtCtx) override final {
392     return Fortran::lower::createBoxValue(loc, *this, expr, localSymbols,
393                                           stmtCtx);
394   }
395 
396   Fortran::evaluate::FoldingContext &getFoldingContext() override final {
397     return foldingContext;
398   }
399 
400   mlir::Type genType(const Fortran::lower::SomeExpr &expr) override final {
401     return Fortran::lower::translateSomeExprToFIRType(*this, expr);
402   }
403   mlir::Type genType(const Fortran::lower::pft::Variable &var) override final {
404     return Fortran::lower::translateVariableToFIRType(*this, var);
405   }
406   mlir::Type genType(Fortran::lower::SymbolRef sym) override final {
407     return Fortran::lower::translateSymbolToFIRType(*this, sym);
408   }
409   mlir::Type
410   genType(Fortran::common::TypeCategory tc, int kind,
411           llvm::ArrayRef<std::int64_t> lenParameters) override final {
412     return Fortran::lower::getFIRType(&getMLIRContext(), tc, kind,
413                                       lenParameters);
414   }
415   mlir::Type
416   genType(const Fortran::semantics::DerivedTypeSpec &tySpec) override final {
417     return Fortran::lower::translateDerivedTypeToFIRType(*this, tySpec);
418   }
419   mlir::Type genType(Fortran::common::TypeCategory tc) override final {
420     return Fortran::lower::getFIRType(
421         &getMLIRContext(), tc, bridge.getDefaultKinds().GetDefaultKind(tc),
422         llvm::None);
423   }
424 
425   bool createHostAssociateVarClone(
426       const Fortran::semantics::Symbol &sym) override final {
427     mlir::Location loc = genLocation(sym.name());
428     mlir::Type symType = genType(sym);
429     const auto *details = sym.detailsIf<Fortran::semantics::HostAssocDetails>();
430     assert(details && "No host-association found");
431     const Fortran::semantics::Symbol &hsym = details->symbol();
432     Fortran::lower::SymbolBox hsb = lookupSymbol(hsym);
433 
434     auto allocate = [&](llvm::ArrayRef<mlir::Value> shape,
435                         llvm::ArrayRef<mlir::Value> typeParams) -> mlir::Value {
436       mlir::Value allocVal = builder->allocateLocal(
437           loc, symType, mangleName(sym), toStringRef(sym.GetUltimate().name()),
438           /*pinned=*/true, shape, typeParams,
439           sym.GetUltimate().attrs().test(Fortran::semantics::Attr::TARGET));
440       return allocVal;
441     };
442 
443     fir::ExtendedValue hexv = getExtendedValue(hsb);
444     fir::ExtendedValue exv = hexv.match(
445         [&](const fir::BoxValue &box) -> fir::ExtendedValue {
446           const Fortran::semantics::DeclTypeSpec *type = sym.GetType();
447           if (type && type->IsPolymorphic())
448             TODO(loc, "create polymorphic host associated copy");
449           // Create a contiguous temp with the same shape and length as
450           // the original variable described by a fir.box.
451           llvm::SmallVector<mlir::Value> extents =
452               fir::factory::getExtents(loc, *builder, hexv);
453           if (box.isDerivedWithLenParameters())
454             TODO(loc, "get length parameters from derived type BoxValue");
455           if (box.isCharacter()) {
456             mlir::Value len = fir::factory::readCharLen(*builder, loc, box);
457             mlir::Value temp = allocate(extents, {len});
458             return fir::CharArrayBoxValue{temp, len, extents};
459           }
460           return fir::ArrayBoxValue{allocate(extents, {}), extents};
461         },
462         [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
463           // Allocate storage for a pointer/allocatble descriptor.
464           // No shape/lengths to be passed to the alloca.
465           return fir::MutableBoxValue(allocate({}, {}),
466                                       box.nonDeferredLenParams(), {});
467         },
468         [&](const auto &) -> fir::ExtendedValue {
469           mlir::Value temp =
470               allocate(fir::factory::getExtents(loc, *builder, hexv),
471                        fir::factory::getTypeParams(loc, *builder, hexv));
472           return fir::substBase(hexv, temp);
473         });
474 
475     // Replace all uses of the original with the clone/copy,
476     // esepcially for loop bounds (that uses the variable being privatised)
477     // since loop bounds use old values that need to be fixed by using the
478     // new copied value.
479     // Not able to use replaceAllUsesWith() because uses outside
480     // the loop body should not use the clone.
481     mlir::Region &curRegion = getFirOpBuilder().getRegion();
482     mlir::Value oldVal = fir::getBase(hexv);
483     mlir::Value cloneVal = fir::getBase(exv);
484     for (auto &oper : curRegion.getOps()) {
485       for (unsigned int ii = 0; ii < oper.getNumOperands(); ++ii) {
486         if (oper.getOperand(ii) == oldVal) {
487           oper.setOperand(ii, cloneVal);
488         }
489       }
490     }
491     return bindIfNewSymbol(sym, exv);
492   }
493 
494   void
495   copyHostAssociateVar(const Fortran::semantics::Symbol &sym) override final {
496     // 1) Fetch the original copy of the variable.
497     assert(sym.has<Fortran::semantics::HostAssocDetails>() &&
498            "No host-association found");
499     const Fortran::semantics::Symbol &hsym = sym.GetUltimate();
500     Fortran::lower::SymbolBox hsb = lookupOneLevelUpSymbol(hsym);
501     assert(hsb && "Host symbol box not found");
502     fir::ExtendedValue hexv = getExtendedValue(hsb);
503 
504     // 2) Fetch the copied one that will mask the original.
505     Fortran::lower::SymbolBox sb = shallowLookupSymbol(sym);
506     assert(sb && "Host-associated symbol box not found");
507     assert(hsb.getAddr() != sb.getAddr() &&
508            "Host and associated symbol boxes are the same");
509     fir::ExtendedValue exv = getExtendedValue(sb);
510 
511     // 3) Perform the assignment.
512     builder->setInsertionPointAfter(fir::getBase(exv).getDefiningOp());
513     mlir::Location loc = genLocation(sym.name());
514     mlir::Type symType = genType(sym);
515     if (auto seqTy = symType.dyn_cast<fir::SequenceType>()) {
516       Fortran::lower::StatementContext stmtCtx;
517       Fortran::lower::createSomeArrayAssignment(*this, exv, hexv, localSymbols,
518                                                 stmtCtx);
519       stmtCtx.finalize();
520     } else if (hexv.getBoxOf<fir::CharBoxValue>()) {
521       fir::factory::CharacterExprHelper{*builder, loc}.createAssign(exv, hexv);
522     } else if (hexv.getBoxOf<fir::MutableBoxValue>()) {
523       TODO(loc, "firstprivatisation of allocatable variables");
524     } else {
525       auto loadVal = builder->create<fir::LoadOp>(loc, fir::getBase(hexv));
526       builder->create<fir::StoreOp>(loc, loadVal, fir::getBase(exv));
527     }
528   }
529 
530   //===--------------------------------------------------------------------===//
531   // Utility methods
532   //===--------------------------------------------------------------------===//
533 
534   void collectSymbolSet(
535       Fortran::lower::pft::Evaluation &eval,
536       llvm::SetVector<const Fortran::semantics::Symbol *> &symbolSet,
537       Fortran::semantics::Symbol::Flag flag,
538       bool isUltimateSymbol) override final {
539     auto addToList = [&](const Fortran::semantics::Symbol &sym) {
540       const Fortran::semantics::Symbol &symbol =
541           isUltimateSymbol ? sym.GetUltimate() : sym;
542       if (symbol.test(flag))
543         symbolSet.insert(&symbol);
544     };
545     Fortran::lower::pft::visitAllSymbols(eval, addToList);
546   }
547 
548   mlir::Location getCurrentLocation() override final { return toLocation(); }
549 
550   /// Generate a dummy location.
551   mlir::Location genUnknownLocation() override final {
552     // Note: builder may not be instantiated yet
553     return mlir::UnknownLoc::get(&getMLIRContext());
554   }
555 
556   /// Generate a `Location` from the `CharBlock`.
557   mlir::Location
558   genLocation(const Fortran::parser::CharBlock &block) override final {
559     if (const Fortran::parser::AllCookedSources *cooked =
560             bridge.getCookedSource()) {
561       if (std::optional<std::pair<Fortran::parser::SourcePosition,
562                                   Fortran::parser::SourcePosition>>
563               loc = cooked->GetSourcePositionRange(block)) {
564         // loc is a pair (begin, end); use the beginning position
565         Fortran::parser::SourcePosition &filePos = loc->first;
566         return mlir::FileLineColLoc::get(&getMLIRContext(), filePos.file.path(),
567                                          filePos.line, filePos.column);
568       }
569     }
570     return genUnknownLocation();
571   }
572 
573   fir::FirOpBuilder &getFirOpBuilder() override final { return *builder; }
574 
575   mlir::ModuleOp &getModuleOp() override final { return bridge.getModule(); }
576 
577   mlir::MLIRContext &getMLIRContext() override final {
578     return bridge.getMLIRContext();
579   }
580   std::string
581   mangleName(const Fortran::semantics::Symbol &symbol) override final {
582     return Fortran::lower::mangle::mangleName(symbol);
583   }
584 
585   const fir::KindMapping &getKindMap() override final {
586     return bridge.getKindMap();
587   }
588 
589   mlir::Value hostAssocTupleValue() override final { return hostAssocTuple; }
590 
591   /// Record a binding for the ssa-value of the tuple for this function.
592   void bindHostAssocTuple(mlir::Value val) override final {
593     assert(!hostAssocTuple && val);
594     hostAssocTuple = val;
595   }
596 
597   void registerRuntimeTypeInfo(
598       mlir::Location loc,
599       Fortran::lower::SymbolRef typeInfoSym) override final {
600     runtimeTypeInfoConverter.registerTypeInfoSymbol(*this, loc, typeInfoSym);
601   }
602 
603 private:
604   FirConverter() = delete;
605   FirConverter(const FirConverter &) = delete;
606   FirConverter &operator=(const FirConverter &) = delete;
607 
608   //===--------------------------------------------------------------------===//
609   // Helper member functions
610   //===--------------------------------------------------------------------===//
611 
612   mlir::Value createFIRExpr(mlir::Location loc,
613                             const Fortran::lower::SomeExpr *expr,
614                             Fortran::lower::StatementContext &stmtCtx) {
615     return fir::getBase(genExprValue(*expr, stmtCtx, &loc));
616   }
617 
618   /// Find the symbol in the local map or return null.
619   Fortran::lower::SymbolBox
620   lookupSymbol(const Fortran::semantics::Symbol &sym) {
621     if (Fortran::lower::SymbolBox v = localSymbols.lookupSymbol(sym))
622       return v;
623     return {};
624   }
625 
626   /// Find the symbol in the inner-most level of the local map or return null.
627   Fortran::lower::SymbolBox
628   shallowLookupSymbol(const Fortran::semantics::Symbol &sym) {
629     if (Fortran::lower::SymbolBox v = localSymbols.shallowLookupSymbol(sym))
630       return v;
631     return {};
632   }
633 
634   /// Find the symbol in one level up of symbol map such as for host-association
635   /// in OpenMP code or return null.
636   Fortran::lower::SymbolBox
637   lookupOneLevelUpSymbol(const Fortran::semantics::Symbol &sym) {
638     if (Fortran::lower::SymbolBox v = localSymbols.lookupOneLevelUpSymbol(sym))
639       return v;
640     return {};
641   }
642 
643   /// Add the symbol to the local map and return `true`. If the symbol is
644   /// already in the map and \p forced is `false`, the map is not updated.
645   /// Instead the value `false` is returned.
646   bool addSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val,
647                  bool forced = false) {
648     if (!forced && lookupSymbol(sym))
649       return false;
650     localSymbols.addSymbol(sym, val, forced);
651     return true;
652   }
653 
654   bool addCharSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val,
655                      mlir::Value len, bool forced = false) {
656     if (!forced && lookupSymbol(sym))
657       return false;
658     // TODO: ensure val type is fir.array<len x fir.char<kind>> like. Insert
659     // cast if needed.
660     localSymbols.addCharSymbol(sym, val, len, forced);
661     return true;
662   }
663 
664   fir::ExtendedValue getExtendedValue(Fortran::lower::SymbolBox sb) {
665     return sb.match(
666         [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &box) {
667           return fir::factory::genMutableBoxRead(*builder, getCurrentLocation(),
668                                                  box);
669         },
670         [&sb](auto &) { return sb.toExtendedValue(); });
671   }
672 
673   /// Generate the address of loop variable \p sym.
674   /// If \p sym is not mapped yet, allocate local storage for it.
675   mlir::Value genLoopVariableAddress(mlir::Location loc,
676                                      const Fortran::semantics::Symbol &sym,
677                                      bool isUnordered) {
678     if (isUnordered || sym.has<Fortran::semantics::HostAssocDetails>() ||
679         sym.has<Fortran::semantics::UseDetails>()) {
680       if (!shallowLookupSymbol(sym)) {
681         // Do concurrent loop variables are not mapped yet since they are local
682         // to the Do concurrent scope (same for OpenMP loops).
683         auto newVal = builder->createTemporary(loc, genType(sym),
684                                                toStringRef(sym.name()));
685         bindIfNewSymbol(sym, newVal);
686         return newVal;
687       }
688     }
689     auto entry = lookupSymbol(sym);
690     (void)entry;
691     assert(entry && "loop control variable must already be in map");
692     Fortran::lower::StatementContext stmtCtx;
693     return fir::getBase(
694         genExprAddr(Fortran::evaluate::AsGenericExpr(sym).value(), stmtCtx));
695   }
696 
697   static bool isNumericScalarCategory(Fortran::common::TypeCategory cat) {
698     return cat == Fortran::common::TypeCategory::Integer ||
699            cat == Fortran::common::TypeCategory::Real ||
700            cat == Fortran::common::TypeCategory::Complex ||
701            cat == Fortran::common::TypeCategory::Logical;
702   }
703   static bool isLogicalCategory(Fortran::common::TypeCategory cat) {
704     return cat == Fortran::common::TypeCategory::Logical;
705   }
706   static bool isCharacterCategory(Fortran::common::TypeCategory cat) {
707     return cat == Fortran::common::TypeCategory::Character;
708   }
709   static bool isDerivedCategory(Fortran::common::TypeCategory cat) {
710     return cat == Fortran::common::TypeCategory::Derived;
711   }
712 
713   /// Insert a new block before \p block.  Leave the insertion point unchanged.
714   mlir::Block *insertBlock(mlir::Block *block) {
715     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
716     mlir::Block *newBlock = builder->createBlock(block);
717     builder->restoreInsertionPoint(insertPt);
718     return newBlock;
719   }
720 
721   mlir::Block *blockOfLabel(Fortran::lower::pft::Evaluation &eval,
722                             Fortran::parser::Label label) {
723     const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap =
724         eval.getOwningProcedure()->labelEvaluationMap;
725     const auto iter = labelEvaluationMap.find(label);
726     assert(iter != labelEvaluationMap.end() && "label missing from map");
727     mlir::Block *block = iter->second->block;
728     assert(block && "missing labeled evaluation block");
729     return block;
730   }
731 
732   void genFIRBranch(mlir::Block *targetBlock) {
733     assert(targetBlock && "missing unconditional target block");
734     builder->create<mlir::cf::BranchOp>(toLocation(), targetBlock);
735   }
736 
737   void genFIRConditionalBranch(mlir::Value cond, mlir::Block *trueTarget,
738                                mlir::Block *falseTarget) {
739     assert(trueTarget && "missing conditional branch true block");
740     assert(falseTarget && "missing conditional branch false block");
741     mlir::Location loc = toLocation();
742     mlir::Value bcc = builder->createConvert(loc, builder->getI1Type(), cond);
743     builder->create<mlir::cf::CondBranchOp>(loc, bcc, trueTarget, llvm::None,
744                                             falseTarget, llvm::None);
745   }
746   void genFIRConditionalBranch(mlir::Value cond,
747                                Fortran::lower::pft::Evaluation *trueTarget,
748                                Fortran::lower::pft::Evaluation *falseTarget) {
749     genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block);
750   }
751   void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr,
752                                mlir::Block *trueTarget,
753                                mlir::Block *falseTarget) {
754     Fortran::lower::StatementContext stmtCtx;
755     mlir::Value cond =
756         createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx);
757     stmtCtx.finalize();
758     genFIRConditionalBranch(cond, trueTarget, falseTarget);
759   }
760   void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr,
761                                Fortran::lower::pft::Evaluation *trueTarget,
762                                Fortran::lower::pft::Evaluation *falseTarget) {
763     Fortran::lower::StatementContext stmtCtx;
764     mlir::Value cond =
765         createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx);
766     stmtCtx.finalize();
767     genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block);
768   }
769 
770   //===--------------------------------------------------------------------===//
771   // Termination of symbolically referenced execution units
772   //===--------------------------------------------------------------------===//
773 
774   /// END of program
775   ///
776   /// Generate the cleanup block before the program exits
777   void genExitRoutine() {
778     if (blockIsUnterminated())
779       builder->create<mlir::func::ReturnOp>(toLocation());
780   }
781   void genFIR(const Fortran::parser::EndProgramStmt &) { genExitRoutine(); }
782 
783   /// END of procedure-like constructs
784   ///
785   /// Generate the cleanup block before the procedure exits
786   void genReturnSymbol(const Fortran::semantics::Symbol &functionSymbol) {
787     const Fortran::semantics::Symbol &resultSym =
788         functionSymbol.get<Fortran::semantics::SubprogramDetails>().result();
789     Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym);
790     mlir::Location loc = toLocation();
791     if (!resultSymBox) {
792       mlir::emitError(loc, "internal error when processing function return");
793       return;
794     }
795     mlir::Value resultVal = resultSymBox.match(
796         [&](const fir::CharBoxValue &x) -> mlir::Value {
797           return fir::factory::CharacterExprHelper{*builder, loc}
798               .createEmboxChar(x.getBuffer(), x.getLen());
799         },
800         [&](const auto &) -> mlir::Value {
801           mlir::Value resultRef = resultSymBox.getAddr();
802           mlir::Type resultType = genType(resultSym);
803           mlir::Type resultRefType = builder->getRefType(resultType);
804           // A function with multiple entry points returning different types
805           // tags all result variables with one of the largest types to allow
806           // them to share the same storage.  Convert this to the actual type.
807           if (resultRef.getType() != resultRefType)
808             resultRef = builder->createConvert(loc, resultRefType, resultRef);
809           return builder->create<fir::LoadOp>(loc, resultRef);
810         });
811     builder->create<mlir::func::ReturnOp>(loc, resultVal);
812   }
813 
814   /// Get the return value of a call to \p symbol, which is a subroutine entry
815   /// point that has alternative return specifiers.
816   const mlir::Value
817   getAltReturnResult(const Fortran::semantics::Symbol &symbol) {
818     assert(Fortran::semantics::HasAlternateReturns(symbol) &&
819            "subroutine does not have alternate returns");
820     return getSymbolAddress(symbol);
821   }
822 
823   void genFIRProcedureExit(Fortran::lower::pft::FunctionLikeUnit &funit,
824                            const Fortran::semantics::Symbol &symbol) {
825     if (mlir::Block *finalBlock = funit.finalBlock) {
826       // The current block must end with a terminator.
827       if (blockIsUnterminated())
828         builder->create<mlir::cf::BranchOp>(toLocation(), finalBlock);
829       // Set insertion point to final block.
830       builder->setInsertionPoint(finalBlock, finalBlock->end());
831     }
832     if (Fortran::semantics::IsFunction(symbol)) {
833       genReturnSymbol(symbol);
834     } else if (Fortran::semantics::HasAlternateReturns(symbol)) {
835       mlir::Value retval = builder->create<fir::LoadOp>(
836           toLocation(), getAltReturnResult(symbol));
837       builder->create<mlir::func::ReturnOp>(toLocation(), retval);
838     } else {
839       genExitRoutine();
840     }
841   }
842 
843   //
844   // Statements that have control-flow semantics
845   //
846 
847   /// Generate an If[Then]Stmt condition or its negation.
848   template <typename A>
849   mlir::Value genIfCondition(const A *stmt, bool negate = false) {
850     mlir::Location loc = toLocation();
851     Fortran::lower::StatementContext stmtCtx;
852     mlir::Value condExpr = createFIRExpr(
853         loc,
854         Fortran::semantics::GetExpr(
855             std::get<Fortran::parser::ScalarLogicalExpr>(stmt->t)),
856         stmtCtx);
857     stmtCtx.finalize();
858     mlir::Value cond =
859         builder->createConvert(loc, builder->getI1Type(), condExpr);
860     if (negate)
861       cond = builder->create<mlir::arith::XOrIOp>(
862           loc, cond, builder->createIntegerConstant(loc, cond.getType(), 1));
863     return cond;
864   }
865 
866   mlir::func::FuncOp getFunc(llvm::StringRef name, mlir::FunctionType ty) {
867     if (mlir::func::FuncOp func = builder->getNamedFunction(name)) {
868       assert(func.getFunctionType() == ty);
869       return func;
870     }
871     return builder->createFunction(toLocation(), name, ty);
872   }
873 
874   /// Lowering of CALL statement
875   void genFIR(const Fortran::parser::CallStmt &stmt) {
876     Fortran::lower::StatementContext stmtCtx;
877     Fortran::lower::pft::Evaluation &eval = getEval();
878     setCurrentPosition(stmt.v.source);
879     assert(stmt.typedCall && "Call was not analyzed");
880     // Call statement lowering shares code with function call lowering.
881     mlir::Value res = Fortran::lower::createSubroutineCall(
882         *this, *stmt.typedCall, explicitIterSpace, implicitIterSpace,
883         localSymbols, stmtCtx, /*isUserDefAssignment=*/false);
884     if (!res)
885       return; // "Normal" subroutine call.
886     // Call with alternate return specifiers.
887     // The call returns an index that selects an alternate return branch target.
888     llvm::SmallVector<int64_t> indexList;
889     llvm::SmallVector<mlir::Block *> blockList;
890     int64_t index = 0;
891     for (const Fortran::parser::ActualArgSpec &arg :
892          std::get<std::list<Fortran::parser::ActualArgSpec>>(stmt.v.t)) {
893       const auto &actual = std::get<Fortran::parser::ActualArg>(arg.t);
894       if (const auto *altReturn =
895               std::get_if<Fortran::parser::AltReturnSpec>(&actual.u)) {
896         indexList.push_back(++index);
897         blockList.push_back(blockOfLabel(eval, altReturn->v));
898       }
899     }
900     blockList.push_back(eval.nonNopSuccessor().block); // default = fallthrough
901     stmtCtx.finalize();
902     builder->create<fir::SelectOp>(toLocation(), res, indexList, blockList);
903   }
904 
905   void genFIR(const Fortran::parser::ComputedGotoStmt &stmt) {
906     Fortran::lower::StatementContext stmtCtx;
907     Fortran::lower::pft::Evaluation &eval = getEval();
908     mlir::Value selectExpr =
909         createFIRExpr(toLocation(),
910                       Fortran::semantics::GetExpr(
911                           std::get<Fortran::parser::ScalarIntExpr>(stmt.t)),
912                       stmtCtx);
913     stmtCtx.finalize();
914     llvm::SmallVector<int64_t> indexList;
915     llvm::SmallVector<mlir::Block *> blockList;
916     int64_t index = 0;
917     for (Fortran::parser::Label label :
918          std::get<std::list<Fortran::parser::Label>>(stmt.t)) {
919       indexList.push_back(++index);
920       blockList.push_back(blockOfLabel(eval, label));
921     }
922     blockList.push_back(eval.nonNopSuccessor().block); // default
923     builder->create<fir::SelectOp>(toLocation(), selectExpr, indexList,
924                                    blockList);
925   }
926 
927   void genFIR(const Fortran::parser::ArithmeticIfStmt &stmt) {
928     Fortran::lower::StatementContext stmtCtx;
929     Fortran::lower::pft::Evaluation &eval = getEval();
930     mlir::Value expr = createFIRExpr(
931         toLocation(),
932         Fortran::semantics::GetExpr(std::get<Fortran::parser::Expr>(stmt.t)),
933         stmtCtx);
934     stmtCtx.finalize();
935     mlir::Type exprType = expr.getType();
936     mlir::Location loc = toLocation();
937     if (exprType.isSignlessInteger()) {
938       // Arithmetic expression has Integer type.  Generate a SelectCaseOp
939       // with ranges {(-inf:-1], 0=default, [1:inf)}.
940       mlir::MLIRContext *context = builder->getContext();
941       llvm::SmallVector<mlir::Attribute> attrList;
942       llvm::SmallVector<mlir::Value> valueList;
943       llvm::SmallVector<mlir::Block *> blockList;
944       attrList.push_back(fir::UpperBoundAttr::get(context));
945       valueList.push_back(builder->createIntegerConstant(loc, exprType, -1));
946       blockList.push_back(blockOfLabel(eval, std::get<1>(stmt.t)));
947       attrList.push_back(fir::LowerBoundAttr::get(context));
948       valueList.push_back(builder->createIntegerConstant(loc, exprType, 1));
949       blockList.push_back(blockOfLabel(eval, std::get<3>(stmt.t)));
950       attrList.push_back(mlir::UnitAttr::get(context)); // 0 is the "default"
951       blockList.push_back(blockOfLabel(eval, std::get<2>(stmt.t)));
952       builder->create<fir::SelectCaseOp>(loc, expr, attrList, valueList,
953                                          blockList);
954       return;
955     }
956     // Arithmetic expression has Real type.  Generate
957     //   sum = expr + expr  [ raise an exception if expr is a NaN ]
958     //   if (sum < 0.0) goto L1 else if (sum > 0.0) goto L3 else goto L2
959     auto sum = builder->create<mlir::arith::AddFOp>(loc, expr, expr);
960     auto zero = builder->create<mlir::arith::ConstantOp>(
961         loc, exprType, builder->getFloatAttr(exprType, 0.0));
962     auto cond1 = builder->create<mlir::arith::CmpFOp>(
963         loc, mlir::arith::CmpFPredicate::OLT, sum, zero);
964     mlir::Block *elseIfBlock =
965         builder->getBlock()->splitBlock(builder->getInsertionPoint());
966     genFIRConditionalBranch(cond1, blockOfLabel(eval, std::get<1>(stmt.t)),
967                             elseIfBlock);
968     startBlock(elseIfBlock);
969     auto cond2 = builder->create<mlir::arith::CmpFOp>(
970         loc, mlir::arith::CmpFPredicate::OGT, sum, zero);
971     genFIRConditionalBranch(cond2, blockOfLabel(eval, std::get<3>(stmt.t)),
972                             blockOfLabel(eval, std::get<2>(stmt.t)));
973   }
974 
975   void genFIR(const Fortran::parser::AssignedGotoStmt &stmt) {
976     // Program requirement 1990 8.2.4 -
977     //
978     //   At the time of execution of an assigned GOTO statement, the integer
979     //   variable must be defined with the value of a statement label of a
980     //   branch target statement that appears in the same scoping unit.
981     //   Note that the variable may be defined with a statement label value
982     //   only by an ASSIGN statement in the same scoping unit as the assigned
983     //   GOTO statement.
984 
985     mlir::Location loc = toLocation();
986     Fortran::lower::pft::Evaluation &eval = getEval();
987     const Fortran::lower::pft::SymbolLabelMap &symbolLabelMap =
988         eval.getOwningProcedure()->assignSymbolLabelMap;
989     const Fortran::semantics::Symbol &symbol =
990         *std::get<Fortran::parser::Name>(stmt.t).symbol;
991     auto selectExpr =
992         builder->create<fir::LoadOp>(loc, getSymbolAddress(symbol));
993     auto iter = symbolLabelMap.find(symbol);
994     if (iter == symbolLabelMap.end()) {
995       // Fail for a nonconforming program unit that does not have any ASSIGN
996       // statements.  The front end should check for this.
997       mlir::emitError(loc, "(semantics issue) no assigned goto targets");
998       exit(1);
999     }
1000     auto labelSet = iter->second;
1001     llvm::SmallVector<int64_t> indexList;
1002     llvm::SmallVector<mlir::Block *> blockList;
1003     auto addLabel = [&](Fortran::parser::Label label) {
1004       indexList.push_back(label);
1005       blockList.push_back(blockOfLabel(eval, label));
1006     };
1007     // Add labels from an explicit list.  The list may have duplicates.
1008     for (Fortran::parser::Label label :
1009          std::get<std::list<Fortran::parser::Label>>(stmt.t)) {
1010       if (labelSet.count(label) &&
1011           std::find(indexList.begin(), indexList.end(), label) ==
1012               indexList.end()) { // ignore duplicates
1013         addLabel(label);
1014       }
1015     }
1016     // Absent an explicit list, add all possible label targets.
1017     if (indexList.empty())
1018       for (auto &label : labelSet)
1019         addLabel(label);
1020     // Add a nop/fallthrough branch to the switch for a nonconforming program
1021     // unit that violates the program requirement above.
1022     blockList.push_back(eval.nonNopSuccessor().block); // default
1023     builder->create<fir::SelectOp>(loc, selectExpr, indexList, blockList);
1024   }
1025 
1026   /// Collect DO CONCURRENT or FORALL loop control information.
1027   IncrementLoopNestInfo getConcurrentControl(
1028       const Fortran::parser::ConcurrentHeader &header,
1029       const std::list<Fortran::parser::LocalitySpec> &localityList = {}) {
1030     IncrementLoopNestInfo incrementLoopNestInfo;
1031     for (const Fortran::parser::ConcurrentControl &control :
1032          std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t))
1033       incrementLoopNestInfo.emplace_back(
1034           *std::get<0>(control.t).symbol, std::get<1>(control.t),
1035           std::get<2>(control.t), std::get<3>(control.t), /*isUnordered=*/true);
1036     IncrementLoopInfo &info = incrementLoopNestInfo.back();
1037     info.maskExpr = Fortran::semantics::GetExpr(
1038         std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(header.t));
1039     for (const Fortran::parser::LocalitySpec &x : localityList) {
1040       if (const auto *localInitList =
1041               std::get_if<Fortran::parser::LocalitySpec::LocalInit>(&x.u))
1042         for (const Fortran::parser::Name &x : localInitList->v)
1043           info.localInitSymList.push_back(x.symbol);
1044       if (const auto *sharedList =
1045               std::get_if<Fortran::parser::LocalitySpec::Shared>(&x.u))
1046         for (const Fortran::parser::Name &x : sharedList->v)
1047           info.sharedSymList.push_back(x.symbol);
1048       if (std::get_if<Fortran::parser::LocalitySpec::Local>(&x.u))
1049         TODO(toLocation(), "do concurrent locality specs not implemented");
1050     }
1051     return incrementLoopNestInfo;
1052   }
1053 
1054   /// Generate FIR for a DO construct.  There are six variants:
1055   ///  - unstructured infinite and while loops
1056   ///  - structured and unstructured increment loops
1057   ///  - structured and unstructured concurrent loops
1058   void genFIR(const Fortran::parser::DoConstruct &doConstruct) {
1059     setCurrentPositionAt(doConstruct);
1060     // Collect loop nest information.
1061     // Generate begin loop code directly for infinite and while loops.
1062     Fortran::lower::pft::Evaluation &eval = getEval();
1063     bool unstructuredContext = eval.lowerAsUnstructured();
1064     Fortran::lower::pft::Evaluation &doStmtEval =
1065         eval.getFirstNestedEvaluation();
1066     auto *doStmt = doStmtEval.getIf<Fortran::parser::NonLabelDoStmt>();
1067     const auto &loopControl =
1068         std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t);
1069     mlir::Block *preheaderBlock = doStmtEval.block;
1070     mlir::Block *beginBlock =
1071         preheaderBlock ? preheaderBlock : builder->getBlock();
1072     auto createNextBeginBlock = [&]() {
1073       // Step beginBlock through unstructured preheader, header, and mask
1074       // blocks, created in outermost to innermost order.
1075       return beginBlock = beginBlock->splitBlock(beginBlock->end());
1076     };
1077     mlir::Block *headerBlock =
1078         unstructuredContext ? createNextBeginBlock() : nullptr;
1079     mlir::Block *bodyBlock = doStmtEval.lexicalSuccessor->block;
1080     mlir::Block *exitBlock = doStmtEval.parentConstruct->constructExit->block;
1081     IncrementLoopNestInfo incrementLoopNestInfo;
1082     const Fortran::parser::ScalarLogicalExpr *whileCondition = nullptr;
1083     bool infiniteLoop = !loopControl.has_value();
1084     if (infiniteLoop) {
1085       assert(unstructuredContext && "infinite loop must be unstructured");
1086       startBlock(headerBlock);
1087     } else if ((whileCondition =
1088                     std::get_if<Fortran::parser::ScalarLogicalExpr>(
1089                         &loopControl->u))) {
1090       assert(unstructuredContext && "while loop must be unstructured");
1091       maybeStartBlock(preheaderBlock); // no block or empty block
1092       startBlock(headerBlock);
1093       genFIRConditionalBranch(*whileCondition, bodyBlock, exitBlock);
1094     } else if (const auto *bounds =
1095                    std::get_if<Fortran::parser::LoopControl::Bounds>(
1096                        &loopControl->u)) {
1097       // Non-concurrent increment loop.
1098       IncrementLoopInfo &info = incrementLoopNestInfo.emplace_back(
1099           *bounds->name.thing.symbol, bounds->lower, bounds->upper,
1100           bounds->step);
1101       if (unstructuredContext) {
1102         maybeStartBlock(preheaderBlock);
1103         info.hasRealControl = info.loopVariableSym.GetType()->IsNumeric(
1104             Fortran::common::TypeCategory::Real);
1105         info.headerBlock = headerBlock;
1106         info.bodyBlock = bodyBlock;
1107         info.exitBlock = exitBlock;
1108       }
1109     } else {
1110       const auto *concurrent =
1111           std::get_if<Fortran::parser::LoopControl::Concurrent>(
1112               &loopControl->u);
1113       assert(concurrent && "invalid DO loop variant");
1114       incrementLoopNestInfo = getConcurrentControl(
1115           std::get<Fortran::parser::ConcurrentHeader>(concurrent->t),
1116           std::get<std::list<Fortran::parser::LocalitySpec>>(concurrent->t));
1117       if (unstructuredContext) {
1118         maybeStartBlock(preheaderBlock);
1119         for (IncrementLoopInfo &info : incrementLoopNestInfo) {
1120           // The original loop body provides the body and latch blocks of the
1121           // innermost dimension.  The (first) body block of a non-innermost
1122           // dimension is the preheader block of the immediately enclosed
1123           // dimension.  The latch block of a non-innermost dimension is the
1124           // exit block of the immediately enclosed dimension.
1125           auto createNextExitBlock = [&]() {
1126             // Create unstructured loop exit blocks, outermost to innermost.
1127             return exitBlock = insertBlock(exitBlock);
1128           };
1129           bool isInnermost = &info == &incrementLoopNestInfo.back();
1130           bool isOutermost = &info == &incrementLoopNestInfo.front();
1131           info.headerBlock = isOutermost ? headerBlock : createNextBeginBlock();
1132           info.bodyBlock = isInnermost ? bodyBlock : createNextBeginBlock();
1133           info.exitBlock = isOutermost ? exitBlock : createNextExitBlock();
1134           if (info.maskExpr)
1135             info.maskBlock = createNextBeginBlock();
1136         }
1137       }
1138     }
1139 
1140     // Increment loop begin code.  (Infinite/while code was already generated.)
1141     if (!infiniteLoop && !whileCondition)
1142       genFIRIncrementLoopBegin(incrementLoopNestInfo);
1143 
1144     // Loop body code - NonLabelDoStmt and EndDoStmt code is generated here.
1145     // Their genFIR calls are nops except for block management in some cases.
1146     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations())
1147       genFIR(e, unstructuredContext);
1148 
1149     // Loop end code.
1150     if (infiniteLoop || whileCondition)
1151       genFIRBranch(headerBlock);
1152     else
1153       genFIRIncrementLoopEnd(incrementLoopNestInfo);
1154   }
1155 
1156   /// Generate FIR to begin a structured or unstructured increment loop nest.
1157   void genFIRIncrementLoopBegin(IncrementLoopNestInfo &incrementLoopNestInfo) {
1158     assert(!incrementLoopNestInfo.empty() && "empty loop nest");
1159     mlir::Location loc = toLocation();
1160     auto genControlValue = [&](const Fortran::lower::SomeExpr *expr,
1161                                const IncrementLoopInfo &info) {
1162       mlir::Type controlType = info.isStructured() ? builder->getIndexType()
1163                                                    : info.getLoopVariableType();
1164       Fortran::lower::StatementContext stmtCtx;
1165       if (expr)
1166         return builder->createConvert(loc, controlType,
1167                                       createFIRExpr(loc, expr, stmtCtx));
1168 
1169       if (info.hasRealControl)
1170         return builder->createRealConstant(loc, controlType, 1u);
1171       return builder->createIntegerConstant(loc, controlType, 1); // step
1172     };
1173     auto handleLocalitySpec = [&](IncrementLoopInfo &info) {
1174       // Generate Local Init Assignments
1175       for (const Fortran::semantics::Symbol *sym : info.localInitSymList) {
1176         const auto *hostDetails =
1177             sym->detailsIf<Fortran::semantics::HostAssocDetails>();
1178         assert(hostDetails && "missing local_init variable host variable");
1179         const Fortran::semantics::Symbol &hostSym = hostDetails->symbol();
1180         (void)hostSym;
1181         TODO(loc, "do concurrent locality specs not implemented");
1182       }
1183       // Handle shared locality spec
1184       for (const Fortran::semantics::Symbol *sym : info.sharedSymList) {
1185         const auto *hostDetails =
1186             sym->detailsIf<Fortran::semantics::HostAssocDetails>();
1187         assert(hostDetails && "missing shared variable host variable");
1188         const Fortran::semantics::Symbol &hostSym = hostDetails->symbol();
1189         copySymbolBinding(hostSym, *sym);
1190       }
1191     };
1192     for (IncrementLoopInfo &info : incrementLoopNestInfo) {
1193       info.loopVariable =
1194           genLoopVariableAddress(loc, info.loopVariableSym, info.isUnordered);
1195       mlir::Value lowerValue = genControlValue(info.lowerExpr, info);
1196       mlir::Value upperValue = genControlValue(info.upperExpr, info);
1197       info.stepValue = genControlValue(info.stepExpr, info);
1198 
1199       // Structured loop - generate fir.do_loop.
1200       if (info.isStructured()) {
1201         info.doLoop = builder->create<fir::DoLoopOp>(
1202             loc, lowerValue, upperValue, info.stepValue, info.isUnordered,
1203             /*finalCountValue=*/!info.isUnordered);
1204         builder->setInsertionPointToStart(info.doLoop.getBody());
1205         // Update the loop variable value, as it may have non-index references.
1206         mlir::Value value = builder->createConvert(
1207             loc, info.getLoopVariableType(), info.doLoop.getInductionVar());
1208         builder->create<fir::StoreOp>(loc, value, info.loopVariable);
1209         if (info.maskExpr) {
1210           Fortran::lower::StatementContext stmtCtx;
1211           mlir::Value maskCond = createFIRExpr(loc, info.maskExpr, stmtCtx);
1212           stmtCtx.finalize();
1213           mlir::Value maskCondCast =
1214               builder->createConvert(loc, builder->getI1Type(), maskCond);
1215           auto ifOp = builder->create<fir::IfOp>(loc, maskCondCast,
1216                                                  /*withElseRegion=*/false);
1217           builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1218         }
1219         handleLocalitySpec(info);
1220         continue;
1221       }
1222 
1223       // Unstructured loop preheader - initialize tripVariable and loopVariable.
1224       mlir::Value tripCount;
1225       if (info.hasRealControl) {
1226         auto diff1 =
1227             builder->create<mlir::arith::SubFOp>(loc, upperValue, lowerValue);
1228         auto diff2 =
1229             builder->create<mlir::arith::AddFOp>(loc, diff1, info.stepValue);
1230         tripCount =
1231             builder->create<mlir::arith::DivFOp>(loc, diff2, info.stepValue);
1232         tripCount =
1233             builder->createConvert(loc, builder->getIndexType(), tripCount);
1234 
1235       } else {
1236         auto diff1 =
1237             builder->create<mlir::arith::SubIOp>(loc, upperValue, lowerValue);
1238         auto diff2 =
1239             builder->create<mlir::arith::AddIOp>(loc, diff1, info.stepValue);
1240         tripCount =
1241             builder->create<mlir::arith::DivSIOp>(loc, diff2, info.stepValue);
1242       }
1243       if (forceLoopToExecuteOnce) { // minimum tripCount is 1
1244         mlir::Value one =
1245             builder->createIntegerConstant(loc, tripCount.getType(), 1);
1246         auto cond = builder->create<mlir::arith::CmpIOp>(
1247             loc, mlir::arith::CmpIPredicate::slt, tripCount, one);
1248         tripCount =
1249             builder->create<mlir::arith::SelectOp>(loc, cond, one, tripCount);
1250       }
1251       info.tripVariable = builder->createTemporary(loc, tripCount.getType());
1252       builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable);
1253       builder->create<fir::StoreOp>(loc, lowerValue, info.loopVariable);
1254 
1255       // Unstructured loop header - generate loop condition and mask.
1256       // Note - Currently there is no way to tag a loop as a concurrent loop.
1257       startBlock(info.headerBlock);
1258       tripCount = builder->create<fir::LoadOp>(loc, info.tripVariable);
1259       mlir::Value zero =
1260           builder->createIntegerConstant(loc, tripCount.getType(), 0);
1261       auto cond = builder->create<mlir::arith::CmpIOp>(
1262           loc, mlir::arith::CmpIPredicate::sgt, tripCount, zero);
1263       if (info.maskExpr) {
1264         genFIRConditionalBranch(cond, info.maskBlock, info.exitBlock);
1265         startBlock(info.maskBlock);
1266         mlir::Block *latchBlock = getEval().getLastNestedEvaluation().block;
1267         assert(latchBlock && "missing masked concurrent loop latch block");
1268         Fortran::lower::StatementContext stmtCtx;
1269         mlir::Value maskCond = createFIRExpr(loc, info.maskExpr, stmtCtx);
1270         stmtCtx.finalize();
1271         genFIRConditionalBranch(maskCond, info.bodyBlock, latchBlock);
1272       } else {
1273         genFIRConditionalBranch(cond, info.bodyBlock, info.exitBlock);
1274         if (&info != &incrementLoopNestInfo.back()) // not innermost
1275           startBlock(info.bodyBlock); // preheader block of enclosed dimension
1276       }
1277       if (!info.localInitSymList.empty()) {
1278         mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1279         builder->setInsertionPointToStart(info.bodyBlock);
1280         handleLocalitySpec(info);
1281         builder->restoreInsertionPoint(insertPt);
1282       }
1283     }
1284   }
1285 
1286   /// Generate FIR to end a structured or unstructured increment loop nest.
1287   void genFIRIncrementLoopEnd(IncrementLoopNestInfo &incrementLoopNestInfo) {
1288     assert(!incrementLoopNestInfo.empty() && "empty loop nest");
1289     mlir::Location loc = toLocation();
1290     for (auto it = incrementLoopNestInfo.rbegin(),
1291               rend = incrementLoopNestInfo.rend();
1292          it != rend; ++it) {
1293       IncrementLoopInfo &info = *it;
1294       if (info.isStructured()) {
1295         // End fir.do_loop.
1296         if (!info.isUnordered) {
1297           builder->setInsertionPointToEnd(info.doLoop.getBody());
1298           mlir::Value result = builder->create<mlir::arith::AddIOp>(
1299               loc, info.doLoop.getInductionVar(), info.doLoop.getStep());
1300           builder->create<fir::ResultOp>(loc, result);
1301         }
1302         builder->setInsertionPointAfter(info.doLoop);
1303         if (info.isUnordered)
1304           continue;
1305         // The loop control variable may be used after loop execution.
1306         mlir::Value lcv = builder->createConvert(
1307             loc, info.getLoopVariableType(), info.doLoop.getResult(0));
1308         builder->create<fir::StoreOp>(loc, lcv, info.loopVariable);
1309         continue;
1310       }
1311 
1312       // Unstructured loop - decrement tripVariable and step loopVariable.
1313       mlir::Value tripCount =
1314           builder->create<fir::LoadOp>(loc, info.tripVariable);
1315       mlir::Value one =
1316           builder->createIntegerConstant(loc, tripCount.getType(), 1);
1317       tripCount = builder->create<mlir::arith::SubIOp>(loc, tripCount, one);
1318       builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable);
1319       mlir::Value value = builder->create<fir::LoadOp>(loc, info.loopVariable);
1320       if (info.hasRealControl)
1321         value =
1322             builder->create<mlir::arith::AddFOp>(loc, value, info.stepValue);
1323       else
1324         value =
1325             builder->create<mlir::arith::AddIOp>(loc, value, info.stepValue);
1326       builder->create<fir::StoreOp>(loc, value, info.loopVariable);
1327 
1328       genFIRBranch(info.headerBlock);
1329       if (&info != &incrementLoopNestInfo.front()) // not outermost
1330         startBlock(info.exitBlock); // latch block of enclosing dimension
1331     }
1332   }
1333 
1334   /// Generate structured or unstructured FIR for an IF construct.
1335   /// The initial statement may be either an IfStmt or an IfThenStmt.
1336   void genFIR(const Fortran::parser::IfConstruct &) {
1337     mlir::Location loc = toLocation();
1338     Fortran::lower::pft::Evaluation &eval = getEval();
1339     if (eval.lowerAsStructured()) {
1340       // Structured fir.if nest.
1341       fir::IfOp topIfOp, currentIfOp;
1342       for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1343         auto genIfOp = [&](mlir::Value cond) {
1344           auto ifOp = builder->create<fir::IfOp>(loc, cond, /*withElse=*/true);
1345           builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1346           return ifOp;
1347         };
1348         if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) {
1349           topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition));
1350         } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) {
1351           topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition));
1352         } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) {
1353           builder->setInsertionPointToStart(
1354               &currentIfOp.getElseRegion().front());
1355           currentIfOp = genIfOp(genIfCondition(s));
1356         } else if (e.isA<Fortran::parser::ElseStmt>()) {
1357           builder->setInsertionPointToStart(
1358               &currentIfOp.getElseRegion().front());
1359         } else if (e.isA<Fortran::parser::EndIfStmt>()) {
1360           builder->setInsertionPointAfter(topIfOp);
1361         } else {
1362           genFIR(e, /*unstructuredContext=*/false);
1363         }
1364       }
1365       return;
1366     }
1367 
1368     // Unstructured branch sequence.
1369     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1370       auto genIfBranch = [&](mlir::Value cond) {
1371         if (e.lexicalSuccessor == e.controlSuccessor) // empty block -> exit
1372           genFIRConditionalBranch(cond, e.parentConstruct->constructExit,
1373                                   e.controlSuccessor);
1374         else // non-empty block
1375           genFIRConditionalBranch(cond, e.lexicalSuccessor, e.controlSuccessor);
1376       };
1377       if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) {
1378         maybeStartBlock(e.block);
1379         genIfBranch(genIfCondition(s, e.negateCondition));
1380       } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) {
1381         maybeStartBlock(e.block);
1382         genIfBranch(genIfCondition(s, e.negateCondition));
1383       } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) {
1384         startBlock(e.block);
1385         genIfBranch(genIfCondition(s));
1386       } else {
1387         genFIR(e);
1388       }
1389     }
1390   }
1391 
1392   void genFIR(const Fortran::parser::CaseConstruct &) {
1393     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1394       genFIR(e);
1395   }
1396 
1397   template <typename A>
1398   void genNestedStatement(const Fortran::parser::Statement<A> &stmt) {
1399     setCurrentPosition(stmt.source);
1400     genFIR(stmt.statement);
1401   }
1402 
1403   /// Force the binding of an explicit symbol. This is used to bind and re-bind
1404   /// a concurrent control symbol to its value.
1405   void forceControlVariableBinding(const Fortran::semantics::Symbol *sym,
1406                                    mlir::Value inducVar) {
1407     mlir::Location loc = toLocation();
1408     assert(sym && "There must be a symbol to bind");
1409     mlir::Type toTy = genType(*sym);
1410     // FIXME: this should be a "per iteration" temporary.
1411     mlir::Value tmp = builder->createTemporary(
1412         loc, toTy, toStringRef(sym->name()),
1413         llvm::ArrayRef<mlir::NamedAttribute>{
1414             Fortran::lower::getAdaptToByRefAttr(*builder)});
1415     mlir::Value cast = builder->createConvert(loc, toTy, inducVar);
1416     builder->create<fir::StoreOp>(loc, cast, tmp);
1417     localSymbols.addSymbol(*sym, tmp, /*force=*/true);
1418   }
1419 
1420   /// Process a concurrent header for a FORALL. (Concurrent headers for DO
1421   /// CONCURRENT loops are lowered elsewhere.)
1422   void genFIR(const Fortran::parser::ConcurrentHeader &header) {
1423     llvm::SmallVector<mlir::Value> lows;
1424     llvm::SmallVector<mlir::Value> highs;
1425     llvm::SmallVector<mlir::Value> steps;
1426     if (explicitIterSpace.isOutermostForall()) {
1427       // For the outermost forall, we evaluate the bounds expressions once.
1428       // Contrastingly, if this forall is nested, the bounds expressions are
1429       // assumed to be pure, possibly dependent on outer concurrent control
1430       // variables, possibly variant with respect to arguments, and will be
1431       // re-evaluated.
1432       mlir::Location loc = toLocation();
1433       mlir::Type idxTy = builder->getIndexType();
1434       Fortran::lower::StatementContext &stmtCtx =
1435           explicitIterSpace.stmtContext();
1436       auto lowerExpr = [&](auto &e) {
1437         return fir::getBase(genExprValue(e, stmtCtx));
1438       };
1439       for (const Fortran::parser::ConcurrentControl &ctrl :
1440            std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
1441         const Fortran::lower::SomeExpr *lo =
1442             Fortran::semantics::GetExpr(std::get<1>(ctrl.t));
1443         const Fortran::lower::SomeExpr *hi =
1444             Fortran::semantics::GetExpr(std::get<2>(ctrl.t));
1445         auto &optStep =
1446             std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t);
1447         lows.push_back(builder->createConvert(loc, idxTy, lowerExpr(*lo)));
1448         highs.push_back(builder->createConvert(loc, idxTy, lowerExpr(*hi)));
1449         steps.push_back(
1450             optStep.has_value()
1451                 ? builder->createConvert(
1452                       loc, idxTy,
1453                       lowerExpr(*Fortran::semantics::GetExpr(*optStep)))
1454                 : builder->createIntegerConstant(loc, idxTy, 1));
1455       }
1456     }
1457     auto lambda = [&, lows, highs, steps]() {
1458       // Create our iteration space from the header spec.
1459       mlir::Location loc = toLocation();
1460       mlir::Type idxTy = builder->getIndexType();
1461       llvm::SmallVector<fir::DoLoopOp> loops;
1462       Fortran::lower::StatementContext &stmtCtx =
1463           explicitIterSpace.stmtContext();
1464       auto lowerExpr = [&](auto &e) {
1465         return fir::getBase(genExprValue(e, stmtCtx));
1466       };
1467       const bool outermost = !lows.empty();
1468       std::size_t headerIndex = 0;
1469       for (const Fortran::parser::ConcurrentControl &ctrl :
1470            std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
1471         const Fortran::semantics::Symbol *ctrlVar =
1472             std::get<Fortran::parser::Name>(ctrl.t).symbol;
1473         mlir::Value lb;
1474         mlir::Value ub;
1475         mlir::Value by;
1476         if (outermost) {
1477           assert(headerIndex < lows.size());
1478           if (headerIndex == 0)
1479             explicitIterSpace.resetInnerArgs();
1480           lb = lows[headerIndex];
1481           ub = highs[headerIndex];
1482           by = steps[headerIndex++];
1483         } else {
1484           const Fortran::lower::SomeExpr *lo =
1485               Fortran::semantics::GetExpr(std::get<1>(ctrl.t));
1486           const Fortran::lower::SomeExpr *hi =
1487               Fortran::semantics::GetExpr(std::get<2>(ctrl.t));
1488           auto &optStep =
1489               std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t);
1490           lb = builder->createConvert(loc, idxTy, lowerExpr(*lo));
1491           ub = builder->createConvert(loc, idxTy, lowerExpr(*hi));
1492           by = optStep.has_value()
1493                    ? builder->createConvert(
1494                          loc, idxTy,
1495                          lowerExpr(*Fortran::semantics::GetExpr(*optStep)))
1496                    : builder->createIntegerConstant(loc, idxTy, 1);
1497         }
1498         auto lp = builder->create<fir::DoLoopOp>(
1499             loc, lb, ub, by, /*unordered=*/true,
1500             /*finalCount=*/false, explicitIterSpace.getInnerArgs());
1501         if ((!loops.empty() || !outermost) && !lp.getRegionIterArgs().empty())
1502           builder->create<fir::ResultOp>(loc, lp.getResults());
1503         explicitIterSpace.setInnerArgs(lp.getRegionIterArgs());
1504         builder->setInsertionPointToStart(lp.getBody());
1505         forceControlVariableBinding(ctrlVar, lp.getInductionVar());
1506         loops.push_back(lp);
1507       }
1508       if (outermost)
1509         explicitIterSpace.setOuterLoop(loops[0]);
1510       explicitIterSpace.appendLoops(loops);
1511       if (const auto &mask =
1512               std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
1513                   header.t);
1514           mask.has_value()) {
1515         mlir::Type i1Ty = builder->getI1Type();
1516         fir::ExtendedValue maskExv =
1517             genExprValue(*Fortran::semantics::GetExpr(mask.value()), stmtCtx);
1518         mlir::Value cond =
1519             builder->createConvert(loc, i1Ty, fir::getBase(maskExv));
1520         auto ifOp = builder->create<fir::IfOp>(
1521             loc, explicitIterSpace.innerArgTypes(), cond,
1522             /*withElseRegion=*/true);
1523         builder->create<fir::ResultOp>(loc, ifOp.getResults());
1524         builder->setInsertionPointToStart(&ifOp.getElseRegion().front());
1525         builder->create<fir::ResultOp>(loc, explicitIterSpace.getInnerArgs());
1526         builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1527       }
1528     };
1529     // Push the lambda to gen the loop nest context.
1530     explicitIterSpace.pushLoopNest(lambda);
1531   }
1532 
1533   void genFIR(const Fortran::parser::ForallAssignmentStmt &stmt) {
1534     std::visit([&](const auto &x) { genFIR(x); }, stmt.u);
1535   }
1536 
1537   void genFIR(const Fortran::parser::EndForallStmt &) {
1538     cleanupExplicitSpace();
1539   }
1540 
1541   template <typename A>
1542   void prepareExplicitSpace(const A &forall) {
1543     if (!explicitIterSpace.isActive())
1544       analyzeExplicitSpace(forall);
1545     localSymbols.pushScope();
1546     explicitIterSpace.enter();
1547   }
1548 
1549   /// Cleanup all the FORALL context information when we exit.
1550   void cleanupExplicitSpace() {
1551     explicitIterSpace.leave();
1552     localSymbols.popScope();
1553   }
1554 
1555   /// Generate FIR for a FORALL statement.
1556   void genFIR(const Fortran::parser::ForallStmt &stmt) {
1557     prepareExplicitSpace(stmt);
1558     genFIR(std::get<
1559                Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
1560                stmt.t)
1561                .value());
1562     genFIR(std::get<Fortran::parser::UnlabeledStatement<
1563                Fortran::parser::ForallAssignmentStmt>>(stmt.t)
1564                .statement);
1565     cleanupExplicitSpace();
1566   }
1567 
1568   /// Generate FIR for a FORALL construct.
1569   void genFIR(const Fortran::parser::ForallConstruct &forall) {
1570     prepareExplicitSpace(forall);
1571     genNestedStatement(
1572         std::get<
1573             Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
1574             forall.t));
1575     for (const Fortran::parser::ForallBodyConstruct &s :
1576          std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
1577       std::visit(
1578           Fortran::common::visitors{
1579               [&](const Fortran::parser::WhereConstruct &b) { genFIR(b); },
1580               [&](const Fortran::common::Indirection<
1581                   Fortran::parser::ForallConstruct> &b) { genFIR(b.value()); },
1582               [&](const auto &b) { genNestedStatement(b); }},
1583           s.u);
1584     }
1585     genNestedStatement(
1586         std::get<Fortran::parser::Statement<Fortran::parser::EndForallStmt>>(
1587             forall.t));
1588   }
1589 
1590   /// Lower the concurrent header specification.
1591   void genFIR(const Fortran::parser::ForallConstructStmt &stmt) {
1592     genFIR(std::get<
1593                Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
1594                stmt.t)
1595                .value());
1596   }
1597 
1598   void genFIR(const Fortran::parser::CompilerDirective &) {
1599     mlir::emitWarning(toLocation(), "ignoring all compiler directives");
1600   }
1601 
1602   void genFIR(const Fortran::parser::OpenACCConstruct &acc) {
1603     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1604     genOpenACCConstruct(*this, getEval(), acc);
1605     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1606       genFIR(e);
1607     builder->restoreInsertionPoint(insertPt);
1608   }
1609 
1610   void genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &accDecl) {
1611     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1612     genOpenACCDeclarativeConstruct(*this, getEval(), accDecl);
1613     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1614       genFIR(e);
1615     builder->restoreInsertionPoint(insertPt);
1616   }
1617 
1618   void genFIR(const Fortran::parser::OpenMPConstruct &omp) {
1619     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1620     localSymbols.pushScope();
1621     genOpenMPConstruct(*this, getEval(), omp);
1622 
1623     const Fortran::parser::OpenMPLoopConstruct *ompLoop =
1624         std::get_if<Fortran::parser::OpenMPLoopConstruct>(&omp.u);
1625 
1626     // If loop is part of an OpenMP Construct then the OpenMP dialect
1627     // workshare loop operation has already been created. Only the
1628     // body needs to be created here and the do_loop can be skipped.
1629     // Skip the number of collapsed loops, which is 1 when there is a
1630     // no collapse requested.
1631 
1632     Fortran::lower::pft::Evaluation *curEval = &getEval();
1633     if (ompLoop) {
1634       const auto &wsLoopOpClauseList = std::get<Fortran::parser::OmpClauseList>(
1635           std::get<Fortran::parser::OmpBeginLoopDirective>(ompLoop->t).t);
1636       int64_t collapseValue =
1637           Fortran::lower::getCollapseValue(wsLoopOpClauseList);
1638 
1639       curEval = &curEval->getFirstNestedEvaluation();
1640       for (int64_t i = 1; i < collapseValue; i++) {
1641         curEval = &*std::next(curEval->getNestedEvaluations().begin());
1642       }
1643     }
1644 
1645     for (Fortran::lower::pft::Evaluation &e : curEval->getNestedEvaluations())
1646       genFIR(e);
1647     localSymbols.popScope();
1648     builder->restoreInsertionPoint(insertPt);
1649   }
1650 
1651   void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) {
1652     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1653     genOpenMPDeclarativeConstruct(*this, getEval(), ompDecl);
1654     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1655       genFIR(e);
1656     builder->restoreInsertionPoint(insertPt);
1657   }
1658 
1659   /// Generate FIR for a SELECT CASE statement.
1660   /// The type may be CHARACTER, INTEGER, or LOGICAL.
1661   void genFIR(const Fortran::parser::SelectCaseStmt &stmt) {
1662     Fortran::lower::pft::Evaluation &eval = getEval();
1663     mlir::MLIRContext *context = builder->getContext();
1664     mlir::Location loc = toLocation();
1665     Fortran::lower::StatementContext stmtCtx;
1666     const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr(
1667         std::get<Fortran::parser::Scalar<Fortran::parser::Expr>>(stmt.t));
1668     bool isCharSelector = isCharacterCategory(expr->GetType()->category());
1669     bool isLogicalSelector = isLogicalCategory(expr->GetType()->category());
1670     auto charValue = [&](const Fortran::lower::SomeExpr *expr) {
1671       fir::ExtendedValue exv = genExprAddr(*expr, stmtCtx, &loc);
1672       return exv.match(
1673           [&](const fir::CharBoxValue &cbv) {
1674             return fir::factory::CharacterExprHelper{*builder, loc}
1675                 .createEmboxChar(cbv.getAddr(), cbv.getLen());
1676           },
1677           [&](auto) {
1678             fir::emitFatalError(loc, "not a character");
1679             return mlir::Value{};
1680           });
1681     };
1682     mlir::Value selector;
1683     if (isCharSelector) {
1684       selector = charValue(expr);
1685     } else {
1686       selector = createFIRExpr(loc, expr, stmtCtx);
1687       if (isLogicalSelector)
1688         selector = builder->createConvert(loc, builder->getI1Type(), selector);
1689     }
1690     mlir::Type selectType = selector.getType();
1691     llvm::SmallVector<mlir::Attribute> attrList;
1692     llvm::SmallVector<mlir::Value> valueList;
1693     llvm::SmallVector<mlir::Block *> blockList;
1694     mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block;
1695     using CaseValue = Fortran::parser::Scalar<Fortran::parser::ConstantExpr>;
1696     auto addValue = [&](const CaseValue &caseValue) {
1697       const Fortran::lower::SomeExpr *expr =
1698           Fortran::semantics::GetExpr(caseValue.thing);
1699       if (isCharSelector)
1700         valueList.push_back(charValue(expr));
1701       else if (isLogicalSelector)
1702         valueList.push_back(builder->createConvert(
1703             loc, selectType, createFIRExpr(toLocation(), expr, stmtCtx)));
1704       else
1705         valueList.push_back(builder->createIntegerConstant(
1706             loc, selectType, *Fortran::evaluate::ToInt64(*expr)));
1707     };
1708     for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e;
1709          e = e->controlSuccessor) {
1710       const auto &caseStmt = e->getIf<Fortran::parser::CaseStmt>();
1711       assert(e->block && "missing CaseStmt block");
1712       const auto &caseSelector =
1713           std::get<Fortran::parser::CaseSelector>(caseStmt->t);
1714       const auto *caseValueRangeList =
1715           std::get_if<std::list<Fortran::parser::CaseValueRange>>(
1716               &caseSelector.u);
1717       if (!caseValueRangeList) {
1718         defaultBlock = e->block;
1719         continue;
1720       }
1721       for (const Fortran::parser::CaseValueRange &caseValueRange :
1722            *caseValueRangeList) {
1723         blockList.push_back(e->block);
1724         if (const auto *caseValue = std::get_if<CaseValue>(&caseValueRange.u)) {
1725           attrList.push_back(fir::PointIntervalAttr::get(context));
1726           addValue(*caseValue);
1727           continue;
1728         }
1729         const auto &caseRange =
1730             std::get<Fortran::parser::CaseValueRange::Range>(caseValueRange.u);
1731         if (caseRange.lower && caseRange.upper) {
1732           attrList.push_back(fir::ClosedIntervalAttr::get(context));
1733           addValue(*caseRange.lower);
1734           addValue(*caseRange.upper);
1735         } else if (caseRange.lower) {
1736           attrList.push_back(fir::LowerBoundAttr::get(context));
1737           addValue(*caseRange.lower);
1738         } else {
1739           attrList.push_back(fir::UpperBoundAttr::get(context));
1740           addValue(*caseRange.upper);
1741         }
1742       }
1743     }
1744     // Skip a logical default block that can never be referenced.
1745     if (isLogicalSelector && attrList.size() == 2)
1746       defaultBlock = eval.parentConstruct->constructExit->block;
1747     attrList.push_back(mlir::UnitAttr::get(context));
1748     blockList.push_back(defaultBlock);
1749 
1750     // Generate a fir::SelectCaseOp.
1751     // Explicit branch code is better for the LOGICAL type.  The CHARACTER type
1752     // does not yet have downstream support, and also uses explicit branch code.
1753     // The -no-structured-fir option can be used to force generation of INTEGER
1754     // type branch code.
1755     if (!isLogicalSelector && !isCharSelector && eval.lowerAsStructured()) {
1756       // Numeric selector is a ssa register, all temps that may have
1757       // been generated while evaluating it can be cleaned-up before the
1758       // fir.select_case.
1759       stmtCtx.finalize();
1760       builder->create<fir::SelectCaseOp>(loc, selector, attrList, valueList,
1761                                          blockList);
1762       return;
1763     }
1764 
1765     // Generate a sequence of case value comparisons and branches.
1766     auto caseValue = valueList.begin();
1767     auto caseBlock = blockList.begin();
1768     bool skipFinalization = false;
1769     for (const auto &attr : llvm::enumerate(attrList)) {
1770       if (attr.value().isa<mlir::UnitAttr>()) {
1771         if (attrList.size() == 1)
1772           stmtCtx.finalize();
1773         genFIRBranch(*caseBlock++);
1774         break;
1775       }
1776       auto genCond = [&](mlir::Value rhs,
1777                          mlir::arith::CmpIPredicate pred) -> mlir::Value {
1778         if (!isCharSelector)
1779           return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs);
1780         fir::factory::CharacterExprHelper charHelper{*builder, loc};
1781         std::pair<mlir::Value, mlir::Value> lhsVal =
1782             charHelper.createUnboxChar(selector);
1783         mlir::Value &lhsAddr = lhsVal.first;
1784         mlir::Value &lhsLen = lhsVal.second;
1785         std::pair<mlir::Value, mlir::Value> rhsVal =
1786             charHelper.createUnboxChar(rhs);
1787         mlir::Value &rhsAddr = rhsVal.first;
1788         mlir::Value &rhsLen = rhsVal.second;
1789         mlir::Value result = fir::runtime::genCharCompare(
1790             *builder, loc, pred, lhsAddr, lhsLen, rhsAddr, rhsLen);
1791         if (stmtCtx.workListIsEmpty() || skipFinalization)
1792           return result;
1793         if (attr.index() == attrList.size() - 2) {
1794           stmtCtx.finalize();
1795           return result;
1796         }
1797         fir::IfOp ifOp = builder->create<fir::IfOp>(loc, result,
1798                                                     /*withElseRegion=*/false);
1799         builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1800         stmtCtx.finalizeAndKeep();
1801         builder->setInsertionPointAfter(ifOp);
1802         return result;
1803       };
1804       mlir::Block *newBlock = insertBlock(*caseBlock);
1805       if (attr.value().isa<fir::ClosedIntervalAttr>()) {
1806         mlir::Block *newBlock2 = insertBlock(*caseBlock);
1807         skipFinalization = true;
1808         mlir::Value cond =
1809             genCond(*caseValue++, mlir::arith::CmpIPredicate::sge);
1810         genFIRConditionalBranch(cond, newBlock, newBlock2);
1811         builder->setInsertionPointToEnd(newBlock);
1812         skipFinalization = false;
1813         mlir::Value cond2 =
1814             genCond(*caseValue++, mlir::arith::CmpIPredicate::sle);
1815         genFIRConditionalBranch(cond2, *caseBlock++, newBlock2);
1816         builder->setInsertionPointToEnd(newBlock2);
1817         continue;
1818       }
1819       mlir::arith::CmpIPredicate pred;
1820       if (attr.value().isa<fir::PointIntervalAttr>()) {
1821         pred = mlir::arith::CmpIPredicate::eq;
1822       } else if (attr.value().isa<fir::LowerBoundAttr>()) {
1823         pred = mlir::arith::CmpIPredicate::sge;
1824       } else {
1825         assert(attr.value().isa<fir::UpperBoundAttr>() &&
1826                "unexpected predicate");
1827         pred = mlir::arith::CmpIPredicate::sle;
1828       }
1829       mlir::Value cond = genCond(*caseValue++, pred);
1830       genFIRConditionalBranch(cond, *caseBlock++, newBlock);
1831       builder->setInsertionPointToEnd(newBlock);
1832     }
1833     assert(caseValue == valueList.end() && caseBlock == blockList.end() &&
1834            "select case list mismatch");
1835     assert(stmtCtx.workListIsEmpty() && "statement context must be empty");
1836   }
1837 
1838   fir::ExtendedValue
1839   genAssociateSelector(const Fortran::lower::SomeExpr &selector,
1840                        Fortran::lower::StatementContext &stmtCtx) {
1841     return Fortran::lower::isArraySectionWithoutVectorSubscript(selector)
1842                ? Fortran::lower::createSomeArrayBox(*this, selector,
1843                                                     localSymbols, stmtCtx)
1844                : genExprAddr(selector, stmtCtx);
1845   }
1846 
1847   void genFIR(const Fortran::parser::AssociateConstruct &) {
1848     Fortran::lower::StatementContext stmtCtx;
1849     Fortran::lower::pft::Evaluation &eval = getEval();
1850     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1851       if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) {
1852         if (eval.lowerAsUnstructured())
1853           maybeStartBlock(e.block);
1854         localSymbols.pushScope();
1855         for (const Fortran::parser::Association &assoc :
1856              std::get<std::list<Fortran::parser::Association>>(stmt->t)) {
1857           Fortran::semantics::Symbol &sym =
1858               *std::get<Fortran::parser::Name>(assoc.t).symbol;
1859           const Fortran::lower::SomeExpr &selector =
1860               *sym.get<Fortran::semantics::AssocEntityDetails>().expr();
1861           localSymbols.addSymbol(sym, genAssociateSelector(selector, stmtCtx));
1862         }
1863       } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) {
1864         if (eval.lowerAsUnstructured())
1865           maybeStartBlock(e.block);
1866         stmtCtx.finalize();
1867         localSymbols.popScope();
1868       } else {
1869         genFIR(e);
1870       }
1871     }
1872   }
1873 
1874   void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) {
1875     setCurrentPositionAt(blockConstruct);
1876     TODO(toLocation(), "BlockConstruct implementation");
1877   }
1878   void genFIR(const Fortran::parser::BlockStmt &) {
1879     TODO(toLocation(), "BlockStmt implementation");
1880   }
1881   void genFIR(const Fortran::parser::EndBlockStmt &) {
1882     TODO(toLocation(), "EndBlockStmt implementation");
1883   }
1884 
1885   void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) {
1886     TODO(toLocation(), "ChangeTeamConstruct implementation");
1887   }
1888   void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) {
1889     TODO(toLocation(), "ChangeTeamStmt implementation");
1890   }
1891   void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) {
1892     TODO(toLocation(), "EndChangeTeamStmt implementation");
1893   }
1894 
1895   void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) {
1896     setCurrentPositionAt(criticalConstruct);
1897     TODO(toLocation(), "CriticalConstruct implementation");
1898   }
1899   void genFIR(const Fortran::parser::CriticalStmt &) {
1900     TODO(toLocation(), "CriticalStmt implementation");
1901   }
1902   void genFIR(const Fortran::parser::EndCriticalStmt &) {
1903     TODO(toLocation(), "EndCriticalStmt implementation");
1904   }
1905 
1906   void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) {
1907     setCurrentPositionAt(selectRankConstruct);
1908     TODO(toLocation(), "SelectRankConstruct implementation");
1909   }
1910   void genFIR(const Fortran::parser::SelectRankStmt &) {
1911     TODO(toLocation(), "SelectRankStmt implementation");
1912   }
1913   void genFIR(const Fortran::parser::SelectRankCaseStmt &) {
1914     TODO(toLocation(), "SelectRankCaseStmt implementation");
1915   }
1916 
1917   void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) {
1918     setCurrentPositionAt(selectTypeConstruct);
1919     TODO(toLocation(), "SelectTypeConstruct implementation");
1920   }
1921   void genFIR(const Fortran::parser::SelectTypeStmt &) {
1922     TODO(toLocation(), "SelectTypeStmt implementation");
1923   }
1924   void genFIR(const Fortran::parser::TypeGuardStmt &) {
1925     TODO(toLocation(), "TypeGuardStmt implementation");
1926   }
1927 
1928   //===--------------------------------------------------------------------===//
1929   // IO statements (see io.h)
1930   //===--------------------------------------------------------------------===//
1931 
1932   void genFIR(const Fortran::parser::BackspaceStmt &stmt) {
1933     mlir::Value iostat = genBackspaceStatement(*this, stmt);
1934     genIoConditionBranches(getEval(), stmt.v, iostat);
1935   }
1936   void genFIR(const Fortran::parser::CloseStmt &stmt) {
1937     mlir::Value iostat = genCloseStatement(*this, stmt);
1938     genIoConditionBranches(getEval(), stmt.v, iostat);
1939   }
1940   void genFIR(const Fortran::parser::EndfileStmt &stmt) {
1941     mlir::Value iostat = genEndfileStatement(*this, stmt);
1942     genIoConditionBranches(getEval(), stmt.v, iostat);
1943   }
1944   void genFIR(const Fortran::parser::FlushStmt &stmt) {
1945     mlir::Value iostat = genFlushStatement(*this, stmt);
1946     genIoConditionBranches(getEval(), stmt.v, iostat);
1947   }
1948   void genFIR(const Fortran::parser::InquireStmt &stmt) {
1949     mlir::Value iostat = genInquireStatement(*this, stmt);
1950     if (const auto *specs =
1951             std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u))
1952       genIoConditionBranches(getEval(), *specs, iostat);
1953   }
1954   void genFIR(const Fortran::parser::OpenStmt &stmt) {
1955     mlir::Value iostat = genOpenStatement(*this, stmt);
1956     genIoConditionBranches(getEval(), stmt.v, iostat);
1957   }
1958   void genFIR(const Fortran::parser::PrintStmt &stmt) {
1959     genPrintStatement(*this, stmt);
1960   }
1961   void genFIR(const Fortran::parser::ReadStmt &stmt) {
1962     mlir::Value iostat = genReadStatement(*this, stmt);
1963     genIoConditionBranches(getEval(), stmt.controls, iostat);
1964   }
1965   void genFIR(const Fortran::parser::RewindStmt &stmt) {
1966     mlir::Value iostat = genRewindStatement(*this, stmt);
1967     genIoConditionBranches(getEval(), stmt.v, iostat);
1968   }
1969   void genFIR(const Fortran::parser::WaitStmt &stmt) {
1970     mlir::Value iostat = genWaitStatement(*this, stmt);
1971     genIoConditionBranches(getEval(), stmt.v, iostat);
1972   }
1973   void genFIR(const Fortran::parser::WriteStmt &stmt) {
1974     mlir::Value iostat = genWriteStatement(*this, stmt);
1975     genIoConditionBranches(getEval(), stmt.controls, iostat);
1976   }
1977 
1978   template <typename A>
1979   void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval,
1980                               const A &specList, mlir::Value iostat) {
1981     if (!iostat)
1982       return;
1983 
1984     mlir::Block *endBlock = nullptr;
1985     mlir::Block *eorBlock = nullptr;
1986     mlir::Block *errBlock = nullptr;
1987     for (const auto &spec : specList) {
1988       std::visit(Fortran::common::visitors{
1989                      [&](const Fortran::parser::EndLabel &label) {
1990                        endBlock = blockOfLabel(eval, label.v);
1991                      },
1992                      [&](const Fortran::parser::EorLabel &label) {
1993                        eorBlock = blockOfLabel(eval, label.v);
1994                      },
1995                      [&](const Fortran::parser::ErrLabel &label) {
1996                        errBlock = blockOfLabel(eval, label.v);
1997                      },
1998                      [](const auto &) {}},
1999                  spec.u);
2000     }
2001     if (!endBlock && !eorBlock && !errBlock)
2002       return;
2003 
2004     mlir::Location loc = toLocation();
2005     mlir::Type indexType = builder->getIndexType();
2006     mlir::Value selector = builder->createConvert(loc, indexType, iostat);
2007     llvm::SmallVector<int64_t> indexList;
2008     llvm::SmallVector<mlir::Block *> blockList;
2009     if (eorBlock) {
2010       indexList.push_back(Fortran::runtime::io::IostatEor);
2011       blockList.push_back(eorBlock);
2012     }
2013     if (endBlock) {
2014       indexList.push_back(Fortran::runtime::io::IostatEnd);
2015       blockList.push_back(endBlock);
2016     }
2017     if (errBlock) {
2018       indexList.push_back(0);
2019       blockList.push_back(eval.nonNopSuccessor().block);
2020       // ERR label statement is the default successor.
2021       blockList.push_back(errBlock);
2022     } else {
2023       // Fallthrough successor statement is the default successor.
2024       blockList.push_back(eval.nonNopSuccessor().block);
2025     }
2026     builder->create<fir::SelectOp>(loc, selector, indexList, blockList);
2027   }
2028 
2029   //===--------------------------------------------------------------------===//
2030   // Memory allocation and deallocation
2031   //===--------------------------------------------------------------------===//
2032 
2033   void genFIR(const Fortran::parser::AllocateStmt &stmt) {
2034     Fortran::lower::genAllocateStmt(*this, stmt, toLocation());
2035   }
2036 
2037   void genFIR(const Fortran::parser::DeallocateStmt &stmt) {
2038     Fortran::lower::genDeallocateStmt(*this, stmt, toLocation());
2039   }
2040 
2041   /// Nullify pointer object list
2042   ///
2043   /// For each pointer object, reset the pointer to a disassociated status.
2044   /// We do this by setting each pointer to null.
2045   void genFIR(const Fortran::parser::NullifyStmt &stmt) {
2046     mlir::Location loc = toLocation();
2047     for (auto &pointerObject : stmt.v) {
2048       const Fortran::lower::SomeExpr *expr =
2049           Fortran::semantics::GetExpr(pointerObject);
2050       assert(expr);
2051       fir::MutableBoxValue box = genExprMutableBox(loc, *expr);
2052       fir::factory::disassociateMutableBox(*builder, loc, box);
2053     }
2054   }
2055 
2056   //===--------------------------------------------------------------------===//
2057 
2058   void genFIR(const Fortran::parser::EventPostStmt &stmt) {
2059     genEventPostStatement(*this, stmt);
2060   }
2061 
2062   void genFIR(const Fortran::parser::EventWaitStmt &stmt) {
2063     genEventWaitStatement(*this, stmt);
2064   }
2065 
2066   void genFIR(const Fortran::parser::FormTeamStmt &stmt) {
2067     genFormTeamStatement(*this, getEval(), stmt);
2068   }
2069 
2070   void genFIR(const Fortran::parser::LockStmt &stmt) {
2071     genLockStatement(*this, stmt);
2072   }
2073 
2074   fir::ExtendedValue
2075   genInitializerExprValue(const Fortran::lower::SomeExpr &expr,
2076                           Fortran::lower::StatementContext &stmtCtx) {
2077     return Fortran::lower::createSomeInitializerExpression(
2078         toLocation(), *this, expr, localSymbols, stmtCtx);
2079   }
2080 
2081   /// Return true if the current context is a conditionalized and implied
2082   /// iteration space.
2083   bool implicitIterationSpace() { return !implicitIterSpace.empty(); }
2084 
2085   /// Return true if context is currently an explicit iteration space. A scalar
2086   /// assignment expression may be contextually within a user-defined iteration
2087   /// space, transforming it into an array expression.
2088   bool explicitIterationSpace() { return explicitIterSpace.isActive(); }
2089 
2090   /// Generate an array assignment.
2091   /// This is an assignment expression with rank > 0. The assignment may or may
2092   /// not be in a WHERE and/or FORALL context.
2093   /// In a FORALL context, the assignment may be a pointer assignment and the \p
2094   /// lbounds and \p ubounds parameters should only be used in such a pointer
2095   /// assignment case. (If both are None then the array assignment cannot be a
2096   /// pointer assignment.)
2097   void genArrayAssignment(
2098       const Fortran::evaluate::Assignment &assign,
2099       Fortran::lower::StatementContext &stmtCtx,
2100       llvm::Optional<llvm::SmallVector<mlir::Value>> lbounds = llvm::None,
2101       llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds = llvm::None) {
2102     if (Fortran::lower::isWholeAllocatable(assign.lhs)) {
2103       // Assignment to allocatables may require the lhs to be
2104       // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3
2105       Fortran::lower::createAllocatableArrayAssignment(
2106           *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
2107           localSymbols, stmtCtx);
2108       return;
2109     }
2110 
2111     if (lbounds) {
2112       // Array of POINTER entities, with elemental assignment.
2113       if (!Fortran::lower::isWholePointer(assign.lhs))
2114         fir::emitFatalError(toLocation(), "pointer assignment to non-pointer");
2115 
2116       Fortran::lower::createArrayOfPointerAssignment(
2117           *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
2118           *lbounds, ubounds, localSymbols, stmtCtx);
2119       return;
2120     }
2121 
2122     if (!implicitIterationSpace() && !explicitIterationSpace()) {
2123       // No masks and the iteration space is implied by the array, so create a
2124       // simple array assignment.
2125       Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs,
2126                                                 localSymbols, stmtCtx);
2127       return;
2128     }
2129 
2130     // If there is an explicit iteration space, generate an array assignment
2131     // with a user-specified iteration space and possibly with masks. These
2132     // assignments may *appear* to be scalar expressions, but the scalar
2133     // expression is evaluated at all points in the user-defined space much like
2134     // an ordinary array assignment. More specifically, the semantics inside the
2135     // FORALL much more closely resembles that of WHERE than a scalar
2136     // assignment.
2137     // Otherwise, generate a masked array assignment. The iteration space is
2138     // implied by the lhs array expression.
2139     Fortran::lower::createAnyMaskedArrayAssignment(
2140         *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
2141         localSymbols,
2142         explicitIterationSpace() ? explicitIterSpace.stmtContext()
2143                                  : implicitIterSpace.stmtContext());
2144   }
2145 
2146 #if !defined(NDEBUG)
2147   static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) {
2148     const Fortran::semantics::Symbol *sym =
2149         Fortran::evaluate::GetFirstSymbol(expr);
2150     return sym && sym->IsFuncResult();
2151   }
2152 #endif
2153 
2154   inline fir::MutableBoxValue
2155   genExprMutableBox(mlir::Location loc,
2156                     const Fortran::lower::SomeExpr &expr) override final {
2157     return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols);
2158   }
2159 
2160   /// Shared for both assignments and pointer assignments.
2161   void genAssignment(const Fortran::evaluate::Assignment &assign) {
2162     Fortran::lower::StatementContext stmtCtx;
2163     mlir::Location loc = toLocation();
2164     if (explicitIterationSpace()) {
2165       Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols);
2166       explicitIterSpace.genLoopNest();
2167     }
2168     std::visit(
2169         Fortran::common::visitors{
2170             // [1] Plain old assignment.
2171             [&](const Fortran::evaluate::Assignment::Intrinsic &) {
2172               const Fortran::semantics::Symbol *sym =
2173                   Fortran::evaluate::GetLastSymbol(assign.lhs);
2174 
2175               if (!sym)
2176                 TODO(loc, "assignment to pointer result of function reference");
2177 
2178               std::optional<Fortran::evaluate::DynamicType> lhsType =
2179                   assign.lhs.GetType();
2180               assert(lhsType && "lhs cannot be typeless");
2181               // Assignment to polymorphic allocatables may require changing the
2182               // variable dynamic type (See Fortran 2018 10.2.1.3 p3).
2183               if (lhsType->IsPolymorphic() &&
2184                   Fortran::lower::isWholeAllocatable(assign.lhs))
2185                 TODO(loc, "assignment to polymorphic allocatable");
2186 
2187               // Note: No ad-hoc handling for pointers is required here. The
2188               // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr
2189               // on a pointer returns the target address and not the address of
2190               // the pointer variable.
2191 
2192               if (assign.lhs.Rank() > 0 || explicitIterationSpace()) {
2193                 // Array assignment
2194                 // See Fortran 2018 10.2.1.3 p5, p6, and p7
2195                 genArrayAssignment(assign, stmtCtx);
2196                 return;
2197               }
2198 
2199               // Scalar assignment
2200               const bool isNumericScalar =
2201                   isNumericScalarCategory(lhsType->category());
2202               fir::ExtendedValue rhs = isNumericScalar
2203                                            ? genExprValue(assign.rhs, stmtCtx)
2204                                            : genExprAddr(assign.rhs, stmtCtx);
2205               const bool lhsIsWholeAllocatable =
2206                   Fortran::lower::isWholeAllocatable(assign.lhs);
2207               llvm::Optional<fir::factory::MutableBoxReallocation> lhsRealloc;
2208               llvm::Optional<fir::MutableBoxValue> lhsMutableBox;
2209               auto lhs = [&]() -> fir::ExtendedValue {
2210                 if (lhsIsWholeAllocatable) {
2211                   lhsMutableBox = genExprMutableBox(loc, assign.lhs);
2212                   llvm::SmallVector<mlir::Value> lengthParams;
2213                   if (const fir::CharBoxValue *charBox = rhs.getCharBox())
2214                     lengthParams.push_back(charBox->getLen());
2215                   else if (fir::isDerivedWithLenParameters(rhs))
2216                     TODO(loc, "assignment to derived type allocatable with "
2217                               "LEN parameters");
2218                   lhsRealloc = fir::factory::genReallocIfNeeded(
2219                       *builder, loc, *lhsMutableBox,
2220                       /*shape=*/llvm::None, lengthParams);
2221                   return lhsRealloc->newValue;
2222                 }
2223                 return genExprAddr(assign.lhs, stmtCtx);
2224               }();
2225 
2226               if (isNumericScalar) {
2227                 // Fortran 2018 10.2.1.3 p8 and p9
2228                 // Conversions should have been inserted by semantic analysis,
2229                 // but they can be incorrect between the rhs and lhs. Correct
2230                 // that here.
2231                 mlir::Value addr = fir::getBase(lhs);
2232                 mlir::Value val = fir::getBase(rhs);
2233                 // A function with multiple entry points returning different
2234                 // types tags all result variables with one of the largest
2235                 // types to allow them to share the same storage.  Assignment
2236                 // to a result variable of one of the other types requires
2237                 // conversion to the actual type.
2238                 mlir::Type toTy = genType(assign.lhs);
2239                 mlir::Value cast =
2240                     builder->convertWithSemantics(loc, toTy, val);
2241                 if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) {
2242                   assert(isFuncResultDesignator(assign.lhs) && "type mismatch");
2243                   addr = builder->createConvert(
2244                       toLocation(), builder->getRefType(toTy), addr);
2245                 }
2246                 builder->create<fir::StoreOp>(loc, cast, addr);
2247               } else if (isCharacterCategory(lhsType->category())) {
2248                 // Fortran 2018 10.2.1.3 p10 and p11
2249                 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(
2250                     lhs, rhs);
2251               } else if (isDerivedCategory(lhsType->category())) {
2252                 // Fortran 2018 10.2.1.3 p13 and p14
2253                 // Recursively gen an assignment on each element pair.
2254                 fir::factory::genRecordAssignment(*builder, loc, lhs, rhs);
2255               } else {
2256                 llvm_unreachable("unknown category");
2257               }
2258               if (lhsIsWholeAllocatable)
2259                 fir::factory::finalizeRealloc(
2260                     *builder, loc, lhsMutableBox.getValue(),
2261                     /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false,
2262                     lhsRealloc.getValue());
2263             },
2264 
2265             // [2] User defined assignment. If the context is a scalar
2266             // expression then call the procedure.
2267             [&](const Fortran::evaluate::ProcedureRef &procRef) {
2268               Fortran::lower::StatementContext &ctx =
2269                   explicitIterationSpace() ? explicitIterSpace.stmtContext()
2270                                            : stmtCtx;
2271               Fortran::lower::createSubroutineCall(
2272                   *this, procRef, explicitIterSpace, implicitIterSpace,
2273                   localSymbols, ctx, /*isUserDefAssignment=*/true);
2274             },
2275 
2276             // [3] Pointer assignment with possibly empty bounds-spec. R1035: a
2277             // bounds-spec is a lower bound value.
2278             [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) {
2279               if (Fortran::evaluate::IsProcedure(assign.rhs))
2280                 TODO(loc, "procedure pointer assignment");
2281               std::optional<Fortran::evaluate::DynamicType> lhsType =
2282                   assign.lhs.GetType();
2283               std::optional<Fortran::evaluate::DynamicType> rhsType =
2284                   assign.rhs.GetType();
2285               // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3.
2286               if ((lhsType && lhsType->IsPolymorphic()) ||
2287                   (rhsType && rhsType->IsPolymorphic()))
2288                 TODO(loc, "pointer assignment involving polymorphic entity");
2289 
2290               llvm::SmallVector<mlir::Value> lbounds;
2291               for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs)
2292                 lbounds.push_back(
2293                     fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
2294               if (explicitIterationSpace()) {
2295                 // Pointer assignment in FORALL context. Copy the rhs box value
2296                 // into the lhs box variable.
2297                 genArrayAssignment(assign, stmtCtx, lbounds);
2298                 return;
2299               }
2300               fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
2301               Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs,
2302                                                   lbounds, stmtCtx);
2303             },
2304 
2305             // [4] Pointer assignment with bounds-remapping. R1036: a
2306             // bounds-remapping is a pair, lower bound and upper bound.
2307             [&](const Fortran::evaluate::Assignment::BoundsRemapping
2308                     &boundExprs) {
2309               std::optional<Fortran::evaluate::DynamicType> lhsType =
2310                   assign.lhs.GetType();
2311               std::optional<Fortran::evaluate::DynamicType> rhsType =
2312                   assign.rhs.GetType();
2313               // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3.
2314               if ((lhsType && lhsType->IsPolymorphic()) ||
2315                   (rhsType && rhsType->IsPolymorphic()))
2316                 TODO(loc, "pointer assignment involving polymorphic entity");
2317 
2318               llvm::SmallVector<mlir::Value> lbounds;
2319               llvm::SmallVector<mlir::Value> ubounds;
2320               for (const std::pair<Fortran::evaluate::ExtentExpr,
2321                                    Fortran::evaluate::ExtentExpr> &pair :
2322                    boundExprs) {
2323                 const Fortran::evaluate::ExtentExpr &lbExpr = pair.first;
2324                 const Fortran::evaluate::ExtentExpr &ubExpr = pair.second;
2325                 lbounds.push_back(
2326                     fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
2327                 ubounds.push_back(
2328                     fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx)));
2329               }
2330               if (explicitIterationSpace()) {
2331                 // Pointer assignment in FORALL context. Copy the rhs box value
2332                 // into the lhs box variable.
2333                 genArrayAssignment(assign, stmtCtx, lbounds, ubounds);
2334                 return;
2335               }
2336               fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
2337               if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
2338                       assign.rhs)) {
2339                 fir::factory::disassociateMutableBox(*builder, loc, lhs);
2340                 return;
2341               }
2342               // Do not generate a temp in case rhs is an array section.
2343               fir::ExtendedValue rhs =
2344                   Fortran::lower::isArraySectionWithoutVectorSubscript(
2345                       assign.rhs)
2346                       ? Fortran::lower::createSomeArrayBox(
2347                             *this, assign.rhs, localSymbols, stmtCtx)
2348                       : genExprAddr(assign.rhs, stmtCtx);
2349               fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs,
2350                                                          rhs, lbounds, ubounds);
2351               if (explicitIterationSpace()) {
2352                 mlir::ValueRange inners = explicitIterSpace.getInnerArgs();
2353                 if (!inners.empty())
2354                   builder->create<fir::ResultOp>(loc, inners);
2355               }
2356             },
2357         },
2358         assign.u);
2359     if (explicitIterationSpace())
2360       Fortran::lower::createArrayMergeStores(*this, explicitIterSpace);
2361   }
2362 
2363   void genFIR(const Fortran::parser::WhereConstruct &c) {
2364     implicitIterSpace.growStack();
2365     genNestedStatement(
2366         std::get<
2367             Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
2368             c.t));
2369     for (const auto &body :
2370          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
2371       genFIR(body);
2372     for (const auto &e :
2373          std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
2374              c.t))
2375       genFIR(e);
2376     if (const auto &e =
2377             std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
2378                 c.t);
2379         e.has_value())
2380       genFIR(*e);
2381     genNestedStatement(
2382         std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>(
2383             c.t));
2384   }
2385   void genFIR(const Fortran::parser::WhereBodyConstruct &body) {
2386     std::visit(
2387         Fortran::common::visitors{
2388             [&](const Fortran::parser::Statement<
2389                 Fortran::parser::AssignmentStmt> &stmt) {
2390               genNestedStatement(stmt);
2391             },
2392             [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt>
2393                     &stmt) { genNestedStatement(stmt); },
2394             [&](const Fortran::common::Indirection<
2395                 Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); },
2396         },
2397         body.u);
2398   }
2399   void genFIR(const Fortran::parser::WhereConstructStmt &stmt) {
2400     implicitIterSpace.append(Fortran::semantics::GetExpr(
2401         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2402   }
2403   void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
2404     genNestedStatement(
2405         std::get<
2406             Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
2407             ew.t));
2408     for (const auto &body :
2409          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2410       genFIR(body);
2411   }
2412   void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) {
2413     implicitIterSpace.append(Fortran::semantics::GetExpr(
2414         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2415   }
2416   void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) {
2417     genNestedStatement(
2418         std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>(
2419             ew.t));
2420     for (const auto &body :
2421          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2422       genFIR(body);
2423   }
2424   void genFIR(const Fortran::parser::ElsewhereStmt &stmt) {
2425     implicitIterSpace.append(nullptr);
2426   }
2427   void genFIR(const Fortran::parser::EndWhereStmt &) {
2428     implicitIterSpace.shrinkStack();
2429   }
2430 
2431   void genFIR(const Fortran::parser::WhereStmt &stmt) {
2432     Fortran::lower::StatementContext stmtCtx;
2433     const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t);
2434     implicitIterSpace.growStack();
2435     implicitIterSpace.append(Fortran::semantics::GetExpr(
2436         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2437     genAssignment(*assign.typedAssignment->v);
2438     implicitIterSpace.shrinkStack();
2439   }
2440 
2441   void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) {
2442     genAssignment(*stmt.typedAssignment->v);
2443   }
2444 
2445   void genFIR(const Fortran::parser::AssignmentStmt &stmt) {
2446     genAssignment(*stmt.typedAssignment->v);
2447   }
2448 
2449   void genFIR(const Fortran::parser::SyncAllStmt &stmt) {
2450     genSyncAllStatement(*this, stmt);
2451   }
2452 
2453   void genFIR(const Fortran::parser::SyncImagesStmt &stmt) {
2454     genSyncImagesStatement(*this, stmt);
2455   }
2456 
2457   void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) {
2458     genSyncMemoryStatement(*this, stmt);
2459   }
2460 
2461   void genFIR(const Fortran::parser::SyncTeamStmt &stmt) {
2462     genSyncTeamStatement(*this, stmt);
2463   }
2464 
2465   void genFIR(const Fortran::parser::UnlockStmt &stmt) {
2466     genUnlockStatement(*this, stmt);
2467   }
2468 
2469   void genFIR(const Fortran::parser::AssignStmt &stmt) {
2470     const Fortran::semantics::Symbol &symbol =
2471         *std::get<Fortran::parser::Name>(stmt.t).symbol;
2472     mlir::Location loc = toLocation();
2473     mlir::Value labelValue = builder->createIntegerConstant(
2474         loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t));
2475     builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol));
2476   }
2477 
2478   void genFIR(const Fortran::parser::FormatStmt &) {
2479     // do nothing.
2480 
2481     // FORMAT statements have no semantics. They may be lowered if used by a
2482     // data transfer statement.
2483   }
2484 
2485   void genFIR(const Fortran::parser::PauseStmt &stmt) {
2486     genPauseStatement(*this, stmt);
2487   }
2488 
2489   // call FAIL IMAGE in runtime
2490   void genFIR(const Fortran::parser::FailImageStmt &stmt) {
2491     genFailImageStatement(*this);
2492   }
2493 
2494   // call STOP, ERROR STOP in runtime
2495   void genFIR(const Fortran::parser::StopStmt &stmt) {
2496     genStopStatement(*this, stmt);
2497   }
2498 
2499   void genFIR(const Fortran::parser::ReturnStmt &stmt) {
2500     Fortran::lower::pft::FunctionLikeUnit *funit =
2501         getEval().getOwningProcedure();
2502     assert(funit && "not inside main program, function or subroutine");
2503     if (funit->isMainProgram()) {
2504       genExitRoutine();
2505       return;
2506     }
2507     mlir::Location loc = toLocation();
2508     if (stmt.v) {
2509       // Alternate return statement - If this is a subroutine where some
2510       // alternate entries have alternate returns, but the active entry point
2511       // does not, ignore the alternate return value.  Otherwise, assign it
2512       // to the compiler-generated result variable.
2513       const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol();
2514       if (Fortran::semantics::HasAlternateReturns(symbol)) {
2515         Fortran::lower::StatementContext stmtCtx;
2516         const Fortran::lower::SomeExpr *expr =
2517             Fortran::semantics::GetExpr(*stmt.v);
2518         assert(expr && "missing alternate return expression");
2519         mlir::Value altReturnIndex = builder->createConvert(
2520             loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx));
2521         builder->create<fir::StoreOp>(loc, altReturnIndex,
2522                                       getAltReturnResult(symbol));
2523       }
2524     }
2525     // Branch to the last block of the SUBROUTINE, which has the actual return.
2526     if (!funit->finalBlock) {
2527       mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint();
2528       funit->finalBlock = builder->createBlock(&builder->getRegion());
2529       builder->restoreInsertionPoint(insPt);
2530     }
2531     builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock);
2532   }
2533 
2534   void genFIR(const Fortran::parser::CycleStmt &) {
2535     genFIRBranch(getEval().controlSuccessor->block);
2536   }
2537   void genFIR(const Fortran::parser::ExitStmt &) {
2538     genFIRBranch(getEval().controlSuccessor->block);
2539   }
2540   void genFIR(const Fortran::parser::GotoStmt &) {
2541     genFIRBranch(getEval().controlSuccessor->block);
2542   }
2543 
2544   // Nop statements - No code, or code is generated at the construct level.
2545   void genFIR(const Fortran::parser::AssociateStmt &) {}       // nop
2546   void genFIR(const Fortran::parser::CaseStmt &) {}            // nop
2547   void genFIR(const Fortran::parser::ContinueStmt &) {}        // nop
2548   void genFIR(const Fortran::parser::ElseIfStmt &) {}          // nop
2549   void genFIR(const Fortran::parser::ElseStmt &) {}            // nop
2550   void genFIR(const Fortran::parser::EndAssociateStmt &) {}    // nop
2551   void genFIR(const Fortran::parser::EndDoStmt &) {}           // nop
2552   void genFIR(const Fortran::parser::EndFunctionStmt &) {}     // nop
2553   void genFIR(const Fortran::parser::EndIfStmt &) {}           // nop
2554   void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop
2555   void genFIR(const Fortran::parser::EndSelectStmt &) {}       // nop
2556   void genFIR(const Fortran::parser::EndSubroutineStmt &) {}   // nop
2557   void genFIR(const Fortran::parser::EntryStmt &) {}           // nop
2558   void genFIR(const Fortran::parser::IfStmt &) {}              // nop
2559   void genFIR(const Fortran::parser::IfThenStmt &) {}          // nop
2560   void genFIR(const Fortran::parser::NonLabelDoStmt &) {}      // nop
2561   void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop
2562 
2563   void genFIR(const Fortran::parser::NamelistStmt &) {
2564     TODO(toLocation(), "NamelistStmt lowering");
2565   }
2566 
2567   /// Generate FIR for the Evaluation `eval`.
2568   void genFIR(Fortran::lower::pft::Evaluation &eval,
2569               bool unstructuredContext = true) {
2570     if (unstructuredContext) {
2571       // When transitioning from unstructured to structured code,
2572       // the structured code could be a target that starts a new block.
2573       maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured()
2574                           ? eval.getFirstNestedEvaluation().block
2575                           : eval.block);
2576     }
2577 
2578     setCurrentEval(eval);
2579     setCurrentPosition(eval.position);
2580     eval.visit([&](const auto &stmt) { genFIR(stmt); });
2581 
2582     if (unstructuredContext && blockIsUnterminated()) {
2583       // Exit from an unstructured IF or SELECT construct block.
2584       Fortran::lower::pft::Evaluation *successor{};
2585       if (eval.isActionStmt())
2586         successor = eval.controlSuccessor;
2587       else if (eval.isConstruct() &&
2588                eval.getLastNestedEvaluation()
2589                    .lexicalSuccessor->isIntermediateConstructStmt())
2590         successor = eval.constructExit;
2591       if (successor && successor->block)
2592         genFIRBranch(successor->block);
2593     }
2594   }
2595 
2596   /// Map mlir function block arguments to the corresponding Fortran dummy
2597   /// variables. When the result is passed as a hidden argument, the Fortran
2598   /// result is also mapped. The symbol map is used to hold this mapping.
2599   void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit,
2600                             const Fortran::lower::CalleeInterface &callee) {
2601     assert(builder && "require a builder object at this point");
2602     using PassBy = Fortran::lower::CalleeInterface::PassEntityBy;
2603     auto mapPassedEntity = [&](const auto arg) {
2604       if (arg.passBy == PassBy::AddressAndLength) {
2605         // TODO: now that fir call has some attributes regarding character
2606         // return, PassBy::AddressAndLength should be retired.
2607         mlir::Location loc = toLocation();
2608         fir::factory::CharacterExprHelper charHelp{*builder, loc};
2609         mlir::Value box =
2610             charHelp.createEmboxChar(arg.firArgument, arg.firLength);
2611         addSymbol(arg.entity->get(), box);
2612       } else {
2613         if (arg.entity.has_value()) {
2614           addSymbol(arg.entity->get(), arg.firArgument);
2615         } else {
2616           assert(funit.parentHasHostAssoc());
2617           funit.parentHostAssoc().internalProcedureBindings(*this,
2618                                                             localSymbols);
2619         }
2620       }
2621     };
2622     for (const Fortran::lower::CalleeInterface::PassedEntity &arg :
2623          callee.getPassedArguments())
2624       mapPassedEntity(arg);
2625     if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2626             passedResult = callee.getPassedResult()) {
2627       mapPassedEntity(*passedResult);
2628       // FIXME: need to make sure things are OK here. addSymbol may not be OK
2629       if (funit.primaryResult &&
2630           passedResult->entity->get() != *funit.primaryResult)
2631         addSymbol(*funit.primaryResult,
2632                   getSymbolAddress(passedResult->entity->get()));
2633     }
2634   }
2635 
2636   /// Instantiate variable \p var and add it to the symbol map.
2637   /// See ConvertVariable.cpp.
2638   void instantiateVar(const Fortran::lower::pft::Variable &var,
2639                       Fortran::lower::AggregateStoreMap &storeMap) {
2640     Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap);
2641     if (var.hasSymbol() &&
2642         var.getSymbol().test(
2643             Fortran::semantics::Symbol::Flag::OmpThreadprivate))
2644       Fortran::lower::genThreadprivateOp(*this, var);
2645   }
2646 
2647   /// Prepare to translate a new function
2648   void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
2649     assert(!builder && "expected nullptr");
2650     Fortran::lower::CalleeInterface callee(funit, *this);
2651     mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments();
2652     builder = new fir::FirOpBuilder(func, bridge.getKindMap());
2653     assert(builder && "FirOpBuilder did not instantiate");
2654     builder->setInsertionPointToStart(&func.front());
2655     func.setVisibility(mlir::SymbolTable::Visibility::Public);
2656 
2657     mapDummiesAndResults(funit, callee);
2658 
2659     // Note: not storing Variable references because getOrderedSymbolTable
2660     // below returns a temporary.
2661     llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList;
2662 
2663     // Backup actual argument for entry character results
2664     // with different lengths. It needs to be added to the non
2665     // primary results symbol before mapSymbolAttributes is called.
2666     Fortran::lower::SymbolBox resultArg;
2667     if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2668             passedResult = callee.getPassedResult())
2669       resultArg = lookupSymbol(passedResult->entity->get());
2670 
2671     Fortran::lower::AggregateStoreMap storeMap;
2672     // The front-end is currently not adding module variables referenced
2673     // in a module procedure as host associated. As a result we need to
2674     // instantiate all module variables here if this is a module procedure.
2675     // It is likely that the front-end behavior should change here.
2676     // This also applies to internal procedures inside module procedures.
2677     if (auto *module = Fortran::lower::pft::getAncestor<
2678             Fortran::lower::pft::ModuleLikeUnit>(funit))
2679       for (const Fortran::lower::pft::Variable &var :
2680            module->getOrderedSymbolTable())
2681         instantiateVar(var, storeMap);
2682 
2683     mlir::Value primaryFuncResultStorage;
2684     for (const Fortran::lower::pft::Variable &var :
2685          funit.getOrderedSymbolTable()) {
2686       // Always instantiate aggregate storage blocks.
2687       if (var.isAggregateStore()) {
2688         instantiateVar(var, storeMap);
2689         continue;
2690       }
2691       const Fortran::semantics::Symbol &sym = var.getSymbol();
2692       if (funit.parentHasHostAssoc()) {
2693         // Never instantitate host associated variables, as they are already
2694         // instantiated from an argument tuple. Instead, just bind the symbol to
2695         // the reference to the host variable, which must be in the map.
2696         const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
2697         if (funit.parentHostAssoc().isAssociated(ultimate)) {
2698           Fortran::lower::SymbolBox hostBox =
2699               localSymbols.lookupSymbol(ultimate);
2700           assert(hostBox && "host association is not in map");
2701           localSymbols.addSymbol(sym, hostBox.toExtendedValue());
2702           continue;
2703         }
2704       }
2705       if (!sym.IsFuncResult() || !funit.primaryResult) {
2706         instantiateVar(var, storeMap);
2707       } else if (&sym == funit.primaryResult) {
2708         instantiateVar(var, storeMap);
2709         primaryFuncResultStorage = getSymbolAddress(sym);
2710       } else {
2711         deferredFuncResultList.push_back(var);
2712       }
2713     }
2714 
2715     // TODO: should use same mechanism as equivalence?
2716     // One blocking point is character entry returns that need special handling
2717     // since they are not locally allocated but come as argument. CHARACTER(*)
2718     // is not something that fits well with equivalence lowering.
2719     for (const Fortran::lower::pft::Variable &altResult :
2720          deferredFuncResultList) {
2721       if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2722               passedResult = callee.getPassedResult())
2723         addSymbol(altResult.getSymbol(), resultArg.getAddr());
2724       Fortran::lower::StatementContext stmtCtx;
2725       Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols,
2726                                           stmtCtx, primaryFuncResultStorage);
2727     }
2728 
2729     // If this is a host procedure with host associations, then create the tuple
2730     // of pointers for passing to the internal procedures.
2731     if (!funit.getHostAssoc().empty())
2732       funit.getHostAssoc().hostProcedureBindings(*this, localSymbols);
2733 
2734     // Create most function blocks in advance.
2735     createEmptyBlocks(funit.evaluationList);
2736 
2737     // Reinstate entry block as the current insertion point.
2738     builder->setInsertionPointToEnd(&func.front());
2739 
2740     if (callee.hasAlternateReturns()) {
2741       // Create a local temp to hold the alternate return index.
2742       // Give it an integer index type and the subroutine name (for dumps).
2743       // Attach it to the subroutine symbol in the localSymbols map.
2744       // Initialize it to zero, the "fallthrough" alternate return value.
2745       const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol();
2746       mlir::Location loc = toLocation();
2747       mlir::Type idxTy = builder->getIndexType();
2748       mlir::Value altResult =
2749           builder->createTemporary(loc, idxTy, toStringRef(symbol.name()));
2750       addSymbol(symbol, altResult);
2751       mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0);
2752       builder->create<fir::StoreOp>(loc, zero, altResult);
2753     }
2754 
2755     if (Fortran::lower::pft::Evaluation *alternateEntryEval =
2756             funit.getEntryEval())
2757       genFIRBranch(alternateEntryEval->lexicalSuccessor->block);
2758   }
2759 
2760   /// Create global blocks for the current function.  This eliminates the
2761   /// distinction between forward and backward targets when generating
2762   /// branches.  A block is "global" if it can be the target of a GOTO or
2763   /// other source code branch.  A block that can only be targeted by a
2764   /// compiler generated branch is "local".  For example, a DO loop preheader
2765   /// block containing loop initialization code is global.  A loop header
2766   /// block, which is the target of the loop back edge, is local.  Blocks
2767   /// belong to a region.  Any block within a nested region must be replaced
2768   /// with a block belonging to that region.  Branches may not cross region
2769   /// boundaries.
2770   void createEmptyBlocks(
2771       std::list<Fortran::lower::pft::Evaluation> &evaluationList) {
2772     mlir::Region *region = &builder->getRegion();
2773     for (Fortran::lower::pft::Evaluation &eval : evaluationList) {
2774       if (eval.isNewBlock)
2775         eval.block = builder->createBlock(region);
2776       if (eval.isConstruct() || eval.isDirective()) {
2777         if (eval.lowerAsUnstructured()) {
2778           createEmptyBlocks(eval.getNestedEvaluations());
2779         } else if (eval.hasNestedEvaluations()) {
2780           // A structured construct that is a target starts a new block.
2781           Fortran::lower::pft::Evaluation &constructStmt =
2782               eval.getFirstNestedEvaluation();
2783           if (constructStmt.isNewBlock)
2784             constructStmt.block = builder->createBlock(region);
2785         }
2786       }
2787     }
2788   }
2789 
2790   /// Return the predicate: "current block does not have a terminator branch".
2791   bool blockIsUnterminated() {
2792     mlir::Block *currentBlock = builder->getBlock();
2793     return currentBlock->empty() ||
2794            !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>();
2795   }
2796 
2797   /// Unconditionally switch code insertion to a new block.
2798   void startBlock(mlir::Block *newBlock) {
2799     assert(newBlock && "missing block");
2800     // Default termination for the current block is a fallthrough branch to
2801     // the new block.
2802     if (blockIsUnterminated())
2803       genFIRBranch(newBlock);
2804     // Some blocks may be re/started more than once, and might not be empty.
2805     // If the new block already has (only) a terminator, set the insertion
2806     // point to the start of the block.  Otherwise set it to the end.
2807     builder->setInsertionPointToStart(newBlock);
2808     if (blockIsUnterminated())
2809       builder->setInsertionPointToEnd(newBlock);
2810   }
2811 
2812   /// Conditionally switch code insertion to a new block.
2813   void maybeStartBlock(mlir::Block *newBlock) {
2814     if (newBlock)
2815       startBlock(newBlock);
2816   }
2817 
2818   /// Emit return and cleanup after the function has been translated.
2819   void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
2820     setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt));
2821     if (funit.isMainProgram())
2822       genExitRoutine();
2823     else
2824       genFIRProcedureExit(funit, funit.getSubprogramSymbol());
2825     funit.finalBlock = nullptr;
2826     LLVM_DEBUG(llvm::dbgs() << "*** Lowering result:\n\n"
2827                             << *builder->getFunction() << '\n');
2828     // FIXME: Simplification should happen in a normal pass, not here.
2829     mlir::IRRewriter rewriter(*builder);
2830     (void)mlir::simplifyRegions(rewriter,
2831                                 {builder->getRegion()}); // remove dead code
2832     delete builder;
2833     builder = nullptr;
2834     hostAssocTuple = mlir::Value{};
2835     localSymbols.clear();
2836   }
2837 
2838   /// Helper to generate GlobalOps when the builder is not positioned in any
2839   /// region block. This is required because the FirOpBuilder assumes it is
2840   /// always positioned inside a region block when creating globals, the easiest
2841   /// way comply is to create a dummy function and to throw it afterwards.
2842   void createGlobalOutsideOfFunctionLowering(
2843       const std::function<void()> &createGlobals) {
2844     // FIXME: get rid of the bogus function context and instantiate the
2845     // globals directly into the module.
2846     mlir::MLIRContext *context = &getMLIRContext();
2847     mlir::func::FuncOp func = fir::FirOpBuilder::createFunction(
2848         mlir::UnknownLoc::get(context), getModuleOp(),
2849         fir::NameUniquer::doGenerated("Sham"),
2850         mlir::FunctionType::get(context, llvm::None, llvm::None));
2851     func.addEntryBlock();
2852     builder = new fir::FirOpBuilder(func, bridge.getKindMap());
2853     createGlobals();
2854     if (mlir::Region *region = func.getCallableRegion())
2855       region->dropAllReferences();
2856     func.erase();
2857     delete builder;
2858     builder = nullptr;
2859     localSymbols.clear();
2860   }
2861   /// Instantiate the data from a BLOCK DATA unit.
2862   void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) {
2863     createGlobalOutsideOfFunctionLowering([&]() {
2864       Fortran::lower::AggregateStoreMap fakeMap;
2865       for (const auto &[_, sym] : bdunit.symTab) {
2866         if (sym->has<Fortran::semantics::ObjectEntityDetails>()) {
2867           Fortran::lower::pft::Variable var(*sym, true);
2868           instantiateVar(var, fakeMap);
2869         }
2870       }
2871     });
2872   }
2873 
2874   /// Create fir::Global for all the common blocks that appear in the program.
2875   void
2876   lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) {
2877     createGlobalOutsideOfFunctionLowering(
2878         [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); });
2879   }
2880 
2881   /// Lower a procedure (nest).
2882   void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) {
2883     if (!funit.isMainProgram()) {
2884       const Fortran::semantics::Symbol &procSymbol =
2885           funit.getSubprogramSymbol();
2886       if (procSymbol.owner().IsSubmodule())
2887         TODO(toLocation(), "support for submodules");
2888       if (Fortran::semantics::IsSeparateModuleProcedureInterface(&procSymbol))
2889         TODO(toLocation(), "separate module procedure");
2890     }
2891     setCurrentPosition(funit.getStartingSourceLoc());
2892     for (int entryIndex = 0, last = funit.entryPointList.size();
2893          entryIndex < last; ++entryIndex) {
2894       funit.setActiveEntry(entryIndex);
2895       startNewFunction(funit); // the entry point for lowering this procedure
2896       for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList)
2897         genFIR(eval);
2898       endNewFunction(funit);
2899     }
2900     funit.setActiveEntry(0);
2901     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
2902       lowerFunc(f); // internal procedure
2903   }
2904 
2905   /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC
2906   /// declarative construct.
2907   void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) {
2908     setCurrentPosition(mod.getStartingSourceLoc());
2909     createGlobalOutsideOfFunctionLowering([&]() {
2910       for (const Fortran::lower::pft::Variable &var :
2911            mod.getOrderedSymbolTable()) {
2912         // Only define the variables owned by this module.
2913         const Fortran::semantics::Scope *owningScope = var.getOwningScope();
2914         if (!owningScope || mod.getScope() == *owningScope)
2915           Fortran::lower::defineModuleVariable(*this, var);
2916       }
2917       for (auto &eval : mod.evaluationList)
2918         genFIR(eval);
2919     });
2920   }
2921 
2922   /// Lower functions contained in a module.
2923   void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) {
2924     for (Fortran::lower::pft::FunctionLikeUnit &f : mod.nestedFunctions)
2925       lowerFunc(f);
2926   }
2927 
2928   void setCurrentPosition(const Fortran::parser::CharBlock &position) {
2929     if (position != Fortran::parser::CharBlock{})
2930       currentPosition = position;
2931   }
2932 
2933   /// Set current position at the location of \p parseTreeNode. Note that the
2934   /// position is updated automatically when visiting statements, but not when
2935   /// entering higher level nodes like constructs or procedures. This helper is
2936   /// intended to cover the latter cases.
2937   template <typename A>
2938   void setCurrentPositionAt(const A &parseTreeNode) {
2939     setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode));
2940   }
2941 
2942   //===--------------------------------------------------------------------===//
2943   // Utility methods
2944   //===--------------------------------------------------------------------===//
2945 
2946   /// Convert a parser CharBlock to a Location
2947   mlir::Location toLocation(const Fortran::parser::CharBlock &cb) {
2948     return genLocation(cb);
2949   }
2950 
2951   mlir::Location toLocation() { return toLocation(currentPosition); }
2952   void setCurrentEval(Fortran::lower::pft::Evaluation &eval) {
2953     evalPtr = &eval;
2954   }
2955   Fortran::lower::pft::Evaluation &getEval() {
2956     assert(evalPtr);
2957     return *evalPtr;
2958   }
2959 
2960   std::optional<Fortran::evaluate::Shape>
2961   getShape(const Fortran::lower::SomeExpr &expr) {
2962     return Fortran::evaluate::GetShape(foldingContext, expr);
2963   }
2964 
2965   //===--------------------------------------------------------------------===//
2966   // Analysis on a nested explicit iteration space.
2967   //===--------------------------------------------------------------------===//
2968 
2969   void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) {
2970     explicitIterSpace.pushLevel();
2971     for (const Fortran::parser::ConcurrentControl &ctrl :
2972          std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
2973       const Fortran::semantics::Symbol *ctrlVar =
2974           std::get<Fortran::parser::Name>(ctrl.t).symbol;
2975       explicitIterSpace.addSymbol(ctrlVar);
2976     }
2977     if (const auto &mask =
2978             std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
2979                 header.t);
2980         mask.has_value())
2981       analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask));
2982   }
2983   template <bool LHS = false, typename A>
2984   void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) {
2985     explicitIterSpace.exprBase(&e, LHS);
2986   }
2987   void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) {
2988     auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs,
2989                              const Fortran::lower::SomeExpr &rhs) {
2990       analyzeExplicitSpace</*LHS=*/true>(lhs);
2991       analyzeExplicitSpace(rhs);
2992     };
2993     std::visit(
2994         Fortran::common::visitors{
2995             [&](const Fortran::evaluate::ProcedureRef &procRef) {
2996               // Ensure the procRef expressions are the one being visited.
2997               assert(procRef.arguments().size() == 2);
2998               const Fortran::lower::SomeExpr *lhs =
2999                   procRef.arguments()[0].value().UnwrapExpr();
3000               const Fortran::lower::SomeExpr *rhs =
3001                   procRef.arguments()[1].value().UnwrapExpr();
3002               assert(lhs && rhs &&
3003                      "user defined assignment arguments must be expressions");
3004               analyzeAssign(*lhs, *rhs);
3005             },
3006             [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }},
3007         assign->u);
3008     explicitIterSpace.endAssign();
3009   }
3010   void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) {
3011     std::visit([&](const auto &s) { analyzeExplicitSpace(s); }, stmt.u);
3012   }
3013   void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) {
3014     analyzeExplicitSpace(s.typedAssignment->v.operator->());
3015   }
3016   void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) {
3017     analyzeExplicitSpace(s.typedAssignment->v.operator->());
3018   }
3019   void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) {
3020     analyzeExplicitSpace(
3021         std::get<
3022             Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
3023             c.t)
3024             .statement);
3025     for (const Fortran::parser::WhereBodyConstruct &body :
3026          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
3027       analyzeExplicitSpace(body);
3028     for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e :
3029          std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
3030              c.t))
3031       analyzeExplicitSpace(e);
3032     if (const auto &e =
3033             std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
3034                 c.t);
3035         e.has_value())
3036       analyzeExplicitSpace(e.operator->());
3037   }
3038   void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) {
3039     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
3040         std::get<Fortran::parser::LogicalExpr>(ws.t));
3041     addMaskVariable(exp);
3042     analyzeExplicitSpace(*exp);
3043   }
3044   void analyzeExplicitSpace(
3045       const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
3046     analyzeExplicitSpace(
3047         std::get<
3048             Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
3049             ew.t)
3050             .statement);
3051     for (const Fortran::parser::WhereBodyConstruct &e :
3052          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
3053       analyzeExplicitSpace(e);
3054   }
3055   void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) {
3056     std::visit(Fortran::common::visitors{
3057                    [&](const Fortran::common::Indirection<
3058                        Fortran::parser::WhereConstruct> &wc) {
3059                      analyzeExplicitSpace(wc.value());
3060                    },
3061                    [&](const auto &s) { analyzeExplicitSpace(s.statement); }},
3062                body.u);
3063   }
3064   void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) {
3065     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
3066         std::get<Fortran::parser::LogicalExpr>(stmt.t));
3067     addMaskVariable(exp);
3068     analyzeExplicitSpace(*exp);
3069   }
3070   void
3071   analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) {
3072     for (const Fortran::parser::WhereBodyConstruct &e :
3073          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t))
3074       analyzeExplicitSpace(e);
3075   }
3076   void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) {
3077     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
3078         std::get<Fortran::parser::LogicalExpr>(stmt.t));
3079     addMaskVariable(exp);
3080     analyzeExplicitSpace(*exp);
3081     const std::optional<Fortran::evaluate::Assignment> &assign =
3082         std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v;
3083     assert(assign.has_value() && "WHERE has no statement");
3084     analyzeExplicitSpace(assign.operator->());
3085   }
3086   void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) {
3087     analyzeExplicitSpace(
3088         std::get<
3089             Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
3090             forall.t)
3091             .value());
3092     analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement<
3093                              Fortran::parser::ForallAssignmentStmt>>(forall.t)
3094                              .statement);
3095     analyzeExplicitSpacePop();
3096   }
3097   void
3098   analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) {
3099     analyzeExplicitSpace(
3100         std::get<
3101             Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
3102             forall.t)
3103             .value());
3104   }
3105   void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) {
3106     analyzeExplicitSpace(
3107         std::get<
3108             Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
3109             forall.t)
3110             .statement);
3111     for (const Fortran::parser::ForallBodyConstruct &s :
3112          std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
3113       std::visit(Fortran::common::visitors{
3114                      [&](const Fortran::common::Indirection<
3115                          Fortran::parser::ForallConstruct> &b) {
3116                        analyzeExplicitSpace(b.value());
3117                      },
3118                      [&](const Fortran::parser::WhereConstruct &w) {
3119                        analyzeExplicitSpace(w);
3120                      },
3121                      [&](const auto &b) { analyzeExplicitSpace(b.statement); }},
3122                  s.u);
3123     }
3124     analyzeExplicitSpacePop();
3125   }
3126 
3127   void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); }
3128 
3129   void addMaskVariable(Fortran::lower::FrontEndExpr exp) {
3130     // Note: use i8 to store bool values. This avoids round-down behavior found
3131     // with sequences of i1. That is, an array of i1 will be truncated in size
3132     // and be too small. For example, a buffer of type fir.array<7xi1> will have
3133     // 0 size.
3134     mlir::Type i64Ty = builder->getIntegerType(64);
3135     mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder);
3136     mlir::Type buffTy = ty.getType(1);
3137     mlir::Type shTy = ty.getType(2);
3138     mlir::Location loc = toLocation();
3139     mlir::Value hdr = builder->createTemporary(loc, ty);
3140     // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect?
3141     // For now, explicitly set lazy ragged header to all zeros.
3142     // auto nilTup = builder->createNullConstant(loc, ty);
3143     // builder->create<fir::StoreOp>(loc, nilTup, hdr);
3144     mlir::Type i32Ty = builder->getIntegerType(32);
3145     mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0);
3146     mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0);
3147     mlir::Value flags = builder->create<fir::CoordinateOp>(
3148         loc, builder->getRefType(i64Ty), hdr, zero);
3149     builder->create<fir::StoreOp>(loc, zero64, flags);
3150     mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1);
3151     mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy);
3152     mlir::Value var = builder->create<fir::CoordinateOp>(
3153         loc, builder->getRefType(buffTy), hdr, one);
3154     builder->create<fir::StoreOp>(loc, nullPtr1, var);
3155     mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2);
3156     mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy);
3157     mlir::Value shape = builder->create<fir::CoordinateOp>(
3158         loc, builder->getRefType(shTy), hdr, two);
3159     builder->create<fir::StoreOp>(loc, nullPtr2, shape);
3160     implicitIterSpace.addMaskVariable(exp, var, shape, hdr);
3161     explicitIterSpace.outermostContext().attachCleanup(
3162         [builder = this->builder, hdr, loc]() {
3163           fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr);
3164         });
3165   }
3166 
3167   void createRuntimeTypeInfoGlobals() {}
3168 
3169   //===--------------------------------------------------------------------===//
3170 
3171   Fortran::lower::LoweringBridge &bridge;
3172   Fortran::evaluate::FoldingContext foldingContext;
3173   fir::FirOpBuilder *builder = nullptr;
3174   Fortran::lower::pft::Evaluation *evalPtr = nullptr;
3175   Fortran::lower::SymMap localSymbols;
3176   Fortran::parser::CharBlock currentPosition;
3177   RuntimeTypeInfoConverter runtimeTypeInfoConverter;
3178 
3179   /// WHERE statement/construct mask expression stack.
3180   Fortran::lower::ImplicitIterSpace implicitIterSpace;
3181 
3182   /// FORALL context
3183   Fortran::lower::ExplicitIterSpace explicitIterSpace;
3184 
3185   /// Tuple of host assoicated variables.
3186   mlir::Value hostAssocTuple;
3187 };
3188 
3189 } // namespace
3190 
3191 Fortran::evaluate::FoldingContext
3192 Fortran::lower::LoweringBridge::createFoldingContext() const {
3193   return {getDefaultKinds(), getIntrinsicTable(), getTargetCharacteristics()};
3194 }
3195 
3196 void Fortran::lower::LoweringBridge::lower(
3197     const Fortran::parser::Program &prg,
3198     const Fortran::semantics::SemanticsContext &semanticsContext) {
3199   std::unique_ptr<Fortran::lower::pft::Program> pft =
3200       Fortran::lower::createPFT(prg, semanticsContext);
3201   if (dumpBeforeFir)
3202     Fortran::lower::dumpPFT(llvm::errs(), *pft);
3203   FirConverter converter{*this};
3204   converter.run(*pft);
3205 }
3206 
3207 void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) {
3208   mlir::OwningOpRef<mlir::ModuleOp> owningRef =
3209       mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context);
3210   module.reset(new mlir::ModuleOp(owningRef.get().getOperation()));
3211   owningRef.release();
3212 }
3213 
3214 Fortran::lower::LoweringBridge::LoweringBridge(
3215     mlir::MLIRContext &context,
3216     const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds,
3217     const Fortran::evaluate::IntrinsicProcTable &intrinsics,
3218     const Fortran::evaluate::TargetCharacteristics &targetCharacteristics,
3219     const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple,
3220     fir::KindMapping &kindMap)
3221     : defaultKinds{defaultKinds}, intrinsics{intrinsics},
3222       targetCharacteristics{targetCharacteristics}, cooked{&cooked},
3223       context{context}, kindMap{kindMap} {
3224   // Register the diagnostic handler.
3225   context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) {
3226     llvm::raw_ostream &os = llvm::errs();
3227     switch (diag.getSeverity()) {
3228     case mlir::DiagnosticSeverity::Error:
3229       os << "error: ";
3230       break;
3231     case mlir::DiagnosticSeverity::Remark:
3232       os << "info: ";
3233       break;
3234     case mlir::DiagnosticSeverity::Warning:
3235       os << "warning: ";
3236       break;
3237     default:
3238       break;
3239     }
3240     if (!diag.getLocation().isa<mlir::UnknownLoc>())
3241       os << diag.getLocation() << ": ";
3242     os << diag << '\n';
3243     os.flush();
3244     return mlir::success();
3245   });
3246 
3247   // Create the module and attach the attributes.
3248   module = std::make_unique<mlir::ModuleOp>(
3249       mlir::ModuleOp::create(mlir::UnknownLoc::get(&context)));
3250   assert(module.get() && "module was not created");
3251   fir::setTargetTriple(*module.get(), triple);
3252   fir::setKindMapping(*module.get(), kindMap);
3253 }
3254