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