xref: /llvm-project/flang/lib/Lower/PFTBuilder.cpp (revision 3aba9264b38c1aa3a991065305c0a04988432692)
1 //===-- PFTBuilder.cpp ----------------------------------------------------===//
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 #include "flang/Lower/PFTBuilder.h"
10 #include "flang/Lower/IntervalSet.h"
11 #include "flang/Lower/Support/Utils.h"
12 #include "flang/Parser/dump-parse-tree.h"
13 #include "flang/Parser/parse-tree-visitor.h"
14 #include "flang/Semantics/semantics.h"
15 #include "flang/Semantics/tools.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/IntervalMap.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 
21 #define DEBUG_TYPE "flang-pft"
22 
23 static llvm::cl::opt<bool> clDisableStructuredFir(
24     "no-structured-fir", llvm::cl::desc("disable generation of structured FIR"),
25     llvm::cl::init(false), llvm::cl::Hidden);
26 
27 using namespace Fortran;
28 
29 namespace {
30 /// Helpers to unveil parser node inside Fortran::parser::Statement<>,
31 /// Fortran::parser::UnlabeledStatement, and Fortran::common::Indirection<>
32 template <typename A>
33 struct RemoveIndirectionHelper {
34   using Type = A;
35 };
36 template <typename A>
37 struct RemoveIndirectionHelper<common::Indirection<A>> {
38   using Type = A;
39 };
40 
41 template <typename A>
42 struct UnwrapStmt {
43   static constexpr bool isStmt{false};
44 };
45 template <typename A>
46 struct UnwrapStmt<parser::Statement<A>> {
47   static constexpr bool isStmt{true};
48   using Type = typename RemoveIndirectionHelper<A>::Type;
49   constexpr UnwrapStmt(const parser::Statement<A> &a)
50       : unwrapped{removeIndirection(a.statement)}, position{a.source},
51         label{a.label} {}
52   const Type &unwrapped;
53   parser::CharBlock position;
54   std::optional<parser::Label> label;
55 };
56 template <typename A>
57 struct UnwrapStmt<parser::UnlabeledStatement<A>> {
58   static constexpr bool isStmt{true};
59   using Type = typename RemoveIndirectionHelper<A>::Type;
60   constexpr UnwrapStmt(const parser::UnlabeledStatement<A> &a)
61       : unwrapped{removeIndirection(a.statement)}, position{a.source} {}
62   const Type &unwrapped;
63   parser::CharBlock position;
64   std::optional<parser::Label> label;
65 };
66 
67 #ifndef NDEBUG
68 void dumpScope(const semantics::Scope *scope, int depth = -1);
69 #endif
70 
71 /// The instantiation of a parse tree visitor (Pre and Post) is extremely
72 /// expensive in terms of compile and link time. So one goal here is to
73 /// limit the bridge to one such instantiation.
74 class PFTBuilder {
75 public:
76   PFTBuilder(const semantics::SemanticsContext &semanticsContext)
77       : pgm{std::make_unique<lower::pft::Program>(
78             semanticsContext.GetCommonBlocks())},
79         semanticsContext{semanticsContext} {
80     lower::pft::PftNode pftRoot{*pgm.get()};
81     pftParentStack.push_back(pftRoot);
82   }
83 
84   /// Get the result
85   std::unique_ptr<lower::pft::Program> result() { return std::move(pgm); }
86 
87   template <typename A>
88   constexpr bool Pre(const A &a) {
89     if constexpr (lower::pft::isFunctionLike<A>) {
90       return enterFunction(a, semanticsContext);
91     } else if constexpr (lower::pft::isConstruct<A> ||
92                          lower::pft::isDirective<A>) {
93       return enterConstructOrDirective(a);
94     } else if constexpr (UnwrapStmt<A>::isStmt) {
95       using T = typename UnwrapStmt<A>::Type;
96       // Node "a" being visited has one of the following types:
97       // Statement<T>, Statement<Indirection<T>>, UnlabeledStatement<T>,
98       // or UnlabeledStatement<Indirection<T>>
99       auto stmt{UnwrapStmt<A>(a)};
100       if constexpr (lower::pft::isConstructStmt<T> ||
101                     lower::pft::isOtherStmt<T>) {
102         addEvaluation(lower::pft::Evaluation{
103             stmt.unwrapped, pftParentStack.back(), stmt.position, stmt.label});
104         return false;
105       } else if constexpr (std::is_same_v<T, parser::ActionStmt>) {
106         return std::visit(
107             common::visitors{
108                 [&](const common::Indirection<parser::CallStmt> &x) {
109                   addEvaluation(lower::pft::Evaluation{
110                       removeIndirection(x), pftParentStack.back(),
111                       stmt.position, stmt.label});
112                   checkForFPEnvironmentCalls(x.value());
113                   return true;
114                 },
115                 [&](const common::Indirection<parser::IfStmt> &x) {
116                   convertIfStmt(x.value(), stmt.position, stmt.label);
117                   return false;
118                 },
119                 [&](const auto &x) {
120                   addEvaluation(lower::pft::Evaluation{
121                       removeIndirection(x), pftParentStack.back(),
122                       stmt.position, stmt.label});
123                   return true;
124                 },
125             },
126             stmt.unwrapped.u);
127       }
128     }
129     return true;
130   }
131 
132   /// Check for calls that could modify the floating point environment.
133   /// See F18 Clauses
134   ///  - 17.1p3 (Overview of IEEE arithmetic support)
135   ///  - 17.3p3 (The exceptions)
136   ///  - 17.4p5 (The rounding modes)
137   ///  - 17.6p1 (Halting)
138   void checkForFPEnvironmentCalls(const parser::CallStmt &callStmt) {
139     const auto *callName = std::get_if<parser::Name>(
140         &std::get<parser::ProcedureDesignator>(callStmt.call.t).u);
141     if (!callName)
142       return;
143     const Fortran::semantics::Symbol &procSym = callName->symbol->GetUltimate();
144     if (!procSym.owner().IsModule())
145       return;
146     const Fortran::semantics::Symbol &modSym = *procSym.owner().symbol();
147     if (!modSym.attrs().test(Fortran::semantics::Attr::INTRINSIC))
148       return;
149     // Modules IEEE_FEATURES, IEEE_EXCEPTIONS, and IEEE_ARITHMETIC get common
150     // declarations from several __fortran_... support module files.
151     llvm::StringRef modName = toStringRef(modSym.name());
152     if (!modName.startswith("ieee_") && !modName.startswith("__fortran_"))
153       return;
154     llvm::StringRef procName = toStringRef(procSym.name());
155     if (!procName.startswith("ieee_"))
156       return;
157     lower::pft::FunctionLikeUnit *proc =
158         evaluationListStack.back()->back().getOwningProcedure();
159     proc->hasIeeeAccess = true;
160     if (!procName.startswith("ieee_set_"))
161       return;
162     if (procName.startswith("ieee_set_modes_") ||
163         procName.startswith("ieee_set_status_"))
164       proc->mayModifyHaltingMode = proc->mayModifyRoundingMode = true;
165     else if (procName.startswith("ieee_set_halting_mode_"))
166       proc->mayModifyHaltingMode = true;
167     else if (procName.startswith("ieee_set_rounding_mode_"))
168       proc->mayModifyRoundingMode = true;
169   }
170 
171   /// Convert an IfStmt into an IfConstruct, retaining the IfStmt as the
172   /// first statement of the construct.
173   void convertIfStmt(const parser::IfStmt &ifStmt, parser::CharBlock position,
174                      std::optional<parser::Label> label) {
175     // Generate a skeleton IfConstruct parse node. Its components are never
176     // referenced. The actual components are available via the IfConstruct
177     // evaluation's nested evaluationList, with the ifStmt in the position of
178     // the otherwise normal IfThenStmt. Caution: All other PFT nodes reference
179     // front end generated parse nodes; this is an exceptional case.
180     static const auto ifConstruct = parser::IfConstruct{
181         parser::Statement<parser::IfThenStmt>{
182             std::nullopt,
183             parser::IfThenStmt{
184                 std::optional<parser::Name>{},
185                 parser::ScalarLogicalExpr{parser::LogicalExpr{parser::Expr{
186                     parser::LiteralConstant{parser::LogicalLiteralConstant{
187                         false, std::optional<parser::KindParam>{}}}}}}}},
188         parser::Block{}, std::list<parser::IfConstruct::ElseIfBlock>{},
189         std::optional<parser::IfConstruct::ElseBlock>{},
190         parser::Statement<parser::EndIfStmt>{std::nullopt,
191                                              parser::EndIfStmt{std::nullopt}}};
192     enterConstructOrDirective(ifConstruct);
193     addEvaluation(
194         lower::pft::Evaluation{ifStmt, pftParentStack.back(), position, label});
195     Pre(std::get<parser::UnlabeledStatement<parser::ActionStmt>>(ifStmt.t));
196     static const auto endIfStmt = parser::EndIfStmt{std::nullopt};
197     addEvaluation(
198         lower::pft::Evaluation{endIfStmt, pftParentStack.back(), {}, {}});
199     exitConstructOrDirective();
200   }
201 
202   template <typename A>
203   constexpr void Post(const A &) {
204     if constexpr (lower::pft::isFunctionLike<A>) {
205       exitFunction();
206     } else if constexpr (lower::pft::isConstruct<A> ||
207                          lower::pft::isDirective<A>) {
208       exitConstructOrDirective();
209     }
210   }
211 
212   // Module like
213   bool Pre(const parser::Module &node) { return enterModule(node); }
214   bool Pre(const parser::Submodule &node) { return enterModule(node); }
215 
216   void Post(const parser::Module &) { exitModule(); }
217   void Post(const parser::Submodule &) { exitModule(); }
218 
219   // Block data
220   bool Pre(const parser::BlockData &node) {
221     addUnit(lower::pft::BlockDataUnit{node, pftParentStack.back(),
222                                       semanticsContext});
223     return false;
224   }
225 
226   // Get rid of production wrapper
227   bool Pre(const parser::Statement<parser::ForallAssignmentStmt> &statement) {
228     addEvaluation(std::visit(
229         [&](const auto &x) {
230           return lower::pft::Evaluation{x, pftParentStack.back(),
231                                         statement.source, statement.label};
232         },
233         statement.statement.u));
234     return false;
235   }
236   bool Pre(const parser::WhereBodyConstruct &whereBody) {
237     return std::visit(
238         common::visitors{
239             [&](const parser::Statement<parser::AssignmentStmt> &stmt) {
240               // Not caught as other AssignmentStmt because it is not
241               // wrapped in a parser::ActionStmt.
242               addEvaluation(lower::pft::Evaluation{stmt.statement,
243                                                    pftParentStack.back(),
244                                                    stmt.source, stmt.label});
245               return false;
246             },
247             [&](const auto &) { return true; },
248         },
249         whereBody.u);
250   }
251 
252   // CompilerDirective have special handling in case they are top level
253   // directives (i.e. they do not belong to a ProgramUnit).
254   bool Pre(const parser::CompilerDirective &directive) {
255     assert(pftParentStack.size() > 0 &&
256            "At least the Program must be a parent");
257     if (pftParentStack.back().isA<lower::pft::Program>()) {
258       addUnit(
259           lower::pft::CompilerDirectiveUnit(directive, pftParentStack.back()));
260       return false;
261     }
262     return enterConstructOrDirective(directive);
263   }
264 
265   bool Pre(const parser::OpenACCRoutineConstruct &directive) {
266     assert(pftParentStack.size() > 0 &&
267            "At least the Program must be a parent");
268     if (pftParentStack.back().isA<lower::pft::Program>()) {
269       addUnit(
270           lower::pft::OpenACCDirectiveUnit(directive, pftParentStack.back()));
271       return false;
272     }
273     return enterConstructOrDirective(directive);
274   }
275 
276 private:
277   /// Initialize a new module-like unit and make it the builder's focus.
278   template <typename A>
279   bool enterModule(const A &mod) {
280     Fortran::lower::pft::ModuleLikeUnit &unit =
281         addUnit(lower::pft::ModuleLikeUnit{mod, pftParentStack.back()});
282     functionList = &unit.nestedFunctions;
283     pushEvaluationList(&unit.evaluationList);
284     pftParentStack.emplace_back(unit);
285     LLVM_DEBUG(dumpScope(&unit.getScope()));
286     return true;
287   }
288 
289   void exitModule() {
290     if (!evaluationListStack.empty())
291       popEvaluationList();
292     pftParentStack.pop_back();
293     resetFunctionState();
294   }
295 
296   /// Add the end statement Evaluation of a sub/program to the PFT.
297   /// There may be intervening internal subprogram definitions between
298   /// prior statements and this end statement.
299   void endFunctionBody() {
300     if (evaluationListStack.empty())
301       return;
302     auto evaluationList = evaluationListStack.back();
303     if (evaluationList->empty() || !evaluationList->back().isEndStmt()) {
304       const auto &endStmt =
305           pftParentStack.back().get<lower::pft::FunctionLikeUnit>().endStmt;
306       endStmt.visit(common::visitors{
307           [&](const parser::Statement<parser::EndProgramStmt> &s) {
308             addEvaluation(lower::pft::Evaluation{
309                 s.statement, pftParentStack.back(), s.source, s.label});
310           },
311           [&](const parser::Statement<parser::EndFunctionStmt> &s) {
312             addEvaluation(lower::pft::Evaluation{
313                 s.statement, pftParentStack.back(), s.source, s.label});
314           },
315           [&](const parser::Statement<parser::EndSubroutineStmt> &s) {
316             addEvaluation(lower::pft::Evaluation{
317                 s.statement, pftParentStack.back(), s.source, s.label});
318           },
319           [&](const parser::Statement<parser::EndMpSubprogramStmt> &s) {
320             addEvaluation(lower::pft::Evaluation{
321                 s.statement, pftParentStack.back(), s.source, s.label});
322           },
323           [&](const auto &s) {
324             llvm::report_fatal_error("missing end statement or unexpected "
325                                      "begin statement reference");
326           },
327       });
328     }
329     lastLexicalEvaluation = nullptr;
330   }
331 
332   /// Pop the ModuleLikeUnit evaluationList when entering the first module
333   /// procedure.
334   void cleanModuleEvaluationList() {
335     if (evaluationListStack.empty())
336       return;
337     if (pftParentStack.back().isA<lower::pft::ModuleLikeUnit>())
338       popEvaluationList();
339   }
340 
341   /// Initialize a new function-like unit and make it the builder's focus.
342   template <typename A>
343   bool enterFunction(const A &func,
344                      const semantics::SemanticsContext &semanticsContext) {
345     cleanModuleEvaluationList();
346     endFunctionBody(); // enclosing host subprogram body, if any
347     Fortran::lower::pft::FunctionLikeUnit &unit =
348         addFunction(lower::pft::FunctionLikeUnit{func, pftParentStack.back(),
349                                                  semanticsContext});
350     labelEvaluationMap = &unit.labelEvaluationMap;
351     assignSymbolLabelMap = &unit.assignSymbolLabelMap;
352     functionList = &unit.nestedFunctions;
353     pushEvaluationList(&unit.evaluationList);
354     pftParentStack.emplace_back(unit);
355     LLVM_DEBUG(dumpScope(&unit.getScope()));
356     return true;
357   }
358 
359   void exitFunction() {
360     rewriteIfGotos();
361     endFunctionBody();
362     analyzeBranches(nullptr, *evaluationListStack.back()); // add branch links
363     processEntryPoints();
364     popEvaluationList();
365     labelEvaluationMap = nullptr;
366     assignSymbolLabelMap = nullptr;
367     pftParentStack.pop_back();
368     resetFunctionState();
369   }
370 
371   /// Initialize a new construct or directive and make it the builder's focus.
372   template <typename A>
373   bool enterConstructOrDirective(const A &constructOrDirective) {
374     Fortran::lower::pft::Evaluation &eval = addEvaluation(
375         lower::pft::Evaluation{constructOrDirective, pftParentStack.back()});
376     eval.evaluationList.reset(new lower::pft::EvaluationList);
377     pushEvaluationList(eval.evaluationList.get());
378     pftParentStack.emplace_back(eval);
379     constructAndDirectiveStack.emplace_back(&eval);
380     return true;
381   }
382 
383   void exitConstructOrDirective() {
384     auto isOpenMPLoopConstruct = [](Fortran::lower::pft::Evaluation *eval) {
385       if (const auto *ompConstruct = eval->getIf<parser::OpenMPConstruct>())
386         if (std::holds_alternative<parser::OpenMPLoopConstruct>(
387                 ompConstruct->u))
388           return true;
389       return false;
390     };
391 
392     rewriteIfGotos();
393     auto *eval = constructAndDirectiveStack.back();
394     if (eval->isExecutableDirective() && !isOpenMPLoopConstruct(eval)) {
395       // A construct at the end of an (unstructured) OpenACC or OpenMP
396       // construct region must have an exit target inside the region.
397       // This is not applicable to the OpenMP loop construct since the
398       // end of the loop is an available target inside the region.
399       Fortran::lower::pft::EvaluationList &evaluationList =
400           *eval->evaluationList;
401       if (!evaluationList.empty() && evaluationList.back().isConstruct()) {
402         static const parser::ContinueStmt exitTarget{};
403         addEvaluation(
404             lower::pft::Evaluation{exitTarget, pftParentStack.back(), {}, {}});
405       }
406     }
407     popEvaluationList();
408     pftParentStack.pop_back();
409     constructAndDirectiveStack.pop_back();
410   }
411 
412   /// Reset function state to that of an enclosing host function.
413   void resetFunctionState() {
414     if (!pftParentStack.empty()) {
415       pftParentStack.back().visit(common::visitors{
416           [&](lower::pft::FunctionLikeUnit &p) {
417             functionList = &p.nestedFunctions;
418             labelEvaluationMap = &p.labelEvaluationMap;
419             assignSymbolLabelMap = &p.assignSymbolLabelMap;
420           },
421           [&](lower::pft::ModuleLikeUnit &p) {
422             functionList = &p.nestedFunctions;
423           },
424           [&](auto &) { functionList = nullptr; },
425       });
426     }
427   }
428 
429   template <typename A>
430   A &addUnit(A &&unit) {
431     pgm->getUnits().emplace_back(std::move(unit));
432     return std::get<A>(pgm->getUnits().back());
433   }
434 
435   template <typename A>
436   A &addFunction(A &&func) {
437     if (functionList) {
438       functionList->emplace_back(std::move(func));
439       return functionList->back();
440     }
441     return addUnit(std::move(func));
442   }
443 
444   // ActionStmt has a couple of non-conforming cases, explicitly handled here.
445   // The other cases use an Indirection, which are discarded in the PFT.
446   lower::pft::Evaluation
447   makeEvaluationAction(const parser::ActionStmt &statement,
448                        parser::CharBlock position,
449                        std::optional<parser::Label> label) {
450     return std::visit(
451         common::visitors{
452             [&](const auto &x) {
453               return lower::pft::Evaluation{
454                   removeIndirection(x), pftParentStack.back(), position, label};
455             },
456         },
457         statement.u);
458   }
459 
460   /// Append an Evaluation to the end of the current list.
461   lower::pft::Evaluation &addEvaluation(lower::pft::Evaluation &&eval) {
462     assert(functionList && "not in a function");
463     assert(!evaluationListStack.empty() && "empty evaluation list stack");
464     if (!constructAndDirectiveStack.empty())
465       eval.parentConstruct = constructAndDirectiveStack.back();
466     lower::pft::FunctionLikeUnit *owningProcedure = eval.getOwningProcedure();
467     evaluationListStack.back()->emplace_back(std::move(eval));
468     lower::pft::Evaluation *p = &evaluationListStack.back()->back();
469     if (p->isActionStmt() || p->isConstructStmt() || p->isEndStmt() ||
470         p->isExecutableDirective()) {
471       if (lastLexicalEvaluation) {
472         lastLexicalEvaluation->lexicalSuccessor = p;
473         p->printIndex = lastLexicalEvaluation->printIndex + 1;
474       } else {
475         p->printIndex = 1;
476       }
477       lastLexicalEvaluation = p;
478       if (owningProcedure) {
479         auto &entryPointList = owningProcedure->entryPointList;
480         for (std::size_t entryIndex = entryPointList.size() - 1;
481              entryIndex && !entryPointList[entryIndex].second->lexicalSuccessor;
482              --entryIndex)
483           // Link to the entry's first executable statement.
484           entryPointList[entryIndex].second->lexicalSuccessor = p;
485       }
486     } else if (const auto *entryStmt = p->getIf<parser::EntryStmt>()) {
487       const semantics::Symbol *sym =
488           std::get<parser::Name>(entryStmt->t).symbol;
489       if (auto *details = sym->detailsIf<semantics::GenericDetails>())
490         sym = details->specific();
491       assert(sym->has<semantics::SubprogramDetails>() &&
492              "entry must be a subprogram");
493       owningProcedure->entryPointList.push_back(std::pair{sym, p});
494     }
495     if (p->label.has_value())
496       labelEvaluationMap->try_emplace(*p->label, p);
497     return evaluationListStack.back()->back();
498   }
499 
500   /// push a new list on the stack of Evaluation lists
501   void pushEvaluationList(lower::pft::EvaluationList *evaluationList) {
502     assert(functionList && "not in a function");
503     assert(evaluationList && evaluationList->empty() &&
504            "evaluation list isn't correct");
505     evaluationListStack.emplace_back(evaluationList);
506   }
507 
508   /// pop the current list and return to the last Evaluation list
509   void popEvaluationList() {
510     assert(functionList && "not in a function");
511     evaluationListStack.pop_back();
512   }
513 
514   /// Rewrite IfConstructs containing a GotoStmt or CycleStmt to eliminate an
515   /// unstructured branch and a trivial basic block. The pre-branch-analysis
516   /// code:
517   ///
518   ///       <<IfConstruct>>
519   ///         1 If[Then]Stmt: if(cond) goto L
520   ///         2 GotoStmt: goto L
521   ///         3 EndIfStmt
522   ///       <<End IfConstruct>>
523   ///       4 Statement: ...
524   ///       5 Statement: ...
525   ///       6 Statement: L ...
526   ///
527   /// becomes:
528   ///
529   ///       <<IfConstruct>>
530   ///         1 If[Then]Stmt [negate]: if(cond) goto L
531   ///         4 Statement: ...
532   ///         5 Statement: ...
533   ///         3 EndIfStmt
534   ///       <<End IfConstruct>>
535   ///       6 Statement: L ...
536   ///
537   /// The If[Then]Stmt condition is implicitly negated. It is not modified
538   /// in the PFT. It must be negated when generating FIR. The GotoStmt or
539   /// CycleStmt is deleted.
540   ///
541   /// The transformation is only valid for forward branch targets at the same
542   /// construct nesting level as the IfConstruct. The result must not violate
543   /// construct nesting requirements or contain an EntryStmt. The result
544   /// is subject to normal un/structured code classification analysis. The
545   /// result is allowed to violate the F18 Clause 11.1.2.1 prohibition on
546   /// transfer of control into the interior of a construct block, as that does
547   /// not compromise correct code generation. When two transformation
548   /// candidates overlap, at least one must be disallowed. In such cases,
549   /// the current heuristic favors simple code generation, which happens to
550   /// favor later candidates over earlier candidates. That choice is probably
551   /// not significant, but could be changed.
552   ///
553   void rewriteIfGotos() {
554     auto &evaluationList = *evaluationListStack.back();
555     if (!evaluationList.size())
556       return;
557     struct T {
558       lower::pft::EvaluationList::iterator ifConstructIt;
559       parser::Label ifTargetLabel;
560       bool isCycleStmt = false;
561     };
562     llvm::SmallVector<T> ifCandidateStack;
563     const auto *doStmt =
564         evaluationList.begin()->getIf<parser::NonLabelDoStmt>();
565     std::string doName = doStmt ? getConstructName(*doStmt) : std::string{};
566     for (auto it = evaluationList.begin(), end = evaluationList.end();
567          it != end; ++it) {
568       auto &eval = *it;
569       if (eval.isA<parser::EntryStmt>() || eval.isIntermediateConstructStmt()) {
570         ifCandidateStack.clear();
571         continue;
572       }
573       auto firstStmt = [](lower::pft::Evaluation *e) {
574         return e->isConstruct() ? &*e->evaluationList->begin() : e;
575       };
576       const Fortran::lower::pft::Evaluation &targetEval = *firstStmt(&eval);
577       bool targetEvalIsEndDoStmt = targetEval.isA<parser::EndDoStmt>();
578       auto branchTargetMatch = [&]() {
579         if (const parser::Label targetLabel =
580                 ifCandidateStack.back().ifTargetLabel)
581           if (targetEval.label && targetLabel == *targetEval.label)
582             return true; // goto target match
583         if (targetEvalIsEndDoStmt && ifCandidateStack.back().isCycleStmt)
584           return true; // cycle target match
585         return false;
586       };
587       if (targetEval.label || targetEvalIsEndDoStmt) {
588         while (!ifCandidateStack.empty() && branchTargetMatch()) {
589           lower::pft::EvaluationList::iterator ifConstructIt =
590               ifCandidateStack.back().ifConstructIt;
591           lower::pft::EvaluationList::iterator successorIt =
592               std::next(ifConstructIt);
593           if (successorIt != it) {
594             Fortran::lower::pft::EvaluationList &ifBodyList =
595                 *ifConstructIt->evaluationList;
596             lower::pft::EvaluationList::iterator branchStmtIt =
597                 std::next(ifBodyList.begin());
598             assert((branchStmtIt->isA<parser::GotoStmt>() ||
599                     branchStmtIt->isA<parser::CycleStmt>()) &&
600                    "expected goto or cycle statement");
601             ifBodyList.erase(branchStmtIt);
602             lower::pft::Evaluation &ifStmt = *ifBodyList.begin();
603             ifStmt.negateCondition = true;
604             ifStmt.lexicalSuccessor = firstStmt(&*successorIt);
605             lower::pft::EvaluationList::iterator endIfStmtIt =
606                 std::prev(ifBodyList.end());
607             std::prev(it)->lexicalSuccessor = &*endIfStmtIt;
608             endIfStmtIt->lexicalSuccessor = firstStmt(&*it);
609             ifBodyList.splice(endIfStmtIt, evaluationList, successorIt, it);
610             for (; successorIt != endIfStmtIt; ++successorIt)
611               successorIt->parentConstruct = &*ifConstructIt;
612           }
613           ifCandidateStack.pop_back();
614         }
615       }
616       if (eval.isA<parser::IfConstruct>() && eval.evaluationList->size() == 3) {
617         const auto bodyEval = std::next(eval.evaluationList->begin());
618         if (const auto *gotoStmt = bodyEval->getIf<parser::GotoStmt>()) {
619           ifCandidateStack.push_back({it, gotoStmt->v});
620         } else if (doStmt) {
621           if (const auto *cycleStmt = bodyEval->getIf<parser::CycleStmt>()) {
622             std::string cycleName = getConstructName(*cycleStmt);
623             if (cycleName.empty() || cycleName == doName)
624               // This candidate will match doStmt's EndDoStmt.
625               ifCandidateStack.push_back({it, {}, true});
626           }
627         }
628       }
629     }
630   }
631 
632   /// Mark IO statement ERR, EOR, and END specifier branch targets.
633   /// Mark an IO statement with an assigned format as unstructured.
634   template <typename A>
635   void analyzeIoBranches(lower::pft::Evaluation &eval, const A &stmt) {
636     auto analyzeFormatSpec = [&](const parser::Format &format) {
637       if (const auto *expr = std::get_if<parser::Expr>(&format.u)) {
638         if (semantics::ExprHasTypeCategory(*semantics::GetExpr(*expr),
639                                            common::TypeCategory::Integer))
640           eval.isUnstructured = true;
641       }
642     };
643     auto analyzeSpecs{[&](const auto &specList) {
644       for (const auto &spec : specList) {
645         std::visit(
646             Fortran::common::visitors{
647                 [&](const Fortran::parser::Format &format) {
648                   analyzeFormatSpec(format);
649                 },
650                 [&](const auto &label) {
651                   using LabelNodes =
652                       std::tuple<parser::ErrLabel, parser::EorLabel,
653                                  parser::EndLabel>;
654                   if constexpr (common::HasMember<decltype(label), LabelNodes>)
655                     markBranchTarget(eval, label.v);
656                 }},
657             spec.u);
658       }
659     }};
660 
661     using OtherIOStmts =
662         std::tuple<parser::BackspaceStmt, parser::CloseStmt,
663                    parser::EndfileStmt, parser::FlushStmt, parser::OpenStmt,
664                    parser::RewindStmt, parser::WaitStmt>;
665 
666     if constexpr (std::is_same_v<A, parser::ReadStmt> ||
667                   std::is_same_v<A, parser::WriteStmt>) {
668       if (stmt.format)
669         analyzeFormatSpec(*stmt.format);
670       analyzeSpecs(stmt.controls);
671     } else if constexpr (std::is_same_v<A, parser::PrintStmt>) {
672       analyzeFormatSpec(std::get<parser::Format>(stmt.t));
673     } else if constexpr (std::is_same_v<A, parser::InquireStmt>) {
674       if (const auto *specList =
675               std::get_if<std::list<parser::InquireSpec>>(&stmt.u))
676         analyzeSpecs(*specList);
677     } else if constexpr (common::HasMember<A, OtherIOStmts>) {
678       analyzeSpecs(stmt.v);
679     } else {
680       // Always crash if this is instantiated
681       static_assert(!std::is_same_v<A, parser::ReadStmt>,
682                     "Unexpected IO statement");
683     }
684   }
685 
686   /// Set the exit of a construct, possibly from multiple enclosing constructs.
687   void setConstructExit(lower::pft::Evaluation &eval) {
688     eval.constructExit = &eval.evaluationList->back().nonNopSuccessor();
689   }
690 
691   /// Mark the target of a branch as a new block.
692   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
693                         lower::pft::Evaluation &targetEvaluation) {
694     sourceEvaluation.isUnstructured = true;
695     if (!sourceEvaluation.controlSuccessor)
696       sourceEvaluation.controlSuccessor = &targetEvaluation;
697     targetEvaluation.isNewBlock = true;
698     // If this is a branch into the body of a construct (usually illegal,
699     // but allowed in some legacy cases), then the targetEvaluation and its
700     // ancestors must be marked as unstructured.
701     lower::pft::Evaluation *sourceConstruct = sourceEvaluation.parentConstruct;
702     lower::pft::Evaluation *targetConstruct = targetEvaluation.parentConstruct;
703     if (targetConstruct &&
704         &targetConstruct->getFirstNestedEvaluation() == &targetEvaluation)
705       // A branch to an initial constructStmt is a branch to the construct.
706       targetConstruct = targetConstruct->parentConstruct;
707     if (targetConstruct) {
708       while (sourceConstruct && sourceConstruct != targetConstruct)
709         sourceConstruct = sourceConstruct->parentConstruct;
710       if (sourceConstruct != targetConstruct) // branch into a construct body
711         for (lower::pft::Evaluation *eval = &targetEvaluation; eval;
712              eval = eval->parentConstruct) {
713           eval->isUnstructured = true;
714           // If the branch is a backward branch into an already analyzed
715           // DO or IF construct, mark the construct exit as a new block.
716           // For a forward branch, the isUnstructured flag will cause this
717           // to be done when the construct is analyzed.
718           if (eval->constructExit && (eval->isA<parser::DoConstruct>() ||
719                                       eval->isA<parser::IfConstruct>()))
720             eval->constructExit->isNewBlock = true;
721         }
722     }
723   }
724   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
725                         parser::Label label) {
726     assert(label && "missing branch target label");
727     lower::pft::Evaluation *targetEvaluation{
728         labelEvaluationMap->find(label)->second};
729     assert(targetEvaluation && "missing branch target evaluation");
730     markBranchTarget(sourceEvaluation, *targetEvaluation);
731   }
732 
733   /// Mark the successor of an Evaluation as a new block.
734   void markSuccessorAsNewBlock(lower::pft::Evaluation &eval) {
735     eval.nonNopSuccessor().isNewBlock = true;
736   }
737 
738   template <typename A>
739   inline std::string getConstructName(const A &stmt) {
740     using MaybeConstructNameWrapper =
741         std::tuple<parser::BlockStmt, parser::CycleStmt, parser::ElseStmt,
742                    parser::ElsewhereStmt, parser::EndAssociateStmt,
743                    parser::EndBlockStmt, parser::EndCriticalStmt,
744                    parser::EndDoStmt, parser::EndForallStmt, parser::EndIfStmt,
745                    parser::EndSelectStmt, parser::EndWhereStmt,
746                    parser::ExitStmt>;
747     if constexpr (common::HasMember<A, MaybeConstructNameWrapper>) {
748       if (stmt.v)
749         return stmt.v->ToString();
750     }
751 
752     using MaybeConstructNameInTuple = std::tuple<
753         parser::AssociateStmt, parser::CaseStmt, parser::ChangeTeamStmt,
754         parser::CriticalStmt, parser::ElseIfStmt, parser::EndChangeTeamStmt,
755         parser::ForallConstructStmt, parser::IfThenStmt, parser::LabelDoStmt,
756         parser::MaskedElsewhereStmt, parser::NonLabelDoStmt,
757         parser::SelectCaseStmt, parser::SelectRankCaseStmt,
758         parser::TypeGuardStmt, parser::WhereConstructStmt>;
759     if constexpr (common::HasMember<A, MaybeConstructNameInTuple>) {
760       if (auto name = std::get<std::optional<parser::Name>>(stmt.t))
761         return name->ToString();
762     }
763 
764     // These statements have multiple std::optional<parser::Name> elements.
765     if constexpr (std::is_same_v<A, parser::SelectRankStmt> ||
766                   std::is_same_v<A, parser::SelectTypeStmt>) {
767       if (auto name = std::get<0>(stmt.t))
768         return name->ToString();
769     }
770 
771     return {};
772   }
773 
774   /// \p parentConstruct can be null if this statement is at the highest
775   /// level of a program.
776   template <typename A>
777   void insertConstructName(const A &stmt,
778                            lower::pft::Evaluation *parentConstruct) {
779     std::string name = getConstructName(stmt);
780     if (!name.empty())
781       constructNameMap[name] = parentConstruct;
782   }
783 
784   /// Insert branch links for a list of Evaluations.
785   /// \p parentConstruct can be null if the evaluationList contains the
786   /// top-level statements of a program.
787   void analyzeBranches(lower::pft::Evaluation *parentConstruct,
788                        std::list<lower::pft::Evaluation> &evaluationList) {
789     lower::pft::Evaluation *lastConstructStmtEvaluation{};
790     for (auto &eval : evaluationList) {
791       eval.visit(common::visitors{
792           // Action statements (except IO statements)
793           [&](const parser::CallStmt &s) {
794             // Look for alternate return specifiers.
795             const auto &args =
796                 std::get<std::list<parser::ActualArgSpec>>(s.call.t);
797             for (const auto &arg : args) {
798               const auto &actual = std::get<parser::ActualArg>(arg.t);
799               if (const auto *altReturn =
800                       std::get_if<parser::AltReturnSpec>(&actual.u))
801                 markBranchTarget(eval, altReturn->v);
802             }
803           },
804           [&](const parser::CycleStmt &s) {
805             std::string name = getConstructName(s);
806             lower::pft::Evaluation *construct{name.empty()
807                                                   ? doConstructStack.back()
808                                                   : constructNameMap[name]};
809             assert(construct && "missing CYCLE construct");
810             markBranchTarget(eval, construct->evaluationList->back());
811           },
812           [&](const parser::ExitStmt &s) {
813             std::string name = getConstructName(s);
814             lower::pft::Evaluation *construct{name.empty()
815                                                   ? doConstructStack.back()
816                                                   : constructNameMap[name]};
817             assert(construct && "missing EXIT construct");
818             markBranchTarget(eval, *construct->constructExit);
819           },
820           [&](const parser::FailImageStmt &) {
821             eval.isUnstructured = true;
822             if (eval.lexicalSuccessor->lexicalSuccessor)
823               markSuccessorAsNewBlock(eval);
824           },
825           [&](const parser::GotoStmt &s) { markBranchTarget(eval, s.v); },
826           [&](const parser::IfStmt &) {
827             eval.lexicalSuccessor->isNewBlock = true;
828             lastConstructStmtEvaluation = &eval;
829           },
830           [&](const parser::ReturnStmt &) {
831             eval.isUnstructured = true;
832             if (eval.lexicalSuccessor->lexicalSuccessor)
833               markSuccessorAsNewBlock(eval);
834           },
835           [&](const parser::StopStmt &) {
836             eval.isUnstructured = true;
837             if (eval.lexicalSuccessor->lexicalSuccessor)
838               markSuccessorAsNewBlock(eval);
839           },
840           [&](const parser::ComputedGotoStmt &s) {
841             for (auto &label : std::get<std::list<parser::Label>>(s.t))
842               markBranchTarget(eval, label);
843           },
844           [&](const parser::ArithmeticIfStmt &s) {
845             markBranchTarget(eval, std::get<1>(s.t));
846             markBranchTarget(eval, std::get<2>(s.t));
847             markBranchTarget(eval, std::get<3>(s.t));
848           },
849           [&](const parser::AssignStmt &s) { // legacy label assignment
850             auto &label = std::get<parser::Label>(s.t);
851             const auto *sym = std::get<parser::Name>(s.t).symbol;
852             assert(sym && "missing AssignStmt symbol");
853             lower::pft::Evaluation *target{
854                 labelEvaluationMap->find(label)->second};
855             assert(target && "missing branch target evaluation");
856             if (!target->isA<parser::FormatStmt>())
857               target->isNewBlock = true;
858             auto iter = assignSymbolLabelMap->find(*sym);
859             if (iter == assignSymbolLabelMap->end()) {
860               lower::pft::LabelSet labelSet{};
861               labelSet.insert(label);
862               assignSymbolLabelMap->try_emplace(*sym, labelSet);
863             } else {
864               iter->second.insert(label);
865             }
866           },
867           [&](const parser::AssignedGotoStmt &) {
868             // Although this statement is a branch, it doesn't have any
869             // explicit control successors. So the code at the end of the
870             // loop won't mark the successor. Do that here.
871             eval.isUnstructured = true;
872             markSuccessorAsNewBlock(eval);
873           },
874 
875           // The first executable statement after an EntryStmt is a new block.
876           [&](const parser::EntryStmt &) {
877             eval.lexicalSuccessor->isNewBlock = true;
878           },
879 
880           // Construct statements
881           [&](const parser::AssociateStmt &s) {
882             insertConstructName(s, parentConstruct);
883           },
884           [&](const parser::BlockStmt &s) {
885             insertConstructName(s, parentConstruct);
886           },
887           [&](const parser::SelectCaseStmt &s) {
888             insertConstructName(s, parentConstruct);
889             lastConstructStmtEvaluation = &eval;
890           },
891           [&](const parser::CaseStmt &) {
892             eval.isNewBlock = true;
893             lastConstructStmtEvaluation->controlSuccessor = &eval;
894             lastConstructStmtEvaluation = &eval;
895           },
896           [&](const parser::EndSelectStmt &) {
897             eval.isNewBlock = true;
898             lastConstructStmtEvaluation = nullptr;
899           },
900           [&](const parser::ChangeTeamStmt &s) {
901             insertConstructName(s, parentConstruct);
902           },
903           [&](const parser::CriticalStmt &s) {
904             insertConstructName(s, parentConstruct);
905           },
906           [&](const parser::NonLabelDoStmt &s) {
907             insertConstructName(s, parentConstruct);
908             doConstructStack.push_back(parentConstruct);
909             const auto &loopControl =
910                 std::get<std::optional<parser::LoopControl>>(s.t);
911             if (!loopControl.has_value()) {
912               eval.isUnstructured = true; // infinite loop
913               return;
914             }
915             eval.nonNopSuccessor().isNewBlock = true;
916             eval.controlSuccessor = &evaluationList.back();
917             if (const auto *bounds =
918                     std::get_if<parser::LoopControl::Bounds>(&loopControl->u)) {
919               if (bounds->name.thing.symbol->GetType()->IsNumeric(
920                       common::TypeCategory::Real))
921                 eval.isUnstructured = true; // real-valued loop control
922             } else if (std::get_if<parser::ScalarLogicalExpr>(
923                            &loopControl->u)) {
924               eval.isUnstructured = true; // while loop
925             }
926           },
927           [&](const parser::EndDoStmt &) {
928             lower::pft::Evaluation &doEval = evaluationList.front();
929             eval.controlSuccessor = &doEval;
930             doConstructStack.pop_back();
931             if (parentConstruct->lowerAsStructured())
932               return;
933             // The loop is unstructured, which wasn't known for all cases when
934             // visiting the NonLabelDoStmt.
935             parentConstruct->constructExit->isNewBlock = true;
936             const auto &doStmt = *doEval.getIf<parser::NonLabelDoStmt>();
937             const auto &loopControl =
938                 std::get<std::optional<parser::LoopControl>>(doStmt.t);
939             if (!loopControl.has_value())
940               return; // infinite loop
941             if (const auto *concurrent =
942                     std::get_if<parser::LoopControl::Concurrent>(
943                         &loopControl->u)) {
944               // If there is a mask, the EndDoStmt starts a new block.
945               const auto &header =
946                   std::get<parser::ConcurrentHeader>(concurrent->t);
947               eval.isNewBlock |=
948                   std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)
949                       .has_value();
950             }
951           },
952           [&](const parser::IfThenStmt &s) {
953             insertConstructName(s, parentConstruct);
954             eval.lexicalSuccessor->isNewBlock = true;
955             lastConstructStmtEvaluation = &eval;
956           },
957           [&](const parser::ElseIfStmt &) {
958             eval.isNewBlock = true;
959             eval.lexicalSuccessor->isNewBlock = true;
960             lastConstructStmtEvaluation->controlSuccessor = &eval;
961             lastConstructStmtEvaluation = &eval;
962           },
963           [&](const parser::ElseStmt &) {
964             eval.isNewBlock = true;
965             lastConstructStmtEvaluation->controlSuccessor = &eval;
966             lastConstructStmtEvaluation = nullptr;
967           },
968           [&](const parser::EndIfStmt &) {
969             if (parentConstruct->lowerAsUnstructured())
970               parentConstruct->constructExit->isNewBlock = true;
971             if (lastConstructStmtEvaluation) {
972               lastConstructStmtEvaluation->controlSuccessor =
973                   parentConstruct->constructExit;
974               lastConstructStmtEvaluation = nullptr;
975             }
976           },
977           [&](const parser::SelectRankStmt &s) {
978             insertConstructName(s, parentConstruct);
979             lastConstructStmtEvaluation = &eval;
980           },
981           [&](const parser::SelectRankCaseStmt &) {
982             eval.isNewBlock = true;
983             lastConstructStmtEvaluation->controlSuccessor = &eval;
984             lastConstructStmtEvaluation = &eval;
985           },
986           [&](const parser::SelectTypeStmt &s) {
987             insertConstructName(s, parentConstruct);
988             lastConstructStmtEvaluation = &eval;
989           },
990           [&](const parser::TypeGuardStmt &) {
991             eval.isNewBlock = true;
992             lastConstructStmtEvaluation->controlSuccessor = &eval;
993             lastConstructStmtEvaluation = &eval;
994           },
995 
996           // Constructs - set (unstructured) construct exit targets
997           [&](const parser::AssociateConstruct &) {
998             eval.constructExit = &eval.evaluationList->back();
999           },
1000           [&](const parser::BlockConstruct &) {
1001             eval.constructExit = &eval.evaluationList->back();
1002           },
1003           [&](const parser::CaseConstruct &) {
1004             eval.constructExit = &eval.evaluationList->back();
1005             eval.isUnstructured = true;
1006           },
1007           [&](const parser::ChangeTeamConstruct &) {
1008             eval.constructExit = &eval.evaluationList->back();
1009           },
1010           [&](const parser::CriticalConstruct &) {
1011             eval.constructExit = &eval.evaluationList->back();
1012           },
1013           [&](const parser::DoConstruct &) { setConstructExit(eval); },
1014           [&](const parser::ForallConstruct &) { setConstructExit(eval); },
1015           [&](const parser::IfConstruct &) { setConstructExit(eval); },
1016           [&](const parser::SelectRankConstruct &) {
1017             eval.constructExit = &eval.evaluationList->back();
1018             eval.isUnstructured = true;
1019           },
1020           [&](const parser::SelectTypeConstruct &) {
1021             eval.constructExit = &eval.evaluationList->back();
1022             eval.isUnstructured = true;
1023           },
1024           [&](const parser::WhereConstruct &) { setConstructExit(eval); },
1025 
1026           // Default - Common analysis for IO statements; otherwise nop.
1027           [&](const auto &stmt) {
1028             using A = std::decay_t<decltype(stmt)>;
1029             using IoStmts = std::tuple<
1030                 parser::BackspaceStmt, parser::CloseStmt, parser::EndfileStmt,
1031                 parser::FlushStmt, parser::InquireStmt, parser::OpenStmt,
1032                 parser::PrintStmt, parser::ReadStmt, parser::RewindStmt,
1033                 parser::WaitStmt, parser::WriteStmt>;
1034             if constexpr (common::HasMember<A, IoStmts>)
1035               analyzeIoBranches(eval, stmt);
1036           },
1037       });
1038 
1039       // Analyze construct evaluations.
1040       if (eval.evaluationList)
1041         analyzeBranches(&eval, *eval.evaluationList);
1042 
1043       // Propagate isUnstructured flag to enclosing construct.
1044       if (parentConstruct && eval.isUnstructured)
1045         parentConstruct->isUnstructured = true;
1046 
1047       // The successor of a branch starts a new block.
1048       if (eval.controlSuccessor && eval.isActionStmt() &&
1049           eval.lowerAsUnstructured())
1050         markSuccessorAsNewBlock(eval);
1051     }
1052   }
1053 
1054   /// Do processing specific to subprograms with multiple entry points.
1055   void processEntryPoints() {
1056     lower::pft::Evaluation *initialEval = &evaluationListStack.back()->front();
1057     lower::pft::FunctionLikeUnit *unit = initialEval->getOwningProcedure();
1058     int entryCount = unit->entryPointList.size();
1059     if (entryCount == 1)
1060       return;
1061 
1062     // The first executable statement in the subprogram is preceded by a
1063     // branch to the entry point, so it starts a new block.
1064     if (initialEval->hasNestedEvaluations())
1065       initialEval = &initialEval->getFirstNestedEvaluation();
1066     else if (initialEval->isA<Fortran::parser::EntryStmt>())
1067       initialEval = initialEval->lexicalSuccessor;
1068     initialEval->isNewBlock = true;
1069 
1070     // All function entry points share a single result container.
1071     // Find one of the largest results.
1072     for (int entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
1073       unit->setActiveEntry(entryIndex);
1074       const auto &details =
1075           unit->getSubprogramSymbol().get<semantics::SubprogramDetails>();
1076       if (details.isFunction()) {
1077         const semantics::Symbol *resultSym = &details.result();
1078         assert(resultSym && "missing result symbol");
1079         if (!unit->primaryResult ||
1080             unit->primaryResult->size() < resultSym->size())
1081           unit->primaryResult = resultSym;
1082       }
1083     }
1084     unit->setActiveEntry(0);
1085   }
1086 
1087   std::unique_ptr<lower::pft::Program> pgm;
1088   std::vector<lower::pft::PftNode> pftParentStack;
1089   const semantics::SemanticsContext &semanticsContext;
1090 
1091   /// functionList points to the internal or module procedure function list
1092   /// of a FunctionLikeUnit or a ModuleLikeUnit. It may be null.
1093   std::list<lower::pft::FunctionLikeUnit> *functionList{};
1094   std::vector<lower::pft::Evaluation *> constructAndDirectiveStack{};
1095   std::vector<lower::pft::Evaluation *> doConstructStack{};
1096   /// evaluationListStack is the current nested construct evaluationList state.
1097   std::vector<lower::pft::EvaluationList *> evaluationListStack{};
1098   llvm::DenseMap<parser::Label, lower::pft::Evaluation *> *labelEvaluationMap{};
1099   lower::pft::SymbolLabelMap *assignSymbolLabelMap{};
1100   std::map<std::string, lower::pft::Evaluation *> constructNameMap{};
1101   lower::pft::Evaluation *lastLexicalEvaluation{};
1102 };
1103 
1104 #ifndef NDEBUG
1105 /// Dump all program scopes and symbols with addresses to disambiguate names.
1106 /// This is static, unchanging front end information, so dump it only once.
1107 void dumpScope(const semantics::Scope *scope, int depth) {
1108   static int initialVisitCounter = 0;
1109   if (depth < 0) {
1110     if (++initialVisitCounter != 1)
1111       return;
1112     while (!scope->IsGlobal())
1113       scope = &scope->parent();
1114     LLVM_DEBUG(llvm::dbgs() << "Full program scope information.\n"
1115                                "Addresses in angle brackets are scopes. "
1116                                "Unbracketed addresses are symbols.\n");
1117   }
1118   static const std::string white{"                                      ++"};
1119   std::string w = white.substr(0, depth * 2);
1120   if (depth >= 0) {
1121     LLVM_DEBUG(llvm::dbgs() << w << "<" << scope << "> ");
1122     if (auto *sym{scope->symbol()}) {
1123       LLVM_DEBUG(llvm::dbgs() << sym << " " << *sym << "\n");
1124     } else {
1125       if (scope->IsIntrinsicModules()) {
1126         LLVM_DEBUG(llvm::dbgs() << "IntrinsicModules (no detail)\n");
1127         return;
1128       }
1129       if (scope->kind() == Fortran::semantics::Scope::Kind::BlockConstruct)
1130         LLVM_DEBUG(llvm::dbgs() << "[block]\n");
1131       else
1132         LLVM_DEBUG(llvm::dbgs() << "[anonymous]\n");
1133     }
1134   }
1135   for (const auto &scp : scope->children())
1136     if (!scp.symbol())
1137       dumpScope(&scp, depth + 1);
1138   for (auto iter = scope->begin(); iter != scope->end(); ++iter) {
1139     common::Reference<semantics::Symbol> sym = iter->second;
1140     if (auto scp = sym->scope())
1141       dumpScope(scp, depth + 1);
1142     else
1143       LLVM_DEBUG(llvm::dbgs() << w + "  " << &*sym << "   " << *sym << "\n");
1144   }
1145 }
1146 #endif // NDEBUG
1147 
1148 class PFTDumper {
1149 public:
1150   void dumpPFT(llvm::raw_ostream &outputStream,
1151                const lower::pft::Program &pft) {
1152     for (auto &unit : pft.getUnits()) {
1153       std::visit(common::visitors{
1154                      [&](const lower::pft::BlockDataUnit &unit) {
1155                        outputStream << getNodeIndex(unit) << " ";
1156                        outputStream << "BlockData: ";
1157                        outputStream << "\nEnd BlockData\n\n";
1158                      },
1159                      [&](const lower::pft::FunctionLikeUnit &func) {
1160                        dumpFunctionLikeUnit(outputStream, func);
1161                      },
1162                      [&](const lower::pft::ModuleLikeUnit &unit) {
1163                        dumpModuleLikeUnit(outputStream, unit);
1164                      },
1165                      [&](const lower::pft::CompilerDirectiveUnit &unit) {
1166                        dumpCompilerDirectiveUnit(outputStream, unit);
1167                      },
1168                      [&](const lower::pft::OpenACCDirectiveUnit &unit) {
1169                        dumpOpenACCDirectiveUnit(outputStream, unit);
1170                      },
1171                  },
1172                  unit);
1173     }
1174   }
1175 
1176   llvm::StringRef evaluationName(const lower::pft::Evaluation &eval) {
1177     return eval.visit([](const auto &parseTreeNode) {
1178       return parser::ParseTreeDumper::GetNodeName(parseTreeNode);
1179     });
1180   }
1181 
1182   void dumpEvaluation(llvm::raw_ostream &outputStream,
1183                       const lower::pft::Evaluation &eval,
1184                       const std::string &indentString, int indent = 1) {
1185     llvm::StringRef name = evaluationName(eval);
1186     llvm::StringRef newBlock = eval.isNewBlock ? "^" : "";
1187     llvm::StringRef bang = eval.isUnstructured ? "!" : "";
1188     outputStream << indentString;
1189     if (eval.printIndex)
1190       outputStream << eval.printIndex << ' ';
1191     if (eval.hasNestedEvaluations())
1192       outputStream << "<<" << newBlock << name << bang << ">>";
1193     else
1194       outputStream << newBlock << name << bang;
1195     if (eval.negateCondition)
1196       outputStream << " [negate]";
1197     if (eval.constructExit)
1198       outputStream << " -> " << eval.constructExit->printIndex;
1199     else if (eval.controlSuccessor)
1200       outputStream << " -> " << eval.controlSuccessor->printIndex;
1201     else if (eval.isA<parser::EntryStmt>() && eval.lexicalSuccessor)
1202       outputStream << " -> " << eval.lexicalSuccessor->printIndex;
1203     if (!eval.position.empty())
1204       outputStream << ": " << eval.position.ToString();
1205     else if (auto *dir = eval.getIf<Fortran::parser::CompilerDirective>())
1206       outputStream << ": !" << dir->source.ToString();
1207     outputStream << '\n';
1208     if (eval.hasNestedEvaluations()) {
1209       dumpEvaluationList(outputStream, *eval.evaluationList, indent + 1);
1210       outputStream << indentString << "<<End " << name << bang << ">>\n";
1211     }
1212   }
1213 
1214   void dumpEvaluation(llvm::raw_ostream &ostream,
1215                       const lower::pft::Evaluation &eval) {
1216     dumpEvaluation(ostream, eval, "");
1217   }
1218 
1219   void dumpEvaluationList(llvm::raw_ostream &outputStream,
1220                           const lower::pft::EvaluationList &evaluationList,
1221                           int indent = 1) {
1222     static const auto white = "                                      ++"s;
1223     auto indentString = white.substr(0, indent * 2);
1224     for (const lower::pft::Evaluation &eval : evaluationList)
1225       dumpEvaluation(outputStream, eval, indentString, indent);
1226   }
1227 
1228   void
1229   dumpFunctionLikeUnit(llvm::raw_ostream &outputStream,
1230                        const lower::pft::FunctionLikeUnit &functionLikeUnit) {
1231     outputStream << getNodeIndex(functionLikeUnit) << " ";
1232     llvm::StringRef unitKind;
1233     llvm::StringRef name;
1234     llvm::StringRef header;
1235     if (functionLikeUnit.beginStmt) {
1236       functionLikeUnit.beginStmt->visit(common::visitors{
1237           [&](const parser::Statement<parser::ProgramStmt> &stmt) {
1238             unitKind = "Program";
1239             name = toStringRef(stmt.statement.v.source);
1240           },
1241           [&](const parser::Statement<parser::FunctionStmt> &stmt) {
1242             unitKind = "Function";
1243             name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1244             header = toStringRef(stmt.source);
1245           },
1246           [&](const parser::Statement<parser::SubroutineStmt> &stmt) {
1247             unitKind = "Subroutine";
1248             name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1249             header = toStringRef(stmt.source);
1250           },
1251           [&](const parser::Statement<parser::MpSubprogramStmt> &stmt) {
1252             unitKind = "MpSubprogram";
1253             name = toStringRef(stmt.statement.v.source);
1254             header = toStringRef(stmt.source);
1255           },
1256           [&](const auto &) { llvm_unreachable("not a valid begin stmt"); },
1257       });
1258     } else {
1259       unitKind = "Program";
1260       name = "<anonymous>";
1261     }
1262     outputStream << unitKind << ' ' << name;
1263     if (!header.empty())
1264       outputStream << ": " << header;
1265     outputStream << '\n';
1266     dumpEvaluationList(outputStream, functionLikeUnit.evaluationList);
1267     if (!functionLikeUnit.nestedFunctions.empty()) {
1268       outputStream << "\nContains\n";
1269       for (const lower::pft::FunctionLikeUnit &func :
1270            functionLikeUnit.nestedFunctions)
1271         dumpFunctionLikeUnit(outputStream, func);
1272       outputStream << "End Contains\n";
1273     }
1274     outputStream << "End " << unitKind << ' ' << name << "\n\n";
1275   }
1276 
1277   void dumpModuleLikeUnit(llvm::raw_ostream &outputStream,
1278                           const lower::pft::ModuleLikeUnit &moduleLikeUnit) {
1279     outputStream << getNodeIndex(moduleLikeUnit) << " ";
1280     llvm::StringRef unitKind;
1281     llvm::StringRef name;
1282     llvm::StringRef header;
1283     moduleLikeUnit.beginStmt.visit(common::visitors{
1284         [&](const parser::Statement<parser::ModuleStmt> &stmt) {
1285           unitKind = "Module";
1286           name = toStringRef(stmt.statement.v.source);
1287           header = toStringRef(stmt.source);
1288         },
1289         [&](const parser::Statement<parser::SubmoduleStmt> &stmt) {
1290           unitKind = "Submodule";
1291           name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1292           header = toStringRef(stmt.source);
1293         },
1294         [&](const auto &) {
1295           llvm_unreachable("not a valid module begin stmt");
1296         },
1297     });
1298     outputStream << unitKind << ' ' << name << ": " << header << '\n';
1299     dumpEvaluationList(outputStream, moduleLikeUnit.evaluationList);
1300     outputStream << "Contains\n";
1301     for (const lower::pft::FunctionLikeUnit &func :
1302          moduleLikeUnit.nestedFunctions)
1303       dumpFunctionLikeUnit(outputStream, func);
1304     outputStream << "End Contains\nEnd " << unitKind << ' ' << name << "\n\n";
1305   }
1306 
1307   // Top level directives
1308   void dumpCompilerDirectiveUnit(
1309       llvm::raw_ostream &outputStream,
1310       const lower::pft::CompilerDirectiveUnit &directive) {
1311     outputStream << getNodeIndex(directive) << " ";
1312     outputStream << "CompilerDirective: !";
1313     outputStream << directive.get<Fortran::parser::CompilerDirective>()
1314                         .source.ToString();
1315     outputStream << "\nEnd CompilerDirective\n\n";
1316   }
1317 
1318   void
1319   dumpOpenACCDirectiveUnit(llvm::raw_ostream &outputStream,
1320                            const lower::pft::OpenACCDirectiveUnit &directive) {
1321     outputStream << getNodeIndex(directive) << " ";
1322     outputStream << "OpenACCDirective: !$acc ";
1323     outputStream << directive.get<Fortran::parser::OpenACCRoutineConstruct>()
1324                         .source.ToString();
1325     outputStream << "\nEnd OpenACCDirective\n\n";
1326   }
1327 
1328   template <typename T>
1329   std::size_t getNodeIndex(const T &node) {
1330     auto addr = static_cast<const void *>(&node);
1331     auto it = nodeIndexes.find(addr);
1332     if (it != nodeIndexes.end())
1333       return it->second;
1334     nodeIndexes.try_emplace(addr, nextIndex);
1335     return nextIndex++;
1336   }
1337   std::size_t getNodeIndex(const lower::pft::Program &) { return 0; }
1338 
1339 private:
1340   llvm::DenseMap<const void *, std::size_t> nodeIndexes;
1341   std::size_t nextIndex{1}; // 0 is the root
1342 };
1343 
1344 } // namespace
1345 
1346 template <typename A, typename T>
1347 static lower::pft::FunctionLikeUnit::FunctionStatement
1348 getFunctionStmt(const T &func) {
1349   lower::pft::FunctionLikeUnit::FunctionStatement result{
1350       std::get<parser::Statement<A>>(func.t)};
1351   return result;
1352 }
1353 
1354 template <typename A, typename T>
1355 static lower::pft::ModuleLikeUnit::ModuleStatement getModuleStmt(const T &mod) {
1356   lower::pft::ModuleLikeUnit::ModuleStatement result{
1357       std::get<parser::Statement<A>>(mod.t)};
1358   return result;
1359 }
1360 
1361 template <typename A>
1362 static const semantics::Symbol *getSymbol(A &beginStmt) {
1363   const auto *symbol = beginStmt.visit(common::visitors{
1364       [](const parser::Statement<parser::ProgramStmt> &stmt)
1365           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1366       [](const parser::Statement<parser::FunctionStmt> &stmt)
1367           -> const semantics::Symbol * {
1368         return std::get<parser::Name>(stmt.statement.t).symbol;
1369       },
1370       [](const parser::Statement<parser::SubroutineStmt> &stmt)
1371           -> const semantics::Symbol * {
1372         return std::get<parser::Name>(stmt.statement.t).symbol;
1373       },
1374       [](const parser::Statement<parser::MpSubprogramStmt> &stmt)
1375           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1376       [](const parser::Statement<parser::ModuleStmt> &stmt)
1377           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1378       [](const parser::Statement<parser::SubmoduleStmt> &stmt)
1379           -> const semantics::Symbol * {
1380         return std::get<parser::Name>(stmt.statement.t).symbol;
1381       },
1382       [](const auto &) -> const semantics::Symbol * {
1383         llvm_unreachable("unknown FunctionLike or ModuleLike beginStmt");
1384         return nullptr;
1385       }});
1386   assert(symbol && "parser::Name must have resolved symbol");
1387   return symbol;
1388 }
1389 
1390 bool Fortran::lower::pft::Evaluation::lowerAsStructured() const {
1391   return !lowerAsUnstructured();
1392 }
1393 
1394 bool Fortran::lower::pft::Evaluation::lowerAsUnstructured() const {
1395   return isUnstructured || clDisableStructuredFir;
1396 }
1397 
1398 bool Fortran::lower::pft::Evaluation::forceAsUnstructured() const {
1399   return clDisableStructuredFir;
1400 }
1401 
1402 lower::pft::FunctionLikeUnit *
1403 Fortran::lower::pft::Evaluation::getOwningProcedure() const {
1404   return parent.visit(common::visitors{
1405       [](lower::pft::FunctionLikeUnit &c) { return &c; },
1406       [&](lower::pft::Evaluation &c) { return c.getOwningProcedure(); },
1407       [](auto &) -> lower::pft::FunctionLikeUnit * { return nullptr; },
1408   });
1409 }
1410 
1411 bool Fortran::lower::definedInCommonBlock(const semantics::Symbol &sym) {
1412   return semantics::FindCommonBlockContaining(sym);
1413 }
1414 
1415 /// Is the symbol `sym` a global?
1416 bool Fortran::lower::symbolIsGlobal(const semantics::Symbol &sym) {
1417   return semantics::IsSaved(sym) || lower::definedInCommonBlock(sym) ||
1418          semantics::IsNamedConstant(sym);
1419 }
1420 
1421 namespace {
1422 /// This helper class sorts the symbols in a scope such that a symbol will
1423 /// be placed after those it depends upon. Otherwise the sort is stable and
1424 /// preserves the order of the symbol table, which is sorted by name. This
1425 /// analysis may also be done for an individual symbol.
1426 struct SymbolDependenceAnalysis {
1427   explicit SymbolDependenceAnalysis(const semantics::Scope &scope) {
1428     analyzeEquivalenceSets(scope);
1429     for (const auto &iter : scope)
1430       analyze(iter.second.get());
1431     finalize();
1432   }
1433   explicit SymbolDependenceAnalysis(const semantics::Symbol &symbol) {
1434     analyzeEquivalenceSets(symbol.owner());
1435     analyze(symbol);
1436     finalize();
1437   }
1438   Fortran::lower::pft::VariableList getVariableList() {
1439     return std::move(layeredVarList[0]);
1440   }
1441 
1442 private:
1443   /// Analyze the equivalence sets defined in \p scope, plus the equivalence
1444   /// sets in host module, submodule, and procedure scopes that may define
1445   /// symbols referenced in \p scope. This analysis excludes equivalence sets
1446   /// involving common blocks, which are handled elsewhere.
1447   void analyzeEquivalenceSets(const semantics::Scope &scope) {
1448     // FIXME: When this function is called on the scope of an internal
1449     // procedure whose parent contains an EQUIVALENCE set and the internal
1450     // procedure uses variables from that EQUIVALENCE set, we end up creating
1451     // an AggregateStore for those variables unnecessarily.
1452 
1453     // A function defined in a [sub]module has no explicit USE of its ancestor
1454     // [sub]modules. Analyze those scopes here to accommodate references to
1455     // symbols in them.
1456     for (auto *scp = &scope.parent(); !scp->IsGlobal(); scp = &scp->parent())
1457       if (scp->kind() == Fortran::semantics::Scope::Kind::Module)
1458         analyzeLocalEquivalenceSets(*scp);
1459     // Analyze local, USEd, and host procedure scope equivalences.
1460     for (const auto &iter : scope) {
1461       const semantics::Symbol &ultimate = iter.second.get().GetUltimate();
1462       if (!skipSymbol(ultimate))
1463         analyzeLocalEquivalenceSets(ultimate.owner());
1464     }
1465     // Add all aggregate stores to the front of the variable list.
1466     adjustSize(1);
1467     // The copy in the loop matters, 'stores' will still be used.
1468     for (auto st : stores)
1469       layeredVarList[0].emplace_back(std::move(st));
1470   }
1471 
1472   /// Analyze the equivalence sets defined locally in \p scope that don't
1473   /// involve common blocks.
1474   void analyzeLocalEquivalenceSets(const semantics::Scope &scope) {
1475     if (scope.equivalenceSets().empty())
1476       return; // no equivalence sets to analyze
1477     if (analyzedScopes.contains(&scope))
1478       return; // equivalence sets already analyzed
1479 
1480     analyzedScopes.insert(&scope);
1481     std::list<std::list<semantics::SymbolRef>> aggregates =
1482         Fortran::semantics::GetStorageAssociations(scope);
1483     for (std::list<semantics::SymbolRef> aggregate : aggregates) {
1484       const Fortran::semantics::Symbol *aggregateSym = nullptr;
1485       bool isGlobal = false;
1486       const semantics::Symbol &first = *aggregate.front();
1487       // Exclude equivalence sets involving common blocks.
1488       // Those are handled in instantiateCommon.
1489       if (lower::definedInCommonBlock(first))
1490         continue;
1491       std::size_t start = first.offset();
1492       std::size_t end = first.offset() + first.size();
1493       const Fortran::semantics::Symbol *namingSym = nullptr;
1494       for (semantics::SymbolRef symRef : aggregate) {
1495         const semantics::Symbol &sym = *symRef;
1496         aliasSyms.insert(&sym);
1497         if (sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated)) {
1498           aggregateSym = &sym;
1499         } else {
1500           isGlobal |= lower::symbolIsGlobal(sym);
1501           start = std::min(sym.offset(), start);
1502           end = std::max(sym.offset() + sym.size(), end);
1503           if (!namingSym || (sym.name() < namingSym->name()))
1504             namingSym = &sym;
1505         }
1506       }
1507       assert(namingSym && "must contain at least one user symbol");
1508       if (!aggregateSym) {
1509         stores.emplace_back(
1510             Fortran::lower::pft::Variable::Interval{start, end - start},
1511             *namingSym, isGlobal);
1512       } else {
1513         stores.emplace_back(*aggregateSym, *namingSym, isGlobal);
1514       }
1515     }
1516   }
1517 
1518   // Recursively visit each symbol to determine the height of its dependence on
1519   // other symbols.
1520   int analyze(const semantics::Symbol &sym) {
1521     auto done = seen.insert(&sym);
1522     if (!done.second)
1523       return 0;
1524     LLVM_DEBUG(llvm::dbgs() << "analyze symbol " << &sym << " in <"
1525                             << &sym.owner() << ">: " << sym << '\n');
1526     const bool isProcedurePointerOrDummy =
1527         semantics::IsProcedurePointer(sym) ||
1528         (semantics::IsProcedure(sym) && IsDummy(sym));
1529     // A procedure argument in a subprogram with multiple entry points might
1530     // need a layeredVarList entry to trigger creation of a symbol map entry
1531     // in some cases. Non-dummy procedures don't.
1532     if (semantics::IsProcedure(sym) && !isProcedurePointerOrDummy)
1533       return 0;
1534     // Derived type component symbols may be collected by "CollectSymbols"
1535     // below when processing something like "real :: x(derived%component)". The
1536     // symbol "component" has "ObjectEntityDetails", but it should not be
1537     // instantiated: it is part of "derived" that should be the only one to
1538     // be instantiated.
1539     if (sym.owner().IsDerivedType())
1540       return 0;
1541 
1542     semantics::Symbol ultimate = sym.GetUltimate();
1543     if (const auto *details =
1544             ultimate.detailsIf<semantics::NamelistDetails>()) {
1545       // handle namelist group symbols
1546       for (const semantics::SymbolRef &s : details->objects())
1547         analyze(s);
1548       return 0;
1549     }
1550     if (!ultimate.has<semantics::ObjectEntityDetails>() &&
1551         !isProcedurePointerOrDummy)
1552       return 0;
1553 
1554     if (sym.has<semantics::DerivedTypeDetails>())
1555       llvm_unreachable("not yet implemented - derived type analysis");
1556 
1557     // Symbol must be something lowering will have to allocate.
1558     int depth = 0;
1559     // Analyze symbols appearing in object entity specification expressions.
1560     // This ensures these symbols will be instantiated before the current one.
1561     // This is not done for object entities that are host associated because
1562     // they must be instantiated from the value of the host symbols.
1563     // (The specification expressions should not be re-evaluated.)
1564     if (const auto *details = sym.detailsIf<semantics::ObjectEntityDetails>()) {
1565       const semantics::DeclTypeSpec *symTy = sym.GetType();
1566       assert(symTy && "symbol must have a type");
1567       // check CHARACTER's length
1568       if (symTy->category() == semantics::DeclTypeSpec::Character)
1569         if (auto e = symTy->characterTypeSpec().length().GetExplicit())
1570           for (const auto &s : evaluate::CollectSymbols(*e))
1571             depth = std::max(analyze(s) + 1, depth);
1572 
1573       auto doExplicit = [&](const auto &bound) {
1574         if (bound.isExplicit()) {
1575           semantics::SomeExpr e{*bound.GetExplicit()};
1576           for (const auto &s : evaluate::CollectSymbols(e))
1577             depth = std::max(analyze(s) + 1, depth);
1578         }
1579       };
1580       // Handle any symbols in array bound declarations.
1581       for (const semantics::ShapeSpec &subs : details->shape()) {
1582         doExplicit(subs.lbound());
1583         doExplicit(subs.ubound());
1584       }
1585       // Handle any symbols in coarray bound declarations.
1586       for (const semantics::ShapeSpec &subs : details->coshape()) {
1587         doExplicit(subs.lbound());
1588         doExplicit(subs.ubound());
1589       }
1590       // Handle any symbols in initialization expressions.
1591       if (auto e = details->init())
1592         for (const auto &s : evaluate::CollectSymbols(*e))
1593           if (!s->has<semantics::DerivedTypeDetails>())
1594             depth = std::max(analyze(s) + 1, depth);
1595     }
1596     adjustSize(depth + 1);
1597     bool global = lower::symbolIsGlobal(sym);
1598     layeredVarList[depth].emplace_back(sym, global, depth);
1599     if (semantics::IsAllocatable(sym))
1600       layeredVarList[depth].back().setHeapAlloc();
1601     if (semantics::IsPointer(sym))
1602       layeredVarList[depth].back().setPointer();
1603     if (ultimate.attrs().test(semantics::Attr::TARGET))
1604       layeredVarList[depth].back().setTarget();
1605 
1606     // If there are alias sets, then link the participating variables to their
1607     // aggregate stores when constructing the new variable on the list.
1608     if (lower::pft::Variable::AggregateStore *store = findStoreIfAlias(sym))
1609       layeredVarList[depth].back().setAlias(store->getOffset());
1610     return depth;
1611   }
1612 
1613   /// Skip symbol in alias analysis.
1614   bool skipSymbol(const semantics::Symbol &sym) {
1615     // Common block equivalences are largely managed by the front end.
1616     // Compiler generated symbols ('.' names) cannot be equivalenced.
1617     // FIXME: Equivalence code generation may need to be revisited.
1618     return !sym.has<semantics::ObjectEntityDetails>() ||
1619            lower::definedInCommonBlock(sym) || sym.name()[0] == '.';
1620   }
1621 
1622   // Make sure the table is of appropriate size.
1623   void adjustSize(std::size_t size) {
1624     if (layeredVarList.size() < size)
1625       layeredVarList.resize(size);
1626   }
1627 
1628   Fortran::lower::pft::Variable::AggregateStore *
1629   findStoreIfAlias(const Fortran::evaluate::Symbol &sym) {
1630     const semantics::Symbol &ultimate = sym.GetUltimate();
1631     const semantics::Scope &scope = ultimate.owner();
1632     // Expect the total number of EQUIVALENCE sets to be small for a typical
1633     // Fortran program.
1634     if (aliasSyms.contains(&ultimate)) {
1635       LLVM_DEBUG(llvm::dbgs() << "found aggregate containing " << &ultimate
1636                               << " " << ultimate.name() << " in <" << &scope
1637                               << "> " << scope.GetName() << '\n');
1638       std::size_t off = ultimate.offset();
1639       std::size_t symSize = ultimate.size();
1640       for (lower::pft::Variable::AggregateStore &v : stores) {
1641         if (&v.getOwningScope() == &scope) {
1642           auto intervalOff = std::get<0>(v.interval);
1643           auto intervalSize = std::get<1>(v.interval);
1644           if (off >= intervalOff && off < intervalOff + intervalSize)
1645             return &v;
1646           // Zero sized symbol in zero sized equivalence.
1647           if (off == intervalOff && symSize == 0)
1648             return &v;
1649         }
1650       }
1651       // clang-format off
1652       LLVM_DEBUG(
1653           llvm::dbgs() << "looking for " << off << "\n{\n";
1654           for (lower::pft::Variable::AggregateStore &v : stores) {
1655             llvm::dbgs() << " in scope: " << &v.getOwningScope() << "\n";
1656             llvm::dbgs() << "  i = [" << std::get<0>(v.interval) << ".."
1657                 << std::get<0>(v.interval) + std::get<1>(v.interval)
1658                 << "]\n";
1659           }
1660           llvm::dbgs() << "}\n");
1661       // clang-format on
1662       llvm_unreachable("the store must be present");
1663     }
1664     return nullptr;
1665   }
1666 
1667   /// Flatten the result VariableList.
1668   void finalize() {
1669     for (int i = 1, end = layeredVarList.size(); i < end; ++i)
1670       layeredVarList[0].insert(layeredVarList[0].end(),
1671                                layeredVarList[i].begin(),
1672                                layeredVarList[i].end());
1673   }
1674 
1675   llvm::SmallSet<const semantics::Symbol *, 32> seen;
1676   std::vector<Fortran::lower::pft::VariableList> layeredVarList;
1677   llvm::SmallSet<const semantics::Symbol *, 32> aliasSyms;
1678   /// Set of scopes that have been analyzed for aliases.
1679   llvm::SmallSet<const semantics::Scope *, 4> analyzedScopes;
1680   std::vector<Fortran::lower::pft::Variable::AggregateStore> stores;
1681 };
1682 } // namespace
1683 
1684 //===----------------------------------------------------------------------===//
1685 // FunctionLikeUnit implementation
1686 //===----------------------------------------------------------------------===//
1687 
1688 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1689     const parser::MainProgram &func, const lower::pft::PftNode &parent,
1690     const semantics::SemanticsContext &semanticsContext)
1691     : ProgramUnit{func, parent},
1692       endStmt{getFunctionStmt<parser::EndProgramStmt>(func)} {
1693   const auto &programStmt =
1694       std::get<std::optional<parser::Statement<parser::ProgramStmt>>>(func.t);
1695   if (programStmt.has_value()) {
1696     beginStmt = FunctionStatement(programStmt.value());
1697     const semantics::Symbol *symbol = getSymbol(*beginStmt);
1698     entryPointList[0].first = symbol;
1699     scope = symbol->scope();
1700   } else {
1701     scope = &semanticsContext.FindScope(
1702         std::get<parser::Statement<parser::EndProgramStmt>>(func.t).source);
1703   }
1704 }
1705 
1706 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1707     const parser::FunctionSubprogram &func, const lower::pft::PftNode &parent,
1708     const semantics::SemanticsContext &)
1709     : ProgramUnit{func, parent},
1710       beginStmt{getFunctionStmt<parser::FunctionStmt>(func)},
1711       endStmt{getFunctionStmt<parser::EndFunctionStmt>(func)} {
1712   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1713   entryPointList[0].first = symbol;
1714   scope = symbol->scope();
1715 }
1716 
1717 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1718     const parser::SubroutineSubprogram &func, const lower::pft::PftNode &parent,
1719     const semantics::SemanticsContext &)
1720     : ProgramUnit{func, parent},
1721       beginStmt{getFunctionStmt<parser::SubroutineStmt>(func)},
1722       endStmt{getFunctionStmt<parser::EndSubroutineStmt>(func)} {
1723   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1724   entryPointList[0].first = symbol;
1725   scope = symbol->scope();
1726 }
1727 
1728 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1729     const parser::SeparateModuleSubprogram &func,
1730     const lower::pft::PftNode &parent, const semantics::SemanticsContext &)
1731     : ProgramUnit{func, parent},
1732       beginStmt{getFunctionStmt<parser::MpSubprogramStmt>(func)},
1733       endStmt{getFunctionStmt<parser::EndMpSubprogramStmt>(func)} {
1734   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1735   entryPointList[0].first = symbol;
1736   scope = symbol->scope();
1737 }
1738 
1739 Fortran::lower::HostAssociations &
1740 Fortran::lower::pft::FunctionLikeUnit::parentHostAssoc() {
1741   if (auto *par = parent.getIf<FunctionLikeUnit>())
1742     return par->hostAssociations;
1743   llvm::report_fatal_error("parent is not a function");
1744 }
1745 
1746 bool Fortran::lower::pft::FunctionLikeUnit::parentHasTupleHostAssoc() {
1747   if (auto *par = parent.getIf<FunctionLikeUnit>())
1748     return par->hostAssociations.hasTupleAssociations();
1749   return false;
1750 }
1751 
1752 bool Fortran::lower::pft::FunctionLikeUnit::parentHasHostAssoc() {
1753   if (auto *par = parent.getIf<FunctionLikeUnit>())
1754     return !par->hostAssociations.empty();
1755   return false;
1756 }
1757 
1758 parser::CharBlock
1759 Fortran::lower::pft::FunctionLikeUnit::getStartingSourceLoc() const {
1760   if (beginStmt)
1761     return stmtSourceLoc(*beginStmt);
1762   return scope->sourceRange();
1763 }
1764 
1765 //===----------------------------------------------------------------------===//
1766 // ModuleLikeUnit implementation
1767 //===----------------------------------------------------------------------===//
1768 
1769 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1770     const parser::Module &m, const lower::pft::PftNode &parent)
1771     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::ModuleStmt>(m)},
1772       endStmt{getModuleStmt<parser::EndModuleStmt>(m)} {}
1773 
1774 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1775     const parser::Submodule &m, const lower::pft::PftNode &parent)
1776     : ProgramUnit{m, parent},
1777       beginStmt{getModuleStmt<parser::SubmoduleStmt>(m)},
1778       endStmt{getModuleStmt<parser::EndSubmoduleStmt>(m)} {}
1779 
1780 parser::CharBlock
1781 Fortran::lower::pft::ModuleLikeUnit::getStartingSourceLoc() const {
1782   return stmtSourceLoc(beginStmt);
1783 }
1784 const Fortran::semantics::Scope &
1785 Fortran::lower::pft::ModuleLikeUnit::getScope() const {
1786   const Fortran::semantics::Symbol *symbol = getSymbol(beginStmt);
1787   assert(symbol && symbol->scope() &&
1788          "Module statement must have a symbol with a scope");
1789   return *symbol->scope();
1790 }
1791 
1792 //===----------------------------------------------------------------------===//
1793 // BlockDataUnit implementation
1794 //===----------------------------------------------------------------------===//
1795 
1796 Fortran::lower::pft::BlockDataUnit::BlockDataUnit(
1797     const parser::BlockData &bd, const lower::pft::PftNode &parent,
1798     const semantics::SemanticsContext &semanticsContext)
1799     : ProgramUnit{bd, parent},
1800       symTab{semanticsContext.FindScope(
1801           std::get<parser::Statement<parser::EndBlockDataStmt>>(bd.t).source)} {
1802 }
1803 
1804 std::unique_ptr<lower::pft::Program>
1805 Fortran::lower::createPFT(const parser::Program &root,
1806                           const semantics::SemanticsContext &semanticsContext) {
1807   PFTBuilder walker(semanticsContext);
1808   Walk(root, walker);
1809   return walker.result();
1810 }
1811 
1812 void Fortran::lower::dumpPFT(llvm::raw_ostream &outputStream,
1813                              const lower::pft::Program &pft) {
1814   PFTDumper{}.dumpPFT(outputStream, pft);
1815 }
1816 
1817 void Fortran::lower::pft::Program::dump() const {
1818   dumpPFT(llvm::errs(), *this);
1819 }
1820 
1821 void Fortran::lower::pft::Evaluation::dump() const {
1822   PFTDumper{}.dumpEvaluation(llvm::errs(), *this);
1823 }
1824 
1825 void Fortran::lower::pft::Variable::dump() const {
1826   if (auto *s = std::get_if<Nominal>(&var)) {
1827     llvm::errs() << s->symbol << " " << *s->symbol;
1828     llvm::errs() << " (depth: " << s->depth << ')';
1829     if (s->global)
1830       llvm::errs() << ", global";
1831     if (s->heapAlloc)
1832       llvm::errs() << ", allocatable";
1833     if (s->pointer)
1834       llvm::errs() << ", pointer";
1835     if (s->target)
1836       llvm::errs() << ", target";
1837     if (s->aliaser)
1838       llvm::errs() << ", equivalence(" << s->aliasOffset << ')';
1839   } else if (auto *s = std::get_if<AggregateStore>(&var)) {
1840     llvm::errs() << "interval[" << std::get<0>(s->interval) << ", "
1841                  << std::get<1>(s->interval) << "]:";
1842     llvm::errs() << " name: " << toStringRef(s->getNamingSymbol().name());
1843     if (s->isGlobal())
1844       llvm::errs() << ", global";
1845     if (s->initialValueSymbol)
1846       llvm::errs() << ", initial value: {" << *s->initialValueSymbol << "}";
1847   } else {
1848     llvm_unreachable("not a Variable");
1849   }
1850   llvm::errs() << '\n';
1851 }
1852 
1853 void Fortran::lower::pft::dump(Fortran::lower::pft::VariableList &variableList,
1854                                std::string s) {
1855   llvm::errs() << (s.empty() ? "VariableList" : s) << " " << &variableList
1856                << " size=" << variableList.size() << "\n";
1857   for (auto var : variableList) {
1858     llvm::errs() << "  ";
1859     var.dump();
1860   }
1861 }
1862 
1863 void Fortran::lower::pft::FunctionLikeUnit::dump() const {
1864   PFTDumper{}.dumpFunctionLikeUnit(llvm::errs(), *this);
1865 }
1866 
1867 void Fortran::lower::pft::ModuleLikeUnit::dump() const {
1868   PFTDumper{}.dumpModuleLikeUnit(llvm::errs(), *this);
1869 }
1870 
1871 /// The BlockDataUnit dump is just the associated symbol table.
1872 void Fortran::lower::pft::BlockDataUnit::dump() const {
1873   llvm::errs() << "block data {\n" << symTab << "\n}\n";
1874 }
1875 
1876 /// Find or create an ordered list of equivalences and variables in \p scope.
1877 /// The result is cached in \p map.
1878 const lower::pft::VariableList &
1879 lower::pft::getScopeVariableList(const semantics::Scope &scope,
1880                                  ScopeVariableListMap &map) {
1881   LLVM_DEBUG(llvm::dbgs() << "\ngetScopeVariableList of [sub]module scope <"
1882                           << &scope << "> " << scope.GetName() << "\n");
1883   auto iter = map.find(&scope);
1884   if (iter == map.end()) {
1885     SymbolDependenceAnalysis sda(scope);
1886     map.emplace(&scope, sda.getVariableList());
1887     iter = map.find(&scope);
1888   }
1889   return iter->second;
1890 }
1891 
1892 /// Create an ordered list of equivalences and variables in \p scope.
1893 /// The result is not cached.
1894 lower::pft::VariableList
1895 lower::pft::getScopeVariableList(const semantics::Scope &scope) {
1896   LLVM_DEBUG(
1897       llvm::dbgs() << "\ngetScopeVariableList of [sub]program|block scope <"
1898                    << &scope << "> " << scope.GetName() << "\n");
1899   SymbolDependenceAnalysis sda(scope);
1900   return sda.getVariableList();
1901 }
1902 
1903 /// Create an ordered list of equivalences and variables that \p symbol
1904 /// depends on (no caching). Include \p symbol at the end of the list.
1905 lower::pft::VariableList
1906 lower::pft::getDependentVariableList(const semantics::Symbol &symbol) {
1907   LLVM_DEBUG(llvm::dbgs() << "\ngetDependentVariableList of " << &symbol
1908                           << " - " << symbol << "\n");
1909   SymbolDependenceAnalysis sda(symbol);
1910   return sda.getVariableList();
1911 }
1912 
1913 namespace {
1914 /// Helper class to find all the symbols referenced in a FunctionLikeUnit.
1915 /// It defines a parse tree visitor doing a deep visit in all nodes with
1916 /// symbols (including evaluate::Expr).
1917 struct SymbolVisitor {
1918   template <typename A>
1919   bool Pre(const A &x) {
1920     if constexpr (Fortran::parser::HasTypedExpr<A>::value)
1921       // Some parse tree Expr may legitimately be un-analyzed after semantics
1922       // (for instance PDT component initial value in the PDT definition body).
1923       if (const auto *expr = Fortran::semantics::GetExpr(nullptr, x))
1924         visitExpr(*expr);
1925     return true;
1926   }
1927 
1928   bool Pre(const Fortran::parser::Name &name) {
1929     if (const semantics::Symbol *symbol = name.symbol)
1930       visitSymbol(*symbol);
1931     return false;
1932   }
1933 
1934   template <typename T>
1935   void visitExpr(const Fortran::evaluate::Expr<T> &expr) {
1936     for (const semantics::Symbol &symbol :
1937          Fortran::evaluate::CollectSymbols(expr))
1938       visitSymbol(symbol);
1939   }
1940 
1941   void visitSymbol(const Fortran::semantics::Symbol &symbol) {
1942     callBack(symbol);
1943     // - Visit statement function body since it will be inlined in lowering.
1944     // - Visit function results specification expressions because allocations
1945     //   happens on the caller side.
1946     if (const auto *subprogramDetails =
1947             symbol.detailsIf<Fortran::semantics::SubprogramDetails>()) {
1948       if (const auto &maybeExpr = subprogramDetails->stmtFunction()) {
1949         visitExpr(*maybeExpr);
1950       } else {
1951         if (subprogramDetails->isFunction()) {
1952           // Visit result extents expressions that are explicit.
1953           const Fortran::semantics::Symbol &result =
1954               subprogramDetails->result();
1955           if (const auto *objectDetails =
1956                   result.detailsIf<Fortran::semantics::ObjectEntityDetails>())
1957             if (objectDetails->shape().IsExplicitShape())
1958               for (const Fortran::semantics::ShapeSpec &shapeSpec :
1959                    objectDetails->shape()) {
1960                 visitExpr(shapeSpec.lbound().GetExplicit().value());
1961                 visitExpr(shapeSpec.ubound().GetExplicit().value());
1962               }
1963         }
1964       }
1965     }
1966     if (Fortran::semantics::IsProcedure(symbol)) {
1967       if (auto dynamicType = Fortran::evaluate::DynamicType::From(symbol)) {
1968         // Visit result length specification expressions that are explicit.
1969         if (dynamicType->category() ==
1970             Fortran::common::TypeCategory::Character) {
1971           if (std::optional<Fortran::evaluate::ExtentExpr> length =
1972                   dynamicType->GetCharLength())
1973             visitExpr(*length);
1974         } else if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
1975                        Fortran::evaluate::GetDerivedTypeSpec(dynamicType)) {
1976           for (const auto &[_, param] : derivedTypeSpec->parameters())
1977             if (const Fortran::semantics::MaybeIntExpr &expr =
1978                     param.GetExplicit())
1979               visitExpr(expr.value());
1980         }
1981       }
1982     }
1983   }
1984 
1985   template <typename A>
1986   constexpr void Post(const A &) {}
1987 
1988   const std::function<void(const Fortran::semantics::Symbol &)> &callBack;
1989 };
1990 } // namespace
1991 
1992 void Fortran::lower::pft::visitAllSymbols(
1993     const Fortran::lower::pft::FunctionLikeUnit &funit,
1994     const std::function<void(const Fortran::semantics::Symbol &)> callBack) {
1995   SymbolVisitor visitor{callBack};
1996   funit.visit([&](const auto &functionParserNode) {
1997     parser::Walk(functionParserNode, visitor);
1998   });
1999 }
2000 
2001 void Fortran::lower::pft::visitAllSymbols(
2002     const Fortran::lower::pft::Evaluation &eval,
2003     const std::function<void(const Fortran::semantics::Symbol &)> callBack) {
2004   SymbolVisitor visitor{callBack};
2005   eval.visit([&](const auto &functionParserNode) {
2006     parser::Walk(functionParserNode, visitor);
2007   });
2008 }
2009