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