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