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