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