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