1 //===-- PFTBuilder.cc -----------------------------------------------------===//
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/Utils.h"
11 #include "flang/Parser/dump-parse-tree.h"
12 #include "flang/Parser/parse-tree-visitor.h"
13 #include "flang/Semantics/semantics.h"
14 #include "flang/Semantics/tools.h"
15 #include "llvm/Support/CommandLine.h"
16 
17 static llvm::cl::opt<bool> clDisableStructuredFir(
18     "no-structured-fir", llvm::cl::desc("disable generation of structured FIR"),
19     llvm::cl::init(false), llvm::cl::Hidden);
20 
21 using namespace Fortran;
22 
23 namespace {
24 /// Helpers to unveil parser node inside Fortran::parser::Statement<>,
25 /// Fortran::parser::UnlabeledStatement, and Fortran::common::Indirection<>
26 template <typename A>
27 struct RemoveIndirectionHelper {
28   using Type = A;
29 };
30 template <typename A>
31 struct RemoveIndirectionHelper<common::Indirection<A>> {
32   using Type = A;
33 };
34 
35 template <typename A>
36 struct UnwrapStmt {
37   static constexpr bool isStmt{false};
38 };
39 template <typename A>
40 struct UnwrapStmt<parser::Statement<A>> {
41   static constexpr bool isStmt{true};
42   using Type = typename RemoveIndirectionHelper<A>::Type;
43   constexpr UnwrapStmt(const parser::Statement<A> &a)
44       : unwrapped{removeIndirection(a.statement)}, position{a.source},
45         label{a.label} {}
46   const Type &unwrapped;
47   parser::CharBlock position;
48   std::optional<parser::Label> label;
49 };
50 template <typename A>
51 struct UnwrapStmt<parser::UnlabeledStatement<A>> {
52   static constexpr bool isStmt{true};
53   using Type = typename RemoveIndirectionHelper<A>::Type;
54   constexpr UnwrapStmt(const parser::UnlabeledStatement<A> &a)
55       : unwrapped{removeIndirection(a.statement)}, position{a.source} {}
56   const Type &unwrapped;
57   parser::CharBlock position;
58   std::optional<parser::Label> label;
59 };
60 
61 /// The instantiation of a parse tree visitor (Pre and Post) is extremely
62 /// expensive in terms of compile and link time.  So one goal here is to
63 /// limit the bridge to one such instantiation.
64 class PFTBuilder {
65 public:
66   PFTBuilder(const semantics::SemanticsContext &semanticsContext)
67       : pgm{std::make_unique<lower::pft::Program>()},
68         parentVariantStack{*pgm.get()}, semanticsContext{semanticsContext} {}
69 
70   /// Get the result
71   std::unique_ptr<lower::pft::Program> result() { return std::move(pgm); }
72 
73   template <typename A>
74   constexpr bool Pre(const A &a) {
75     if constexpr (lower::pft::isFunctionLike<A>) {
76       return enterFunction(a, semanticsContext);
77     } else if constexpr (lower::pft::isConstruct<A> ||
78                          lower::pft::isDirective<A>) {
79       return enterConstructOrDirective(a);
80     } else if constexpr (UnwrapStmt<A>::isStmt) {
81       using T = typename UnwrapStmt<A>::Type;
82       // Node "a" being visited has one of the following types:
83       // Statement<T>, Statement<Indirection<T>, UnlabeledStatement<T>,
84       // or UnlabeledStatement<Indirection<T>>
85       auto stmt{UnwrapStmt<A>(a)};
86       if constexpr (lower::pft::isConstructStmt<T> ||
87                     lower::pft::isOtherStmt<T>) {
88         addEvaluation(lower::pft::Evaluation{stmt.unwrapped,
89                                              parentVariantStack.back(),
90                                              stmt.position, stmt.label});
91         return false;
92       } else if constexpr (std::is_same_v<T, parser::ActionStmt>) {
93         addEvaluation(
94             makeEvaluationAction(stmt.unwrapped, stmt.position, stmt.label));
95         return true;
96       }
97     }
98     return true;
99   }
100 
101   template <typename A>
102   constexpr void Post(const A &) {
103     if constexpr (lower::pft::isFunctionLike<A>) {
104       exitFunction();
105     } else if constexpr (lower::pft::isConstruct<A> ||
106                          lower::pft::isDirective<A>) {
107       exitConstructOrDirective();
108     }
109   }
110 
111   // Module like
112   bool Pre(const parser::Module &node) { return enterModule(node); }
113   bool Pre(const parser::Submodule &node) { return enterModule(node); }
114 
115   void Post(const parser::Module &) { exitModule(); }
116   void Post(const parser::Submodule &) { exitModule(); }
117 
118   // Block data
119   bool Pre(const parser::BlockData &node) {
120     addUnit(lower::pft::BlockDataUnit{node, parentVariantStack.back()});
121     return false;
122   }
123 
124   // Get rid of production wrapper
125   bool Pre(const parser::UnlabeledStatement<parser::ForallAssignmentStmt>
126                &statement) {
127     addEvaluation(std::visit(
128         [&](const auto &x) {
129           return lower::pft::Evaluation{
130               x, parentVariantStack.back(), statement.source, {}};
131         },
132         statement.statement.u));
133     return false;
134   }
135   bool Pre(const parser::Statement<parser::ForallAssignmentStmt> &statement) {
136     addEvaluation(std::visit(
137         [&](const auto &x) {
138           return lower::pft::Evaluation{x, parentVariantStack.back(),
139                                         statement.source, statement.label};
140         },
141         statement.statement.u));
142     return false;
143   }
144   bool Pre(const parser::WhereBodyConstruct &whereBody) {
145     return std::visit(
146         common::visitors{
147             [&](const parser::Statement<parser::AssignmentStmt> &stmt) {
148               // Not caught as other AssignmentStmt because it is not
149               // wrapped in a parser::ActionStmt.
150               addEvaluation(lower::pft::Evaluation{stmt.statement,
151                                                    parentVariantStack.back(),
152                                                    stmt.source, stmt.label});
153               return false;
154             },
155             [&](const auto &) { return true; },
156         },
157         whereBody.u);
158   }
159 
160 private:
161   /// Initialize a new module-like unit and make it the builder's focus.
162   template <typename A>
163   bool enterModule(const A &func) {
164     auto &unit =
165         addUnit(lower::pft::ModuleLikeUnit{func, parentVariantStack.back()});
166     functionList = &unit.nestedFunctions;
167     parentVariantStack.emplace_back(unit);
168     return true;
169   }
170 
171   void exitModule() {
172     parentVariantStack.pop_back();
173     resetFunctionState();
174   }
175 
176   /// Ensure that a function has a branch target after the last user statement.
177   void endFunctionBody() {
178     if (lastLexicalEvaluation) {
179       static const parser::ContinueStmt endTarget{};
180       addEvaluation(
181           lower::pft::Evaluation{endTarget, parentVariantStack.back(), {}, {}});
182       lastLexicalEvaluation = nullptr;
183     }
184   }
185 
186   /// Initialize a new function-like unit and make it the builder's focus.
187   template <typename A>
188   bool enterFunction(const A &func,
189                      const semantics::SemanticsContext &semanticsContext) {
190     endFunctionBody(); // enclosing host subprogram body, if any
191     auto &unit = addFunction(lower::pft::FunctionLikeUnit{
192         func, parentVariantStack.back(), semanticsContext});
193     labelEvaluationMap = &unit.labelEvaluationMap;
194     assignSymbolLabelMap = &unit.assignSymbolLabelMap;
195     functionList = &unit.nestedFunctions;
196     pushEvaluationList(&unit.evaluationList);
197     parentVariantStack.emplace_back(unit);
198     return true;
199   }
200 
201   void exitFunction() {
202     endFunctionBody();
203     analyzeBranches(nullptr, *evaluationListStack.back()); // add branch links
204     popEvaluationList();
205     labelEvaluationMap = nullptr;
206     assignSymbolLabelMap = nullptr;
207     parentVariantStack.pop_back();
208     resetFunctionState();
209   }
210 
211   /// Initialize a new construct and make it the builder's focus.
212   template <typename A>
213   bool enterConstructOrDirective(const A &construct) {
214     auto &eval = addEvaluation(
215         lower::pft::Evaluation{construct, parentVariantStack.back()});
216     eval.evaluationList.reset(new lower::pft::EvaluationList);
217     pushEvaluationList(eval.evaluationList.get());
218     parentVariantStack.emplace_back(eval);
219     constructAndDirectiveStack.emplace_back(&eval);
220     return true;
221   }
222 
223   void exitConstructOrDirective() {
224     popEvaluationList();
225     parentVariantStack.pop_back();
226     constructAndDirectiveStack.pop_back();
227   }
228 
229   /// Reset function state to that of an enclosing host function.
230   void resetFunctionState() {
231     if (!parentVariantStack.empty()) {
232       parentVariantStack.back().visit(common::visitors{
233           [&](lower::pft::FunctionLikeUnit &p) {
234             functionList = &p.nestedFunctions;
235             labelEvaluationMap = &p.labelEvaluationMap;
236             assignSymbolLabelMap = &p.assignSymbolLabelMap;
237           },
238           [&](lower::pft::ModuleLikeUnit &p) {
239             functionList = &p.nestedFunctions;
240           },
241           [&](auto &) { functionList = nullptr; },
242       });
243     }
244   }
245 
246   template <typename A>
247   A &addUnit(A &&unit) {
248     pgm->getUnits().emplace_back(std::move(unit));
249     return std::get<A>(pgm->getUnits().back());
250   }
251 
252   template <typename A>
253   A &addFunction(A &&func) {
254     if (functionList) {
255       functionList->emplace_back(std::move(func));
256       return functionList->back();
257     }
258     return addUnit(std::move(func));
259   }
260 
261   // ActionStmt has a couple of non-conforming cases, explicitly handled here.
262   // The other cases use an Indirection, which are discarded in the PFT.
263   lower::pft::Evaluation
264   makeEvaluationAction(const parser::ActionStmt &statement,
265                        parser::CharBlock position,
266                        std::optional<parser::Label> label) {
267     return std::visit(
268         common::visitors{
269             [&](const auto &x) {
270               return lower::pft::Evaluation{removeIndirection(x),
271                                             parentVariantStack.back(), position,
272                                             label};
273             },
274         },
275         statement.u);
276   }
277 
278   /// Append an Evaluation to the end of the current list.
279   lower::pft::Evaluation &addEvaluation(lower::pft::Evaluation &&eval) {
280     assert(functionList && "not in a function");
281     assert(evaluationListStack.size() > 0);
282     if (constructAndDirectiveStack.size() > 0) {
283       eval.parentConstruct = constructAndDirectiveStack.back();
284     }
285     evaluationListStack.back()->emplace_back(std::move(eval));
286     lower::pft::Evaluation *p = &evaluationListStack.back()->back();
287     if (p->isActionStmt() || p->isConstructStmt()) {
288       if (lastLexicalEvaluation) {
289         lastLexicalEvaluation->lexicalSuccessor = p;
290         p->printIndex = lastLexicalEvaluation->printIndex + 1;
291       } else {
292         p->printIndex = 1;
293       }
294       lastLexicalEvaluation = p;
295     }
296     if (p->label.has_value()) {
297       labelEvaluationMap->try_emplace(*p->label, p);
298     }
299     return evaluationListStack.back()->back();
300   }
301 
302   /// push a new list on the stack of Evaluation lists
303   void pushEvaluationList(lower::pft::EvaluationList *eval) {
304     assert(functionList && "not in a function");
305     assert(eval && eval->empty() && "evaluation list isn't correct");
306     evaluationListStack.emplace_back(eval);
307   }
308 
309   /// pop the current list and return to the last Evaluation list
310   void popEvaluationList() {
311     assert(functionList && "not in a function");
312     evaluationListStack.pop_back();
313   }
314 
315   /// Mark I/O statement ERR, EOR, and END specifier branch targets.
316   template <typename A>
317   void analyzeIoBranches(lower::pft::Evaluation &eval, const A &stmt) {
318     auto processIfLabel{[&](const auto &specs) {
319       using LabelNodes =
320           std::tuple<parser::ErrLabel, parser::EorLabel, parser::EndLabel>;
321       for (const auto &spec : specs) {
322         const auto *label = std::visit(
323             [](const auto &label) -> const parser::Label * {
324               using B = std::decay_t<decltype(label)>;
325               if constexpr (common::HasMember<B, LabelNodes>) {
326                 return &label.v;
327               }
328               return nullptr;
329             },
330             spec.u);
331 
332         if (label)
333           markBranchTarget(eval, *label);
334       }
335     }};
336 
337     using OtherIOStmts =
338         std::tuple<parser::BackspaceStmt, parser::CloseStmt,
339                    parser::EndfileStmt, parser::FlushStmt, parser::OpenStmt,
340                    parser::RewindStmt, parser::WaitStmt>;
341 
342     if constexpr (std::is_same_v<A, parser::ReadStmt> ||
343                   std::is_same_v<A, parser::WriteStmt>) {
344       processIfLabel(stmt.controls);
345     } else if constexpr (std::is_same_v<A, parser::InquireStmt>) {
346       processIfLabel(std::get<std::list<parser::InquireSpec>>(stmt.u));
347     } else if constexpr (common::HasMember<A, OtherIOStmts>) {
348       processIfLabel(stmt.v);
349     } else {
350       // Always crash if this is instantiated
351       static_assert(!std::is_same_v<A, parser::ReadStmt>,
352                     "Unexpected IO statement");
353     }
354   }
355 
356   /// Set the exit of a construct, possibly from multiple enclosing constructs.
357   void setConstructExit(lower::pft::Evaluation &eval) {
358     eval.constructExit = &eval.evaluationList->back().nonNopSuccessor();
359   }
360 
361   /// Mark the target of a branch as a new block.
362   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
363                         lower::pft::Evaluation &targetEvaluation) {
364     sourceEvaluation.isUnstructured = true;
365     if (!sourceEvaluation.controlSuccessor) {
366       sourceEvaluation.controlSuccessor = &targetEvaluation;
367     }
368     targetEvaluation.isNewBlock = true;
369     // If this is a branch into the body of a construct (usually illegal,
370     // but allowed in some legacy cases), then the targetEvaluation and its
371     // ancestors must be marked as unstructured.
372     auto *sourceConstruct = sourceEvaluation.parentConstruct;
373     auto *targetConstruct = targetEvaluation.parentConstruct;
374     if (targetEvaluation.isConstructStmt() &&
375         &targetConstruct->getFirstNestedEvaluation() == &targetEvaluation)
376       // A branch to an initial constructStmt is a branch to the construct.
377       targetConstruct = targetConstruct->parentConstruct;
378     if (targetConstruct) {
379       while (sourceConstruct && sourceConstruct != targetConstruct)
380         sourceConstruct = sourceConstruct->parentConstruct;
381       if (sourceConstruct != targetConstruct)
382         for (auto *eval = &targetEvaluation; eval; eval = eval->parentConstruct)
383           eval->isUnstructured = true;
384     }
385   }
386   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
387                         parser::Label label) {
388     assert(label && "missing branch target label");
389     lower::pft::Evaluation *targetEvaluation{
390         labelEvaluationMap->find(label)->second};
391     assert(targetEvaluation && "missing branch target evaluation");
392     markBranchTarget(sourceEvaluation, *targetEvaluation);
393   }
394 
395   /// Mark the successor of an Evaluation as a new block.
396   void markSuccessorAsNewBlock(lower::pft::Evaluation &eval) {
397     eval.nonNopSuccessor().isNewBlock = true;
398   }
399 
400   template <typename A>
401   inline std::string getConstructName(const A &stmt) {
402     using MaybeConstructNameWrapper =
403         std::tuple<parser::BlockStmt, parser::CycleStmt, parser::ElseStmt,
404                    parser::ElsewhereStmt, parser::EndAssociateStmt,
405                    parser::EndBlockStmt, parser::EndCriticalStmt,
406                    parser::EndDoStmt, parser::EndForallStmt, parser::EndIfStmt,
407                    parser::EndSelectStmt, parser::EndWhereStmt,
408                    parser::ExitStmt>;
409     if constexpr (common::HasMember<A, MaybeConstructNameWrapper>) {
410       if (stmt.v)
411         return stmt.v->ToString();
412     }
413 
414     using MaybeConstructNameInTuple = std::tuple<
415         parser::AssociateStmt, parser::CaseStmt, parser::ChangeTeamStmt,
416         parser::CriticalStmt, parser::ElseIfStmt, parser::EndChangeTeamStmt,
417         parser::ForallConstructStmt, parser::IfThenStmt, parser::LabelDoStmt,
418         parser::MaskedElsewhereStmt, parser::NonLabelDoStmt,
419         parser::SelectCaseStmt, parser::SelectRankCaseStmt,
420         parser::TypeGuardStmt, parser::WhereConstructStmt>;
421 
422     if constexpr (common::HasMember<A, MaybeConstructNameInTuple>) {
423       if (auto name{std::get<std::optional<parser::Name>>(stmt.t)})
424         return name->ToString();
425     }
426 
427     // These statements have several std::optional<parser::Name>
428     if constexpr (std::is_same_v<A, parser::SelectRankStmt> ||
429                   std::is_same_v<A, parser::SelectTypeStmt>) {
430       if (auto name{std::get<0>(stmt.t)}) {
431         return name->ToString();
432       }
433     }
434     return {};
435   }
436 
437   /// \p parentConstruct can be null if this statement is at the highest
438   /// level of a program.
439   template <typename A>
440   void insertConstructName(const A &stmt,
441                            lower::pft::Evaluation *parentConstruct) {
442     std::string name{getConstructName(stmt)};
443     if (!name.empty()) {
444       constructNameMap[name] = parentConstruct;
445     }
446   }
447 
448   /// Insert branch links for a list of Evaluations.
449   /// \p parentConstruct can be null if the evaluationList contains the
450   /// top-level statements of a program.
451   void analyzeBranches(lower::pft::Evaluation *parentConstruct,
452                        std::list<lower::pft::Evaluation> &evaluationList) {
453     lower::pft::Evaluation *lastConstructStmtEvaluation{nullptr};
454     lower::pft::Evaluation *lastIfStmtEvaluation{nullptr};
455     for (auto &eval : evaluationList) {
456       eval.visit(common::visitors{
457           // Action statements
458           [&](const parser::CallStmt &s) {
459             // Look for alternate return specifiers.
460             const auto &args{std::get<std::list<parser::ActualArgSpec>>(s.v.t)};
461             for (const auto &arg : args) {
462               const auto &actual{std::get<parser::ActualArg>(arg.t)};
463               if (const auto *altReturn{
464                       std::get_if<parser::AltReturnSpec>(&actual.u)}) {
465                 markBranchTarget(eval, altReturn->v);
466               }
467             }
468           },
469           [&](const parser::CycleStmt &s) {
470             std::string name{getConstructName(s)};
471             lower::pft::Evaluation *construct{name.empty()
472                                                   ? doConstructStack.back()
473                                                   : constructNameMap[name]};
474             assert(construct && "missing CYCLE construct");
475             markBranchTarget(eval, construct->evaluationList->back());
476           },
477           [&](const parser::ExitStmt &s) {
478             std::string name{getConstructName(s)};
479             lower::pft::Evaluation *construct{name.empty()
480                                                   ? doConstructStack.back()
481                                                   : constructNameMap[name]};
482             assert(construct && "missing EXIT construct");
483             markBranchTarget(eval, *construct->constructExit);
484           },
485           [&](const parser::GotoStmt &s) { markBranchTarget(eval, s.v); },
486           [&](const parser::IfStmt &) { lastIfStmtEvaluation = &eval; },
487           [&](const parser::ReturnStmt &) {
488             eval.isUnstructured = true;
489             if (eval.lexicalSuccessor->lexicalSuccessor)
490               markSuccessorAsNewBlock(eval);
491           },
492           [&](const parser::StopStmt &) {
493             eval.isUnstructured = true;
494             if (eval.lexicalSuccessor->lexicalSuccessor)
495               markSuccessorAsNewBlock(eval);
496           },
497           [&](const parser::ComputedGotoStmt &s) {
498             for (auto &label : std::get<std::list<parser::Label>>(s.t)) {
499               markBranchTarget(eval, label);
500             }
501           },
502           [&](const parser::ArithmeticIfStmt &s) {
503             markBranchTarget(eval, std::get<1>(s.t));
504             markBranchTarget(eval, std::get<2>(s.t));
505             markBranchTarget(eval, std::get<3>(s.t));
506             if (semantics::ExprHasTypeCategory(
507                     *semantics::GetExpr(std::get<parser::Expr>(s.t)),
508                     common::TypeCategory::Real)) {
509               // Real expression evaluation uses an additional local block.
510               eval.localBlocks.emplace_back(nullptr);
511             }
512           },
513           [&](const parser::AssignStmt &s) { // legacy label assignment
514             auto &label = std::get<parser::Label>(s.t);
515             const auto *sym = std::get<parser::Name>(s.t).symbol;
516             assert(sym && "missing AssignStmt symbol");
517             lower::pft::Evaluation *target{
518                 labelEvaluationMap->find(label)->second};
519             assert(target && "missing branch target evaluation");
520             if (!target->isA<parser::FormatStmt>()) {
521               target->isNewBlock = true;
522             }
523             auto iter = assignSymbolLabelMap->find(*sym);
524             if (iter == assignSymbolLabelMap->end()) {
525               lower::pft::LabelSet labelSet{};
526               labelSet.insert(label);
527               assignSymbolLabelMap->try_emplace(*sym, labelSet);
528             } else {
529               iter->second.insert(label);
530             }
531           },
532           [&](const parser::AssignedGotoStmt &) {
533             // Although this statement is a branch, it doesn't have any
534             // explicit control successors.  So the code at the end of the
535             // loop won't mark the successor.  Do that here.
536             eval.isUnstructured = true;
537             markSuccessorAsNewBlock(eval);
538           },
539 
540           // Construct statements
541           [&](const parser::AssociateStmt &s) {
542             insertConstructName(s, parentConstruct);
543           },
544           [&](const parser::BlockStmt &s) {
545             insertConstructName(s, parentConstruct);
546           },
547           [&](const parser::SelectCaseStmt &s) {
548             insertConstructName(s, parentConstruct);
549             lastConstructStmtEvaluation = &eval;
550           },
551           [&](const parser::CaseStmt &) {
552             eval.isNewBlock = true;
553             lastConstructStmtEvaluation->controlSuccessor = &eval;
554             lastConstructStmtEvaluation = &eval;
555           },
556           [&](const parser::EndSelectStmt &) {
557             eval.nonNopSuccessor().isNewBlock = true;
558             lastConstructStmtEvaluation = nullptr;
559           },
560           [&](const parser::ChangeTeamStmt &s) {
561             insertConstructName(s, parentConstruct);
562           },
563           [&](const parser::CriticalStmt &s) {
564             insertConstructName(s, parentConstruct);
565           },
566           [&](const parser::NonLabelDoStmt &s) {
567             insertConstructName(s, parentConstruct);
568             doConstructStack.push_back(parentConstruct);
569             auto &control{std::get<std::optional<parser::LoopControl>>(s.t)};
570             // eval.block is the loop preheader block, which will be set
571             // elsewhere if the NonLabelDoStmt is itself a target.
572             // eval.localBlocks[0] is the loop header block.
573             eval.localBlocks.emplace_back(nullptr);
574             if (!control.has_value()) {
575               eval.isUnstructured = true; // infinite loop
576               return;
577             }
578             eval.nonNopSuccessor().isNewBlock = true;
579             eval.controlSuccessor = &evaluationList.back();
580             if (std::holds_alternative<parser::ScalarLogicalExpr>(control->u)) {
581               eval.isUnstructured = true; // while loop
582             }
583             // Defer additional processing for an unstructured concurrent loop
584             // to the EndDoStmt, when the loop is known to be unstructured.
585           },
586           [&](const parser::EndDoStmt &) {
587             lower::pft::Evaluation &doEval{evaluationList.front()};
588             eval.controlSuccessor = &doEval;
589             doConstructStack.pop_back();
590             if (parentConstruct->lowerAsStructured()) {
591               return;
592             }
593             // Now that the loop is known to be unstructured, finish concurrent
594             // loop processing, using NonLabelDoStmt information.
595             parentConstruct->constructExit->isNewBlock = true;
596             const auto &doStmt{doEval.getIf<parser::NonLabelDoStmt>()};
597             assert(doStmt && "missing NonLabelDoStmt");
598             auto &control{
599                 std::get<std::optional<parser::LoopControl>>(doStmt->t)};
600             if (!control.has_value()) {
601               return; // infinite loop
602             }
603             const auto *concurrent{
604                 std::get_if<parser::LoopControl::Concurrent>(&control->u)};
605             if (!concurrent) {
606               return;
607             }
608             // Unstructured concurrent loop.  NonLabelDoStmt code accounts
609             // for one concurrent loop dimension.  Reserve preheader,
610             // header, and latch blocks for the remaining dimensions, and
611             // one block for a mask expression.
612             const auto &header{
613                 std::get<parser::ConcurrentHeader>(concurrent->t)};
614             auto dims{std::get<std::list<parser::ConcurrentControl>>(header.t)
615                           .size()};
616             for (; dims > 1; --dims) {
617               doEval.localBlocks.emplace_back(nullptr); // preheader
618               doEval.localBlocks.emplace_back(nullptr); // header
619               eval.localBlocks.emplace_back(nullptr);   // latch
620             }
621             if (std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)) {
622               doEval.localBlocks.emplace_back(nullptr); // mask
623             }
624           },
625           [&](const parser::IfThenStmt &s) {
626             insertConstructName(s, parentConstruct);
627             eval.lexicalSuccessor->isNewBlock = true;
628             lastConstructStmtEvaluation = &eval;
629           },
630           [&](const parser::ElseIfStmt &) {
631             eval.isNewBlock = true;
632             eval.lexicalSuccessor->isNewBlock = true;
633             lastConstructStmtEvaluation->controlSuccessor = &eval;
634             lastConstructStmtEvaluation = &eval;
635           },
636           [&](const parser::ElseStmt &) {
637             eval.isNewBlock = true;
638             lastConstructStmtEvaluation->controlSuccessor = &eval;
639             lastConstructStmtEvaluation = nullptr;
640           },
641           [&](const parser::EndIfStmt &) {
642             if (parentConstruct->lowerAsUnstructured()) {
643               parentConstruct->constructExit->isNewBlock = true;
644             }
645             if (lastConstructStmtEvaluation) {
646               lastConstructStmtEvaluation->controlSuccessor =
647                   parentConstruct->constructExit;
648               lastConstructStmtEvaluation = nullptr;
649             }
650           },
651           [&](const parser::SelectRankStmt &s) {
652             insertConstructName(s, parentConstruct);
653           },
654           [&](const parser::SelectRankCaseStmt &) { eval.isNewBlock = true; },
655           [&](const parser::SelectTypeStmt &s) {
656             insertConstructName(s, parentConstruct);
657           },
658           [&](const parser::TypeGuardStmt &) { eval.isNewBlock = true; },
659 
660           // Constructs - set (unstructured) construct exit targets
661           [&](const parser::AssociateConstruct &) { setConstructExit(eval); },
662           [&](const parser::BlockConstruct &) {
663             // EndBlockStmt may have code.
664             eval.constructExit = &eval.evaluationList->back();
665           },
666           [&](const parser::CaseConstruct &) {
667             setConstructExit(eval);
668             eval.isUnstructured = true;
669           },
670           [&](const parser::ChangeTeamConstruct &) {
671             // EndChangeTeamStmt may have code.
672             eval.constructExit = &eval.evaluationList->back();
673           },
674           [&](const parser::CriticalConstruct &) {
675             // EndCriticalStmt may have code.
676             eval.constructExit = &eval.evaluationList->back();
677           },
678           [&](const parser::DoConstruct &) { setConstructExit(eval); },
679           [&](const parser::IfConstruct &) { setConstructExit(eval); },
680           [&](const parser::SelectRankConstruct &) {
681             setConstructExit(eval);
682             eval.isUnstructured = true;
683           },
684           [&](const parser::SelectTypeConstruct &) {
685             setConstructExit(eval);
686             eval.isUnstructured = true;
687           },
688 
689           [&](const auto &stmt) {
690             using A = std::decay_t<decltype(stmt)>;
691             using IoStmts = std::tuple<parser::BackspaceStmt, parser::CloseStmt,
692                                        parser::EndfileStmt, parser::FlushStmt,
693                                        parser::InquireStmt, parser::OpenStmt,
694                                        parser::ReadStmt, parser::RewindStmt,
695                                        parser::WaitStmt, parser::WriteStmt>;
696             if constexpr (common::HasMember<A, IoStmts>) {
697               analyzeIoBranches(eval, stmt);
698             }
699 
700             /* do nothing */
701           },
702       });
703 
704       // Analyze construct evaluations.
705       if (eval.evaluationList) {
706         analyzeBranches(&eval, *eval.evaluationList);
707       }
708 
709       // Insert branch links for an unstructured IF statement.
710       if (lastIfStmtEvaluation && lastIfStmtEvaluation != &eval) {
711         // eval is the action substatement of an IfStmt.
712         if (eval.lowerAsUnstructured()) {
713           eval.isNewBlock = true;
714           markSuccessorAsNewBlock(eval);
715           lastIfStmtEvaluation->isUnstructured = true;
716         }
717         lastIfStmtEvaluation->controlSuccessor = &eval.nonNopSuccessor();
718         lastIfStmtEvaluation = nullptr;
719       }
720 
721       // Set the successor of the last statement in an IF or SELECT block.
722       if (!eval.controlSuccessor && eval.lexicalSuccessor &&
723           eval.lexicalSuccessor->isIntermediateConstructStmt()) {
724         eval.controlSuccessor = parentConstruct->constructExit;
725         eval.lexicalSuccessor->isNewBlock = true;
726       }
727 
728       // Propagate isUnstructured flag to enclosing construct.
729       if (parentConstruct && eval.isUnstructured) {
730         parentConstruct->isUnstructured = true;
731       }
732 
733       // The successor of a branch starts a new block.
734       if (eval.controlSuccessor && eval.isActionStmt() &&
735           eval.lowerAsUnstructured()) {
736         markSuccessorAsNewBlock(eval);
737       }
738     }
739   }
740 
741   std::unique_ptr<lower::pft::Program> pgm;
742   std::vector<lower::pft::ParentVariant> parentVariantStack;
743   const semantics::SemanticsContext &semanticsContext;
744 
745   /// functionList points to the internal or module procedure function list
746   /// of a FunctionLikeUnit or a ModuleLikeUnit.  It may be null.
747   std::list<lower::pft::FunctionLikeUnit> *functionList{nullptr};
748   std::vector<lower::pft::Evaluation *> constructAndDirectiveStack{};
749   std::vector<lower::pft::Evaluation *> doConstructStack{};
750   /// evaluationListStack is the current nested construct evaluationList state.
751   std::vector<lower::pft::EvaluationList *> evaluationListStack{};
752   llvm::DenseMap<parser::Label, lower::pft::Evaluation *> *labelEvaluationMap{
753       nullptr};
754   lower::pft::SymbolLabelMap *assignSymbolLabelMap{nullptr};
755   std::map<std::string, lower::pft::Evaluation *> constructNameMap{};
756   lower::pft::Evaluation *lastLexicalEvaluation{nullptr};
757 };
758 
759 class PFTDumper {
760 public:
761   void dumpPFT(llvm::raw_ostream &outputStream, lower::pft::Program &pft) {
762     for (auto &unit : pft.getUnits()) {
763       std::visit(common::visitors{
764                      [&](lower::pft::BlockDataUnit &unit) {
765                        outputStream << getNodeIndex(unit) << " ";
766                        outputStream << "BlockData: ";
767                        outputStream << "\nEndBlockData\n\n";
768                      },
769                      [&](lower::pft::FunctionLikeUnit &func) {
770                        dumpFunctionLikeUnit(outputStream, func);
771                      },
772                      [&](lower::pft::ModuleLikeUnit &unit) {
773                        dumpModuleLikeUnit(outputStream, unit);
774                      },
775                  },
776                  unit);
777     }
778   }
779 
780   llvm::StringRef evaluationName(lower::pft::Evaluation &eval) {
781     return eval.visit(common::visitors{
782         [](const auto &parseTreeNode) {
783           return parser::ParseTreeDumper::GetNodeName(parseTreeNode);
784         },
785     });
786   }
787 
788   void dumpEvaluationList(llvm::raw_ostream &outputStream,
789                           lower::pft::EvaluationList &evaluationList,
790                           int indent = 1) {
791     static const std::string white{"                                      ++"};
792     std::string indentString{white.substr(0, indent * 2)};
793     for (lower::pft::Evaluation &eval : evaluationList) {
794       llvm::StringRef name{evaluationName(eval)};
795       std::string bang{eval.isUnstructured ? "!" : ""};
796       if (eval.isConstruct() || eval.isDirective()) {
797         outputStream << indentString << "<<" << name << bang << ">>";
798         if (eval.constructExit) {
799           outputStream << " -> " << eval.constructExit->printIndex;
800         }
801         outputStream << '\n';
802         dumpEvaluationList(outputStream, *eval.evaluationList, indent + 1);
803         outputStream << indentString << "<<End " << name << bang << ">>\n";
804         continue;
805       }
806       outputStream << indentString;
807       if (eval.printIndex) {
808         outputStream << eval.printIndex << ' ';
809       }
810       if (eval.isNewBlock) {
811         outputStream << '^';
812       }
813       if (eval.localBlocks.size()) {
814         outputStream << '*';
815       }
816       outputStream << name << bang;
817       if (eval.isActionStmt() || eval.isConstructStmt()) {
818         if (eval.controlSuccessor) {
819           outputStream << " -> " << eval.controlSuccessor->printIndex;
820         }
821       }
822       if (eval.position.size()) {
823         outputStream << ": " << eval.position.ToString();
824       }
825       outputStream << '\n';
826     }
827   }
828 
829   void dumpFunctionLikeUnit(llvm::raw_ostream &outputStream,
830                             lower::pft::FunctionLikeUnit &functionLikeUnit) {
831     outputStream << getNodeIndex(functionLikeUnit) << " ";
832     llvm::StringRef unitKind{};
833     std::string name{};
834     std::string header{};
835     if (functionLikeUnit.beginStmt) {
836       functionLikeUnit.beginStmt->visit(common::visitors{
837           [&](const parser::Statement<parser::ProgramStmt> &statement) {
838             unitKind = "Program";
839             name = statement.statement.v.ToString();
840           },
841           [&](const parser::Statement<parser::FunctionStmt> &statement) {
842             unitKind = "Function";
843             name = std::get<parser::Name>(statement.statement.t).ToString();
844             header = statement.source.ToString();
845           },
846           [&](const parser::Statement<parser::SubroutineStmt> &statement) {
847             unitKind = "Subroutine";
848             name = std::get<parser::Name>(statement.statement.t).ToString();
849             header = statement.source.ToString();
850           },
851           [&](const parser::Statement<parser::MpSubprogramStmt> &statement) {
852             unitKind = "MpSubprogram";
853             name = statement.statement.v.ToString();
854             header = statement.source.ToString();
855           },
856           [&](const auto &) {},
857       });
858     } else {
859       unitKind = "Program";
860       name = "<anonymous>";
861     }
862     outputStream << unitKind << ' ' << name;
863     if (header.size())
864       outputStream << ": " << header;
865     outputStream << '\n';
866     dumpEvaluationList(outputStream, functionLikeUnit.evaluationList);
867     if (!functionLikeUnit.nestedFunctions.empty()) {
868       outputStream << "\nContains\n";
869       for (auto &func : functionLikeUnit.nestedFunctions)
870         dumpFunctionLikeUnit(outputStream, func);
871       outputStream << "EndContains\n";
872     }
873     outputStream << "End" << unitKind << ' ' << name << "\n\n";
874   }
875 
876   void dumpModuleLikeUnit(llvm::raw_ostream &outputStream,
877                           lower::pft::ModuleLikeUnit &moduleLikeUnit) {
878     outputStream << getNodeIndex(moduleLikeUnit) << " ";
879     outputStream << "ModuleLike: ";
880     outputStream << "\nContains\n";
881     for (auto &func : moduleLikeUnit.nestedFunctions)
882       dumpFunctionLikeUnit(outputStream, func);
883     outputStream << "EndContains\nEndModuleLike\n\n";
884   }
885 
886   template <typename T>
887   std::size_t getNodeIndex(const T &node) {
888     auto addr{static_cast<const void *>(&node)};
889     auto it{nodeIndexes.find(addr)};
890     if (it != nodeIndexes.end()) {
891       return it->second;
892     }
893     nodeIndexes.try_emplace(addr, nextIndex);
894     return nextIndex++;
895   }
896   std::size_t getNodeIndex(const lower::pft::Program &) { return 0; }
897 
898 private:
899   llvm::DenseMap<const void *, std::size_t> nodeIndexes;
900   std::size_t nextIndex{1}; // 0 is the root
901 };
902 
903 } // namespace
904 
905 template <typename A, typename T>
906 static lower::pft::FunctionLikeUnit::FunctionStatement
907 getFunctionStmt(const T &func) {
908   return std::get<parser::Statement<A>>(func.t);
909 }
910 template <typename A, typename T>
911 static lower::pft::ModuleLikeUnit::ModuleStatement getModuleStmt(const T &mod) {
912   return std::get<parser::Statement<A>>(mod.t);
913 }
914 
915 static const semantics::Symbol *getSymbol(
916     std::optional<lower::pft::FunctionLikeUnit::FunctionStatement> &beginStmt) {
917   if (!beginStmt)
918     return nullptr;
919 
920   const auto *symbol = beginStmt->visit(common::visitors{
921       [](const parser::Statement<parser::ProgramStmt> &stmt)
922           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
923       [](const parser::Statement<parser::FunctionStmt> &stmt)
924           -> const semantics::Symbol * {
925         return std::get<parser::Name>(stmt.statement.t).symbol;
926       },
927       [](const parser::Statement<parser::SubroutineStmt> &stmt)
928           -> const semantics::Symbol * {
929         return std::get<parser::Name>(stmt.statement.t).symbol;
930       },
931       [](const parser::Statement<parser::MpSubprogramStmt> &stmt)
932           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
933       [](const auto &) -> const semantics::Symbol * {
934         llvm_unreachable("unknown FunctionLike beginStmt");
935         return nullptr;
936       }});
937   assert(symbol && "parser::Name must have resolved symbol");
938   return symbol;
939 }
940 
941 bool Fortran::lower::pft::Evaluation::lowerAsStructured() const {
942   return !lowerAsUnstructured();
943 }
944 
945 bool Fortran::lower::pft::Evaluation::lowerAsUnstructured() const {
946   return isUnstructured || clDisableStructuredFir;
947 }
948 
949 lower::pft::FunctionLikeUnit *
950 Fortran::lower::pft::Evaluation::getOwningProcedure() const {
951   return parentVariant.visit(common::visitors{
952       [](lower::pft::FunctionLikeUnit &c) { return &c; },
953       [&](lower::pft::Evaluation &c) { return c.getOwningProcedure(); },
954       [](auto &) -> lower::pft::FunctionLikeUnit * { return nullptr; },
955   });
956 }
957 
958 namespace {
959 /// This helper class is for sorting the symbols in the symbol table. We want
960 /// the symbols in an order such that a symbol will be visited after those it
961 /// depends upon. Otherwise this sort is stable and preserves the order of the
962 /// symbol table, which is sorted by name.
963 struct SymbolDependenceDepth {
964   explicit SymbolDependenceDepth(
965       std::vector<std::vector<lower::pft::Variable>> &vars)
966       : vars{vars} {}
967 
968   // Recursively visit each symbol to determine the height of its dependence on
969   // other symbols.
970   int analyze(const semantics::Symbol &sym) {
971     auto done = seen.insert(&sym);
972     if (!done.second)
973       return 0;
974     if (semantics::IsProcedure(sym)) {
975       // TODO: add declaration?
976       return 0;
977     }
978     if (sym.has<semantics::UseDetails>() ||
979         sym.has<semantics::HostAssocDetails>() ||
980         sym.has<semantics::NamelistDetails>() ||
981         sym.has<semantics::MiscDetails>()) {
982       // FIXME: do we want to do anything with any of these?
983       return 0;
984     }
985 
986     // Symbol must be something lowering will have to allocate.
987     bool global = semantics::IsSaved(sym);
988     int depth = 0;
989     const auto *symTy = sym.GetType();
990     assert(symTy && "symbol must have a type");
991 
992     // check CHARACTER's length
993     if (symTy->category() == semantics::DeclTypeSpec::Character)
994       if (auto e = symTy->characterTypeSpec().length().GetExplicit())
995         for (const auto &s : evaluate::CollectSymbols(*e))
996           depth = std::max(analyze(s) + 1, depth);
997 
998     if (const auto *details = sym.detailsIf<semantics::ObjectEntityDetails>()) {
999       auto doExplicit = [&](const auto &bound) {
1000         if (bound.isExplicit()) {
1001           semantics::SomeExpr e{*bound.GetExplicit()};
1002           for (const auto &s : evaluate::CollectSymbols(e))
1003             depth = std::max(analyze(s) + 1, depth);
1004         }
1005       };
1006       // handle any symbols in array bound declarations
1007       for (const auto &subs : details->shape()) {
1008         doExplicit(subs.lbound());
1009         doExplicit(subs.ubound());
1010       }
1011       // handle any symbols in coarray bound declarations
1012       for (const auto &subs : details->coshape()) {
1013         doExplicit(subs.lbound());
1014         doExplicit(subs.ubound());
1015       }
1016       // handle any symbols in initialization expressions
1017       if (auto e = details->init()) {
1018         // A PARAMETER may not be marked as implicitly SAVE, so set the flag.
1019         global = true;
1020         for (const auto &s : evaluate::CollectSymbols(*e))
1021           depth = std::max(analyze(s) + 1, depth);
1022       }
1023     }
1024     adjustSize(depth + 1);
1025     vars[depth].emplace_back(sym, global, depth);
1026     if (Fortran::semantics::IsAllocatable(sym))
1027       vars[depth].back().setHeapAlloc();
1028     if (Fortran::semantics::IsPointer(sym))
1029       vars[depth].back().setPointer();
1030     if (sym.attrs().test(Fortran::semantics::Attr::TARGET))
1031       vars[depth].back().setTarget();
1032     return depth;
1033   }
1034 
1035   // Save the final list of symbols as a single vector and free the rest.
1036   void finalize() {
1037     for (int i = 1, end = vars.size(); i < end; ++i)
1038       vars[0].insert(vars[0].end(), vars[i].begin(), vars[i].end());
1039     vars.resize(1);
1040   }
1041 
1042 private:
1043   // Make sure the table is of appropriate size.
1044   void adjustSize(std::size_t size) {
1045     if (vars.size() < size)
1046       vars.resize(size);
1047   }
1048 
1049   llvm::SmallSet<const semantics::Symbol *, 32> seen;
1050   std::vector<std::vector<lower::pft::Variable>> &vars;
1051 };
1052 } // namespace
1053 
1054 void Fortran::lower::pft::FunctionLikeUnit::processSymbolTable(
1055     const semantics::Scope &scope) {
1056   // TODO: handle equivalence and common blocks
1057   if (!scope.equivalenceSets().empty()) {
1058     llvm::errs() << "TODO: equivalence not yet handled in lowering.\n"
1059                  << "note: equivalence used in "
1060                  << (scope.GetName() && !scope.GetName()->empty()
1061                          ? scope.GetName()->ToString()
1062                          : "unnamed program"s)
1063                  << "\n";
1064     exit(1);
1065   }
1066   SymbolDependenceDepth sdd{varList};
1067   for (const auto &iter : scope)
1068     sdd.analyze(iter.second.get());
1069   sdd.finalize();
1070 }
1071 
1072 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1073     const parser::MainProgram &func, const lower::pft::ParentVariant &parent,
1074     const semantics::SemanticsContext &semanticsContext)
1075     : ProgramUnit{func, parent}, endStmt{
1076                                      getFunctionStmt<parser::EndProgramStmt>(
1077                                          func)} {
1078   const auto &ps{
1079       std::get<std::optional<parser::Statement<parser::ProgramStmt>>>(func.t)};
1080   if (ps.has_value()) {
1081     beginStmt = ps.value();
1082     symbol = getSymbol(beginStmt);
1083     processSymbolTable(*symbol->scope());
1084   } else {
1085     processSymbolTable(semanticsContext.FindScope(
1086         std::get<parser::Statement<parser::EndProgramStmt>>(func.t).source));
1087   }
1088 }
1089 
1090 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1091     const parser::FunctionSubprogram &func,
1092     const lower::pft::ParentVariant &parent,
1093     const semantics::SemanticsContext &)
1094     : ProgramUnit{func, parent},
1095       beginStmt{getFunctionStmt<parser::FunctionStmt>(func)},
1096       endStmt{getFunctionStmt<parser::EndFunctionStmt>(func)}, symbol{getSymbol(
1097                                                                    beginStmt)} {
1098   processSymbolTable(*symbol->scope());
1099 }
1100 
1101 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1102     const parser::SubroutineSubprogram &func,
1103     const lower::pft::ParentVariant &parent,
1104     const semantics::SemanticsContext &)
1105     : ProgramUnit{func, parent},
1106       beginStmt{getFunctionStmt<parser::SubroutineStmt>(func)},
1107       endStmt{getFunctionStmt<parser::EndSubroutineStmt>(func)},
1108       symbol{getSymbol(beginStmt)} {
1109   processSymbolTable(*symbol->scope());
1110 }
1111 
1112 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1113     const parser::SeparateModuleSubprogram &func,
1114     const lower::pft::ParentVariant &parent,
1115     const semantics::SemanticsContext &)
1116     : ProgramUnit{func, parent},
1117       beginStmt{getFunctionStmt<parser::MpSubprogramStmt>(func)},
1118       endStmt{getFunctionStmt<parser::EndMpSubprogramStmt>(func)},
1119       symbol{getSymbol(beginStmt)} {
1120   processSymbolTable(*symbol->scope());
1121 }
1122 
1123 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1124     const parser::Module &m, const lower::pft::ParentVariant &parent)
1125     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::ModuleStmt>(m)},
1126       endStmt{getModuleStmt<parser::EndModuleStmt>(m)} {}
1127 
1128 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1129     const parser::Submodule &m, const lower::pft::ParentVariant &parent)
1130     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::SubmoduleStmt>(
1131                                   m)},
1132       endStmt{getModuleStmt<parser::EndSubmoduleStmt>(m)} {}
1133 
1134 Fortran::lower::pft::BlockDataUnit::BlockDataUnit(
1135     const parser::BlockData &bd, const lower::pft::ParentVariant &parent)
1136     : ProgramUnit{bd, parent} {}
1137 
1138 std::unique_ptr<lower::pft::Program>
1139 Fortran::lower::createPFT(const parser::Program &root,
1140                           const semantics::SemanticsContext &semanticsContext) {
1141   PFTBuilder walker(semanticsContext);
1142   Walk(root, walker);
1143   return walker.result();
1144 }
1145 
1146 void Fortran::lower::dumpPFT(llvm::raw_ostream &outputStream,
1147                              lower::pft::Program &pft) {
1148   PFTDumper{}.dumpPFT(outputStream, pft);
1149 }
1150 
1151 void Fortran::lower::pft::Program::dump() { dumpPFT(llvm::errs(), *this); }
1152