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;
UnwrapStmt__anon431f4f760111::UnwrapStmt62   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;
UnwrapStmt__anon431f4f760111::UnwrapStmt73   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:
PFTBuilder(const semantics::SemanticsContext & semanticsContext)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
result()94   std::unique_ptr<lower::pft::Program> result() { return std::move(pgm); }
95 
96   template <typename A>
Pre(const A & 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.
convertIfStmt(const parser::IfStmt & ifStmt,parser::CharBlock position,std::optional<parser::Label> label)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>
Post(const 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
Pre(const parser::Module & node)176   bool Pre(const parser::Module &node) { return enterModule(node); }
Pre(const parser::Submodule & node)177   bool Pre(const parser::Submodule &node) { return enterModule(node); }
178 
Post(const parser::Module &)179   void Post(const parser::Module &) { exitModule(); }
Post(const parser::Submodule &)180   void Post(const parser::Submodule &) { exitModule(); }
181 
182   // Block data
Pre(const parser::BlockData & node)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
Pre(const parser::Statement<parser::ForallAssignmentStmt> & statement)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   }
Pre(const parser::WhereBodyConstruct & whereBody)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).
Pre(const parser::CompilerDirective & directive)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>
enterModule(const A & func)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 
exitModule()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.
endFunctionBody()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.
cleanModuleEvaluationList()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>
enterFunction(const A & func,const semantics::SemanticsContext & semanticsContext)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 
exitFunction()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>
enterConstructOrDirective(const A & constructOrDirective)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 
exitConstructOrDirective()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.
resetFunctionState()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>
addUnit(A && unit)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>
addFunction(A && func)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
makeEvaluationAction(const parser::ActionStmt & statement,parser::CharBlock position,std::optional<parser::Label> label)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.
addEvaluation(lower::pft::Evaluation && eval)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
pushEvaluationList(lower::pft::EvaluationList * evaluationList)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
popEvaluationList()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   ///
rewriteIfGotos()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>
analyzeIoBranches(lower::pft::Evaluation & eval,const A & stmt)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.
setConstructExit(lower::pft::Evaluation & eval)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.
markBranchTarget(lower::pft::Evaluation & sourceEvaluation,lower::pft::Evaluation & targetEvaluation)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   }
markBranchTarget(lower::pft::Evaluation & sourceEvaluation,parser::Label label)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.
markSuccessorAsNewBlock(lower::pft::Evaluation & eval)671   void markSuccessorAsNewBlock(lower::pft::Evaluation &eval) {
672     eval.nonNopSuccessor().isNewBlock = true;
673   }
674 
675   template <typename A>
getConstructName(const A & stmt)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>
insertConstructName(const A & stmt,lower::pft::Evaluation * parentConstruct)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.
analyzeBranches(lower::pft::Evaluation * parentConstruct,std::list<lower::pft::Evaluation> & evaluationList)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::ForallConstruct &) { setConstructExit(eval); },
943           [&](const parser::IfConstruct &) { setConstructExit(eval); },
944           [&](const parser::SelectRankConstruct &) {
945             setConstructExit(eval);
946             eval.isUnstructured = true;
947           },
948           [&](const parser::SelectTypeConstruct &) {
949             setConstructExit(eval);
950             eval.isUnstructured = true;
951           },
952           [&](const parser::WhereConstruct &) { setConstructExit(eval); },
953 
954           // Default - Common analysis for IO statements; otherwise nop.
955           [&](const auto &stmt) {
956             using A = std::decay_t<decltype(stmt)>;
957             using IoStmts = std::tuple<
958                 parser::BackspaceStmt, parser::CloseStmt, parser::EndfileStmt,
959                 parser::FlushStmt, parser::InquireStmt, parser::OpenStmt,
960                 parser::PrintStmt, parser::ReadStmt, parser::RewindStmt,
961                 parser::WaitStmt, parser::WriteStmt>;
962             if constexpr (common::HasMember<A, IoStmts>)
963               analyzeIoBranches(eval, stmt);
964           },
965       });
966 
967       // Analyze construct evaluations.
968       if (eval.evaluationList)
969         analyzeBranches(&eval, *eval.evaluationList);
970 
971       // Set the successor of the last statement in an IF or SELECT block.
972       if (!eval.controlSuccessor && eval.lexicalSuccessor &&
973           eval.lexicalSuccessor->isIntermediateConstructStmt()) {
974         eval.controlSuccessor = parentConstruct->constructExit;
975         eval.lexicalSuccessor->isNewBlock = true;
976       }
977 
978       // Propagate isUnstructured flag to enclosing construct.
979       if (parentConstruct && eval.isUnstructured)
980         parentConstruct->isUnstructured = true;
981 
982       // The successor of a branch starts a new block.
983       if (eval.controlSuccessor && eval.isActionStmt() &&
984           eval.lowerAsUnstructured())
985         markSuccessorAsNewBlock(eval);
986     }
987   }
988 
989   /// Do processing specific to subprograms with multiple entry points.
processEntryPoints()990   void processEntryPoints() {
991     lower::pft::Evaluation *initialEval = &evaluationListStack.back()->front();
992     lower::pft::FunctionLikeUnit *unit = initialEval->getOwningProcedure();
993     int entryCount = unit->entryPointList.size();
994     if (entryCount == 1)
995       return;
996 
997     // The first executable statement in the subprogram is preceded by a
998     // branch to the entry point, so it starts a new block.
999     if (initialEval->hasNestedEvaluations())
1000       initialEval = &initialEval->getFirstNestedEvaluation();
1001     else if (initialEval->isA<Fortran::parser::EntryStmt>())
1002       initialEval = initialEval->lexicalSuccessor;
1003     initialEval->isNewBlock = true;
1004 
1005     // All function entry points share a single result container.
1006     // Find one of the largest results.
1007     for (int entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
1008       unit->setActiveEntry(entryIndex);
1009       const auto &details =
1010           unit->getSubprogramSymbol().get<semantics::SubprogramDetails>();
1011       if (details.isFunction()) {
1012         const semantics::Symbol *resultSym = &details.result();
1013         assert(resultSym && "missing result symbol");
1014         if (!unit->primaryResult ||
1015             unit->primaryResult->size() < resultSym->size())
1016           unit->primaryResult = resultSym;
1017       }
1018     }
1019     unit->setActiveEntry(0);
1020   }
1021 
1022   std::unique_ptr<lower::pft::Program> pgm;
1023   std::vector<lower::pft::PftNode> pftParentStack;
1024   const semantics::SemanticsContext &semanticsContext;
1025 
1026   /// functionList points to the internal or module procedure function list
1027   /// of a FunctionLikeUnit or a ModuleLikeUnit.  It may be null.
1028   std::list<lower::pft::FunctionLikeUnit> *functionList{};
1029   std::vector<lower::pft::Evaluation *> constructAndDirectiveStack{};
1030   std::vector<lower::pft::Evaluation *> doConstructStack{};
1031   /// evaluationListStack is the current nested construct evaluationList state.
1032   std::vector<lower::pft::EvaluationList *> evaluationListStack{};
1033   llvm::DenseMap<parser::Label, lower::pft::Evaluation *> *labelEvaluationMap{};
1034   lower::pft::SymbolLabelMap *assignSymbolLabelMap{};
1035   std::map<std::string, lower::pft::Evaluation *> constructNameMap{};
1036   lower::pft::Evaluation *lastLexicalEvaluation{};
1037 };
1038 
1039 class PFTDumper {
1040 public:
dumpPFT(llvm::raw_ostream & outputStream,const lower::pft::Program & pft)1041   void dumpPFT(llvm::raw_ostream &outputStream,
1042                const lower::pft::Program &pft) {
1043     for (auto &unit : pft.getUnits()) {
1044       std::visit(common::visitors{
1045                      [&](const lower::pft::BlockDataUnit &unit) {
1046                        outputStream << getNodeIndex(unit) << " ";
1047                        outputStream << "BlockData: ";
1048                        outputStream << "\nEnd BlockData\n\n";
1049                      },
1050                      [&](const lower::pft::FunctionLikeUnit &func) {
1051                        dumpFunctionLikeUnit(outputStream, func);
1052                      },
1053                      [&](const lower::pft::ModuleLikeUnit &unit) {
1054                        dumpModuleLikeUnit(outputStream, unit);
1055                      },
1056                      [&](const lower::pft::CompilerDirectiveUnit &unit) {
1057                        dumpCompilerDirectiveUnit(outputStream, unit);
1058                      },
1059                  },
1060                  unit);
1061     }
1062   }
1063 
evaluationName(const lower::pft::Evaluation & eval)1064   llvm::StringRef evaluationName(const lower::pft::Evaluation &eval) {
1065     return eval.visit([](const auto &parseTreeNode) {
1066       return parser::ParseTreeDumper::GetNodeName(parseTreeNode);
1067     });
1068   }
1069 
dumpEvaluation(llvm::raw_ostream & outputStream,const lower::pft::Evaluation & eval,const std::string & indentString,int indent=1)1070   void dumpEvaluation(llvm::raw_ostream &outputStream,
1071                       const lower::pft::Evaluation &eval,
1072                       const std::string &indentString, int indent = 1) {
1073     llvm::StringRef name = evaluationName(eval);
1074     llvm::StringRef newBlock = eval.isNewBlock ? "^" : "";
1075     llvm::StringRef bang = eval.isUnstructured ? "!" : "";
1076     outputStream << indentString;
1077     if (eval.printIndex)
1078       outputStream << eval.printIndex << ' ';
1079     if (eval.hasNestedEvaluations())
1080       outputStream << "<<" << newBlock << name << bang << ">>";
1081     else
1082       outputStream << newBlock << name << bang;
1083     if (eval.negateCondition)
1084       outputStream << " [negate]";
1085     if (eval.constructExit)
1086       outputStream << " -> " << eval.constructExit->printIndex;
1087     else if (eval.controlSuccessor)
1088       outputStream << " -> " << eval.controlSuccessor->printIndex;
1089     else if (eval.isA<parser::EntryStmt>() && eval.lexicalSuccessor)
1090       outputStream << " -> " << eval.lexicalSuccessor->printIndex;
1091     if (!eval.position.empty())
1092       outputStream << ": " << eval.position.ToString();
1093     else if (auto *dir = eval.getIf<Fortran::parser::CompilerDirective>())
1094       outputStream << ": !" << dir->source.ToString();
1095     outputStream << '\n';
1096     if (eval.hasNestedEvaluations()) {
1097       dumpEvaluationList(outputStream, *eval.evaluationList, indent + 1);
1098       outputStream << indentString << "<<End " << name << bang << ">>\n";
1099     }
1100   }
1101 
dumpEvaluation(llvm::raw_ostream & ostream,const lower::pft::Evaluation & eval)1102   void dumpEvaluation(llvm::raw_ostream &ostream,
1103                       const lower::pft::Evaluation &eval) {
1104     dumpEvaluation(ostream, eval, "");
1105   }
1106 
dumpEvaluationList(llvm::raw_ostream & outputStream,const lower::pft::EvaluationList & evaluationList,int indent=1)1107   void dumpEvaluationList(llvm::raw_ostream &outputStream,
1108                           const lower::pft::EvaluationList &evaluationList,
1109                           int indent = 1) {
1110     static const auto white = "                                      ++"s;
1111     auto indentString = white.substr(0, indent * 2);
1112     for (const lower::pft::Evaluation &eval : evaluationList)
1113       dumpEvaluation(outputStream, eval, indentString, indent);
1114   }
1115 
1116   void
dumpFunctionLikeUnit(llvm::raw_ostream & outputStream,const lower::pft::FunctionLikeUnit & functionLikeUnit)1117   dumpFunctionLikeUnit(llvm::raw_ostream &outputStream,
1118                        const lower::pft::FunctionLikeUnit &functionLikeUnit) {
1119     outputStream << getNodeIndex(functionLikeUnit) << " ";
1120     llvm::StringRef unitKind;
1121     llvm::StringRef name;
1122     llvm::StringRef header;
1123     if (functionLikeUnit.beginStmt) {
1124       functionLikeUnit.beginStmt->visit(common::visitors{
1125           [&](const parser::Statement<parser::ProgramStmt> &stmt) {
1126             unitKind = "Program";
1127             name = toStringRef(stmt.statement.v.source);
1128           },
1129           [&](const parser::Statement<parser::FunctionStmt> &stmt) {
1130             unitKind = "Function";
1131             name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1132             header = toStringRef(stmt.source);
1133           },
1134           [&](const parser::Statement<parser::SubroutineStmt> &stmt) {
1135             unitKind = "Subroutine";
1136             name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1137             header = toStringRef(stmt.source);
1138           },
1139           [&](const parser::Statement<parser::MpSubprogramStmt> &stmt) {
1140             unitKind = "MpSubprogram";
1141             name = toStringRef(stmt.statement.v.source);
1142             header = toStringRef(stmt.source);
1143           },
1144           [&](const auto &) { llvm_unreachable("not a valid begin stmt"); },
1145       });
1146     } else {
1147       unitKind = "Program";
1148       name = "<anonymous>";
1149     }
1150     outputStream << unitKind << ' ' << name;
1151     if (!header.empty())
1152       outputStream << ": " << header;
1153     outputStream << '\n';
1154     dumpEvaluationList(outputStream, functionLikeUnit.evaluationList);
1155     if (!functionLikeUnit.nestedFunctions.empty()) {
1156       outputStream << "\nContains\n";
1157       for (const lower::pft::FunctionLikeUnit &func :
1158            functionLikeUnit.nestedFunctions)
1159         dumpFunctionLikeUnit(outputStream, func);
1160       outputStream << "End Contains\n";
1161     }
1162     outputStream << "End " << unitKind << ' ' << name << "\n\n";
1163   }
1164 
dumpModuleLikeUnit(llvm::raw_ostream & outputStream,const lower::pft::ModuleLikeUnit & moduleLikeUnit)1165   void dumpModuleLikeUnit(llvm::raw_ostream &outputStream,
1166                           const lower::pft::ModuleLikeUnit &moduleLikeUnit) {
1167     outputStream << getNodeIndex(moduleLikeUnit) << " ";
1168     outputStream << "ModuleLike:\n";
1169     dumpEvaluationList(outputStream, moduleLikeUnit.evaluationList);
1170     outputStream << "Contains\n";
1171     for (const lower::pft::FunctionLikeUnit &func :
1172          moduleLikeUnit.nestedFunctions)
1173       dumpFunctionLikeUnit(outputStream, func);
1174     outputStream << "End Contains\nEnd ModuleLike\n\n";
1175   }
1176 
1177   // Top level directives
dumpCompilerDirectiveUnit(llvm::raw_ostream & outputStream,const lower::pft::CompilerDirectiveUnit & directive)1178   void dumpCompilerDirectiveUnit(
1179       llvm::raw_ostream &outputStream,
1180       const lower::pft::CompilerDirectiveUnit &directive) {
1181     outputStream << getNodeIndex(directive) << " ";
1182     outputStream << "CompilerDirective: !";
1183     outputStream << directive.get<Fortran::parser::CompilerDirective>()
1184                         .source.ToString();
1185     outputStream << "\nEnd CompilerDirective\n\n";
1186   }
1187 
1188   template <typename T>
getNodeIndex(const T & node)1189   std::size_t getNodeIndex(const T &node) {
1190     auto addr = static_cast<const void *>(&node);
1191     auto it = nodeIndexes.find(addr);
1192     if (it != nodeIndexes.end())
1193       return it->second;
1194     nodeIndexes.try_emplace(addr, nextIndex);
1195     return nextIndex++;
1196   }
getNodeIndex(const lower::pft::Program &)1197   std::size_t getNodeIndex(const lower::pft::Program &) { return 0; }
1198 
1199 private:
1200   llvm::DenseMap<const void *, std::size_t> nodeIndexes;
1201   std::size_t nextIndex{1}; // 0 is the root
1202 };
1203 
1204 } // namespace
1205 
1206 template <typename A, typename T>
1207 static lower::pft::FunctionLikeUnit::FunctionStatement
getFunctionStmt(const T & func)1208 getFunctionStmt(const T &func) {
1209   lower::pft::FunctionLikeUnit::FunctionStatement result{
1210       std::get<parser::Statement<A>>(func.t)};
1211   return result;
1212 }
1213 
1214 template <typename A, typename T>
getModuleStmt(const T & mod)1215 static lower::pft::ModuleLikeUnit::ModuleStatement getModuleStmt(const T &mod) {
1216   lower::pft::ModuleLikeUnit::ModuleStatement result{
1217       std::get<parser::Statement<A>>(mod.t)};
1218   return result;
1219 }
1220 
1221 template <typename A>
getSymbol(A & beginStmt)1222 static const semantics::Symbol *getSymbol(A &beginStmt) {
1223   const auto *symbol = beginStmt.visit(common::visitors{
1224       [](const parser::Statement<parser::ProgramStmt> &stmt)
1225           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1226       [](const parser::Statement<parser::FunctionStmt> &stmt)
1227           -> const semantics::Symbol * {
1228         return std::get<parser::Name>(stmt.statement.t).symbol;
1229       },
1230       [](const parser::Statement<parser::SubroutineStmt> &stmt)
1231           -> const semantics::Symbol * {
1232         return std::get<parser::Name>(stmt.statement.t).symbol;
1233       },
1234       [](const parser::Statement<parser::MpSubprogramStmt> &stmt)
1235           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1236       [](const parser::Statement<parser::ModuleStmt> &stmt)
1237           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1238       [](const parser::Statement<parser::SubmoduleStmt> &stmt)
1239           -> const semantics::Symbol * {
1240         return std::get<parser::Name>(stmt.statement.t).symbol;
1241       },
1242       [](const auto &) -> const semantics::Symbol * {
1243         llvm_unreachable("unknown FunctionLike or ModuleLike beginStmt");
1244         return nullptr;
1245       }});
1246   assert(symbol && "parser::Name must have resolved symbol");
1247   return symbol;
1248 }
1249 
lowerAsStructured() const1250 bool Fortran::lower::pft::Evaluation::lowerAsStructured() const {
1251   return !lowerAsUnstructured();
1252 }
1253 
lowerAsUnstructured() const1254 bool Fortran::lower::pft::Evaluation::lowerAsUnstructured() const {
1255   return isUnstructured || clDisableStructuredFir;
1256 }
1257 
1258 lower::pft::FunctionLikeUnit *
getOwningProcedure() const1259 Fortran::lower::pft::Evaluation::getOwningProcedure() const {
1260   return parent.visit(common::visitors{
1261       [](lower::pft::FunctionLikeUnit &c) { return &c; },
1262       [&](lower::pft::Evaluation &c) { return c.getOwningProcedure(); },
1263       [](auto &) -> lower::pft::FunctionLikeUnit * { return nullptr; },
1264   });
1265 }
1266 
definedInCommonBlock(const semantics::Symbol & sym)1267 bool Fortran::lower::definedInCommonBlock(const semantics::Symbol &sym) {
1268   return semantics::FindCommonBlockContaining(sym);
1269 }
1270 
isReentrant(const Fortran::semantics::Scope & scope)1271 static bool isReentrant(const Fortran::semantics::Scope &scope) {
1272   if (scope.kind() == Fortran::semantics::Scope::Kind::MainProgram)
1273     return false;
1274   if (scope.kind() == Fortran::semantics::Scope::Kind::Subprogram) {
1275     const Fortran::semantics::Symbol *sym = scope.symbol();
1276     assert(sym && "Subprogram scope must have a symbol");
1277     return sym->attrs().test(semantics::Attr::RECURSIVE) ||
1278            (!sym->attrs().test(semantics::Attr::NON_RECURSIVE) &&
1279             Fortran::lower::defaultRecursiveFunctionSetting());
1280   }
1281   if (scope.kind() == Fortran::semantics::Scope::Kind::Module)
1282     return false;
1283   return true;
1284 }
1285 
1286 /// Is the symbol `sym` a global?
symbolIsGlobal(const semantics::Symbol & sym)1287 bool Fortran::lower::symbolIsGlobal(const semantics::Symbol &sym) {
1288   if (const auto *details = sym.detailsIf<semantics::ObjectEntityDetails>()) {
1289     if (details->init())
1290       return true;
1291     if (!isReentrant(sym.owner())) {
1292       // Turn array and character of non re-entrant programs (like the main
1293       // program) into global memory.
1294       if (const Fortran::semantics::DeclTypeSpec *symTy = sym.GetType())
1295         if (symTy->category() == semantics::DeclTypeSpec::Character)
1296           if (auto e = symTy->characterTypeSpec().length().GetExplicit())
1297             return true;
1298       if (!details->shape().empty() || !details->coshape().empty())
1299         return true;
1300     }
1301     if (mainProgramGlobals &&
1302         sym.owner().kind() == Fortran::semantics::Scope::Kind::MainProgram)
1303       return true;
1304   }
1305   return semantics::IsSaved(sym) || lower::definedInCommonBlock(sym) ||
1306          semantics::IsNamedConstant(sym);
1307 }
1308 
1309 namespace {
1310 /// This helper class is for sorting the symbols in the symbol table. We want
1311 /// the symbols in an order such that a symbol will be visited after those it
1312 /// depends upon. Otherwise this sort is stable and preserves the order of the
1313 /// symbol table, which is sorted by name.
1314 struct SymbolDependenceDepth {
SymbolDependenceDepth__anon431f4f765411::SymbolDependenceDepth1315   explicit SymbolDependenceDepth(
1316       std::vector<std::vector<lower::pft::Variable>> &vars)
1317       : vars{vars} {}
1318 
analyzeAliasesInCurrentScope__anon431f4f765411::SymbolDependenceDepth1319   void analyzeAliasesInCurrentScope(const semantics::Scope &scope) {
1320     // FIXME: When this function is called on the scope of an internal
1321     // procedure whose parent contains an EQUIVALENCE set and the internal
1322     // procedure uses variables from that EQUIVALENCE set, we end up creating
1323     // an AggregateStore for those variables unnecessarily.
1324     //
1325     /// If this is a function nested in a module no host associated
1326     /// symbol are added to the function scope for module symbols used in this
1327     /// scope. As a result, alias analysis in parent module scopes must be
1328     /// preformed here.
1329     const semantics::Scope *parentScope = &scope;
1330     while (!parentScope->IsGlobal()) {
1331       parentScope = &parentScope->parent();
1332       if (parentScope->IsModule())
1333         analyzeAliases(*parentScope);
1334     }
1335     for (const auto &iter : scope) {
1336       const semantics::Symbol &ultimate = iter.second.get().GetUltimate();
1337       if (skipSymbol(ultimate))
1338         continue;
1339       analyzeAliases(ultimate.owner());
1340     }
1341     // add all aggregate stores to the front of the work list
1342     adjustSize(1);
1343     // The copy in the loop matters, 'stores' will still be used.
1344     for (auto st : stores)
1345       vars[0].emplace_back(std::move(st));
1346   }
1347 
1348   // Compute the offset of the last byte that resides in the symbol.
offsetWidth__anon431f4f765411::SymbolDependenceDepth1349   inline static std::size_t offsetWidth(const Fortran::semantics::Symbol &sym) {
1350     std::size_t width = sym.offset();
1351     if (std::size_t size = sym.size())
1352       width += size - 1;
1353     return width;
1354   }
1355 
1356   // Analyze the equivalence sets. This analysis need not be performed when the
1357   // scope has no equivalence sets.
analyzeAliases__anon431f4f765411::SymbolDependenceDepth1358   void analyzeAliases(const semantics::Scope &scope) {
1359     if (scope.equivalenceSets().empty())
1360       return;
1361     // Don't analyze a scope if it has already been analyzed.
1362     if (analyzedScopes.find(&scope) != analyzedScopes.end())
1363       return;
1364 
1365     analyzedScopes.insert(&scope);
1366     std::list<std::list<semantics::SymbolRef>> aggregates =
1367         Fortran::semantics::GetStorageAssociations(scope);
1368     for (std::list<semantics::SymbolRef> aggregate : aggregates) {
1369       const Fortran::semantics::Symbol *aggregateSym = nullptr;
1370       bool isGlobal = false;
1371       const semantics::Symbol &first = *aggregate.front();
1372       std::size_t start = first.offset();
1373       std::size_t end = first.offset() + first.size();
1374       const Fortran::semantics::Symbol *namingSym = nullptr;
1375       for (semantics::SymbolRef symRef : aggregate) {
1376         const semantics::Symbol &sym = *symRef;
1377         aliasSyms.insert(&sym);
1378         if (sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated)) {
1379           aggregateSym = &sym;
1380         } else {
1381           isGlobal |= lower::symbolIsGlobal(sym);
1382           start = std::min(sym.offset(), start);
1383           end = std::max(sym.offset() + sym.size(), end);
1384           if (!namingSym || (sym.name() < namingSym->name()))
1385             namingSym = &sym;
1386         }
1387       }
1388       assert(namingSym && "must contain at least one user symbol");
1389       if (!aggregateSym) {
1390         stores.emplace_back(
1391             Fortran::lower::pft::Variable::Interval{start, end - start},
1392             *namingSym, isGlobal);
1393       } else {
1394         stores.emplace_back(*aggregateSym, *namingSym, isGlobal);
1395       }
1396     }
1397   }
1398 
1399   // Recursively visit each symbol to determine the height of its dependence on
1400   // other symbols.
analyze__anon431f4f765411::SymbolDependenceDepth1401   int analyze(const semantics::Symbol &sym) {
1402     auto done = seen.insert(&sym);
1403     LLVM_DEBUG(llvm::dbgs() << "analyze symbol: " << sym << '\n');
1404     if (!done.second)
1405       return 0;
1406     const bool isProcedurePointerOrDummy =
1407         semantics::IsProcedurePointer(sym) ||
1408         (semantics::IsProcedure(sym) && IsDummy(sym));
1409     // A procedure argument in a subprogram with multiple entry points might
1410     // need a vars list entry to trigger creation of a symbol map entry in
1411     // some cases.  Non-dummy procedures don't.
1412     if (semantics::IsProcedure(sym) && !isProcedurePointerOrDummy)
1413       return 0;
1414     semantics::Symbol ultimate = sym.GetUltimate();
1415     if (const auto *details =
1416             ultimate.detailsIf<semantics::NamelistDetails>()) {
1417       // handle namelist group symbols
1418       for (const semantics::SymbolRef &s : details->objects())
1419         analyze(s);
1420       return 0;
1421     }
1422     if (!ultimate.has<semantics::ObjectEntityDetails>() &&
1423         !isProcedurePointerOrDummy)
1424       return 0;
1425 
1426     if (sym.has<semantics::DerivedTypeDetails>())
1427       llvm_unreachable("not yet implemented - derived type analysis");
1428 
1429     // Symbol must be something lowering will have to allocate.
1430     int depth = 0;
1431     // Analyze symbols appearing in object entity specification expression. This
1432     // ensures these symbols will be instantiated before the current one.
1433     // This is not done for object entities that are host associated because
1434     // they must be instantiated from the value of the host symbols (the
1435     // specification expressions should not be re-evaluated).
1436     if (const auto *details = sym.detailsIf<semantics::ObjectEntityDetails>()) {
1437       const semantics::DeclTypeSpec *symTy = sym.GetType();
1438       assert(symTy && "symbol must have a type");
1439       // check CHARACTER's length
1440       if (symTy->category() == semantics::DeclTypeSpec::Character)
1441         if (auto e = symTy->characterTypeSpec().length().GetExplicit())
1442           for (const auto &s : evaluate::CollectSymbols(*e))
1443             depth = std::max(analyze(s) + 1, depth);
1444 
1445       auto doExplicit = [&](const auto &bound) {
1446         if (bound.isExplicit()) {
1447           semantics::SomeExpr e{*bound.GetExplicit()};
1448           for (const auto &s : evaluate::CollectSymbols(e))
1449             depth = std::max(analyze(s) + 1, depth);
1450         }
1451       };
1452       // handle any symbols in array bound declarations
1453       for (const semantics::ShapeSpec &subs : details->shape()) {
1454         doExplicit(subs.lbound());
1455         doExplicit(subs.ubound());
1456       }
1457       // handle any symbols in coarray bound declarations
1458       for (const semantics::ShapeSpec &subs : details->coshape()) {
1459         doExplicit(subs.lbound());
1460         doExplicit(subs.ubound());
1461       }
1462       // handle any symbols in initialization expressions
1463       if (auto e = details->init())
1464         for (const auto &s : evaluate::CollectSymbols(*e))
1465           depth = std::max(analyze(s) + 1, depth);
1466     }
1467     adjustSize(depth + 1);
1468     bool global = lower::symbolIsGlobal(sym);
1469     vars[depth].emplace_back(sym, global, depth);
1470     if (semantics::IsAllocatable(sym))
1471       vars[depth].back().setHeapAlloc();
1472     if (semantics::IsPointer(sym))
1473       vars[depth].back().setPointer();
1474     if (ultimate.attrs().test(semantics::Attr::TARGET))
1475       vars[depth].back().setTarget();
1476 
1477     // If there are alias sets, then link the participating variables to their
1478     // aggregate stores when constructing the new variable on the list.
1479     if (lower::pft::Variable::AggregateStore *store = findStoreIfAlias(sym))
1480       vars[depth].back().setAlias(store->getOffset());
1481     return depth;
1482   }
1483 
1484   /// Save the final list of variable allocations as a single vector and free
1485   /// the rest.
finalize__anon431f4f765411::SymbolDependenceDepth1486   void finalize() {
1487     for (int i = 1, end = vars.size(); i < end; ++i)
1488       vars[0].insert(vars[0].end(), vars[i].begin(), vars[i].end());
1489     vars.resize(1);
1490   }
1491 
1492   Fortran::lower::pft::Variable::AggregateStore *
findStoreIfAlias__anon431f4f765411::SymbolDependenceDepth1493   findStoreIfAlias(const Fortran::evaluate::Symbol &sym) {
1494     const semantics::Symbol &ultimate = sym.GetUltimate();
1495     const semantics::Scope &scope = ultimate.owner();
1496     // Expect the total number of EQUIVALENCE sets to be small for a typical
1497     // Fortran program.
1498     if (aliasSyms.find(&ultimate) != aliasSyms.end()) {
1499       LLVM_DEBUG(llvm::dbgs() << "symbol: " << ultimate << '\n');
1500       LLVM_DEBUG(llvm::dbgs() << "scope: " << scope << '\n');
1501       std::size_t off = ultimate.offset();
1502       std::size_t symSize = ultimate.size();
1503       for (lower::pft::Variable::AggregateStore &v : stores) {
1504         if (&v.getOwningScope() == &scope) {
1505           auto intervalOff = std::get<0>(v.interval);
1506           auto intervalSize = std::get<1>(v.interval);
1507           if (off >= intervalOff && off < intervalOff + intervalSize)
1508             return &v;
1509           // Zero sized symbol in zero sized equivalence.
1510           if (off == intervalOff && symSize == 0)
1511             return &v;
1512         }
1513       }
1514       // clang-format off
1515       LLVM_DEBUG(
1516           llvm::dbgs() << "looking for " << off << "\n{\n";
1517           for (lower::pft::Variable::AggregateStore &v : stores) {
1518             llvm::dbgs() << " in scope: " << &v.getOwningScope() << "\n";
1519             llvm::dbgs() << "  i = [" << std::get<0>(v.interval) << ".."
1520                 << std::get<0>(v.interval) + std::get<1>(v.interval)
1521                 << "]\n";
1522           }
1523           llvm::dbgs() << "}\n");
1524       // clang-format on
1525       llvm_unreachable("the store must be present");
1526     }
1527     return nullptr;
1528   }
1529 
1530 private:
1531   /// Skip symbol in alias analysis.
skipSymbol__anon431f4f765411::SymbolDependenceDepth1532   bool skipSymbol(const semantics::Symbol &sym) {
1533     // Common block equivalences are largely managed by the front end.
1534     // Compiler generated symbols ('.' names) cannot be equivalenced.
1535     // FIXME: Equivalence code generation may need to be revisited.
1536     return !sym.has<semantics::ObjectEntityDetails>() ||
1537            lower::definedInCommonBlock(sym) || sym.name()[0] == '.';
1538   }
1539 
1540   // Make sure the table is of appropriate size.
adjustSize__anon431f4f765411::SymbolDependenceDepth1541   void adjustSize(std::size_t size) {
1542     if (vars.size() < size)
1543       vars.resize(size);
1544   }
1545 
1546   llvm::SmallSet<const semantics::Symbol *, 32> seen;
1547   std::vector<std::vector<lower::pft::Variable>> &vars;
1548   llvm::SmallSet<const semantics::Symbol *, 32> aliasSyms;
1549   /// Set of Scope that have been analyzed for aliases.
1550   llvm::SmallSet<const semantics::Scope *, 4> analyzedScopes;
1551   std::vector<Fortran::lower::pft::Variable::AggregateStore> stores;
1552 };
1553 } // namespace
1554 
processSymbolTable(const semantics::Scope & scope,std::vector<std::vector<Fortran::lower::pft::Variable>> & varList)1555 static void processSymbolTable(
1556     const semantics::Scope &scope,
1557     std::vector<std::vector<Fortran::lower::pft::Variable>> &varList) {
1558   SymbolDependenceDepth sdd{varList};
1559   sdd.analyzeAliasesInCurrentScope(scope);
1560   for (const auto &iter : scope)
1561     sdd.analyze(iter.second.get());
1562   sdd.finalize();
1563 }
1564 
1565 //===----------------------------------------------------------------------===//
1566 // FunctionLikeUnit implementation
1567 //===----------------------------------------------------------------------===//
1568 
FunctionLikeUnit(const parser::MainProgram & func,const lower::pft::PftNode & parent,const semantics::SemanticsContext & semanticsContext)1569 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1570     const parser::MainProgram &func, const lower::pft::PftNode &parent,
1571     const semantics::SemanticsContext &semanticsContext)
1572     : ProgramUnit{func, parent}, endStmt{
1573                                      getFunctionStmt<parser::EndProgramStmt>(
1574                                          func)} {
1575   const auto &programStmt =
1576       std::get<std::optional<parser::Statement<parser::ProgramStmt>>>(func.t);
1577   if (programStmt.has_value()) {
1578     beginStmt = FunctionStatement(programStmt.value());
1579     const semantics::Symbol *symbol = getSymbol(*beginStmt);
1580     entryPointList[0].first = symbol;
1581     processSymbolTable(*symbol->scope(), varList);
1582   } else {
1583     processSymbolTable(
1584         semanticsContext.FindScope(
1585             std::get<parser::Statement<parser::EndProgramStmt>>(func.t).source),
1586         varList);
1587   }
1588 }
1589 
FunctionLikeUnit(const parser::FunctionSubprogram & func,const lower::pft::PftNode & parent,const semantics::SemanticsContext &)1590 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1591     const parser::FunctionSubprogram &func, const lower::pft::PftNode &parent,
1592     const semantics::SemanticsContext &)
1593     : ProgramUnit{func, parent},
1594       beginStmt{getFunctionStmt<parser::FunctionStmt>(func)},
1595       endStmt{getFunctionStmt<parser::EndFunctionStmt>(func)} {
1596   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1597   entryPointList[0].first = symbol;
1598   processSymbolTable(*symbol->scope(), varList);
1599 }
1600 
FunctionLikeUnit(const parser::SubroutineSubprogram & func,const lower::pft::PftNode & parent,const semantics::SemanticsContext &)1601 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1602     const parser::SubroutineSubprogram &func, const lower::pft::PftNode &parent,
1603     const semantics::SemanticsContext &)
1604     : ProgramUnit{func, parent},
1605       beginStmt{getFunctionStmt<parser::SubroutineStmt>(func)},
1606       endStmt{getFunctionStmt<parser::EndSubroutineStmt>(func)} {
1607   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1608   entryPointList[0].first = symbol;
1609   processSymbolTable(*symbol->scope(), varList);
1610 }
1611 
FunctionLikeUnit(const parser::SeparateModuleSubprogram & func,const lower::pft::PftNode & parent,const semantics::SemanticsContext &)1612 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1613     const parser::SeparateModuleSubprogram &func,
1614     const lower::pft::PftNode &parent, const semantics::SemanticsContext &)
1615     : ProgramUnit{func, parent},
1616       beginStmt{getFunctionStmt<parser::MpSubprogramStmt>(func)},
1617       endStmt{getFunctionStmt<parser::EndMpSubprogramStmt>(func)} {
1618   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1619   entryPointList[0].first = symbol;
1620   processSymbolTable(*symbol->scope(), varList);
1621 }
1622 
1623 Fortran::lower::HostAssociations &
parentHostAssoc()1624 Fortran::lower::pft::FunctionLikeUnit::parentHostAssoc() {
1625   if (auto *par = parent.getIf<FunctionLikeUnit>())
1626     return par->hostAssociations;
1627   llvm::report_fatal_error("parent is not a function");
1628 }
1629 
parentHasHostAssoc()1630 bool Fortran::lower::pft::FunctionLikeUnit::parentHasHostAssoc() {
1631   if (auto *par = parent.getIf<FunctionLikeUnit>())
1632     return !par->hostAssociations.empty();
1633   return false;
1634 }
1635 
1636 parser::CharBlock
getStartingSourceLoc() const1637 Fortran::lower::pft::FunctionLikeUnit::getStartingSourceLoc() const {
1638   if (beginStmt)
1639     return stmtSourceLoc(*beginStmt);
1640   if (!evaluationList.empty())
1641     return evaluationList.front().position;
1642   return stmtSourceLoc(endStmt);
1643 }
1644 
1645 //===----------------------------------------------------------------------===//
1646 // ModuleLikeUnit implementation
1647 //===----------------------------------------------------------------------===//
1648 
ModuleLikeUnit(const parser::Module & m,const lower::pft::PftNode & parent)1649 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1650     const parser::Module &m, const lower::pft::PftNode &parent)
1651     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::ModuleStmt>(m)},
1652       endStmt{getModuleStmt<parser::EndModuleStmt>(m)} {
1653   const semantics::Symbol *symbol = getSymbol(beginStmt);
1654   processSymbolTable(*symbol->scope(), varList);
1655 }
1656 
ModuleLikeUnit(const parser::Submodule & m,const lower::pft::PftNode & parent)1657 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1658     const parser::Submodule &m, const lower::pft::PftNode &parent)
1659     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::SubmoduleStmt>(
1660                                   m)},
1661       endStmt{getModuleStmt<parser::EndSubmoduleStmt>(m)} {
1662   const semantics::Symbol *symbol = getSymbol(beginStmt);
1663   processSymbolTable(*symbol->scope(), varList);
1664 }
1665 
1666 parser::CharBlock
getStartingSourceLoc() const1667 Fortran::lower::pft::ModuleLikeUnit::getStartingSourceLoc() const {
1668   return stmtSourceLoc(beginStmt);
1669 }
1670 const Fortran::semantics::Scope &
getScope() const1671 Fortran::lower::pft::ModuleLikeUnit::getScope() const {
1672   const Fortran::semantics::Symbol *symbol = getSymbol(beginStmt);
1673   assert(symbol && symbol->scope() &&
1674          "Module statement must have a symbol with a scope");
1675   return *symbol->scope();
1676 }
1677 
1678 //===----------------------------------------------------------------------===//
1679 // BlockDataUnit implementation
1680 //===----------------------------------------------------------------------===//
1681 
BlockDataUnit(const parser::BlockData & bd,const lower::pft::PftNode & parent,const semantics::SemanticsContext & semanticsContext)1682 Fortran::lower::pft::BlockDataUnit::BlockDataUnit(
1683     const parser::BlockData &bd, const lower::pft::PftNode &parent,
1684     const semantics::SemanticsContext &semanticsContext)
1685     : ProgramUnit{bd, parent},
1686       symTab{semanticsContext.FindScope(
1687           std::get<parser::Statement<parser::EndBlockDataStmt>>(bd.t).source)} {
1688 }
1689 
1690 std::unique_ptr<lower::pft::Program>
createPFT(const parser::Program & root,const semantics::SemanticsContext & semanticsContext)1691 Fortran::lower::createPFT(const parser::Program &root,
1692                           const semantics::SemanticsContext &semanticsContext) {
1693   PFTBuilder walker(semanticsContext);
1694   Walk(root, walker);
1695   return walker.result();
1696 }
1697 
1698 // FIXME: FlangDriver
1699 // This option should be integrated with the real driver as the default of
1700 // RECURSIVE vs. NON_RECURSIVE may be changed by other command line options,
1701 // etc., etc.
defaultRecursiveFunctionSetting()1702 bool Fortran::lower::defaultRecursiveFunctionSetting() {
1703   return !nonRecursiveProcedures;
1704 }
1705 
dumpPFT(llvm::raw_ostream & outputStream,const lower::pft::Program & pft)1706 void Fortran::lower::dumpPFT(llvm::raw_ostream &outputStream,
1707                              const lower::pft::Program &pft) {
1708   PFTDumper{}.dumpPFT(outputStream, pft);
1709 }
1710 
dump() const1711 void Fortran::lower::pft::Program::dump() const {
1712   dumpPFT(llvm::errs(), *this);
1713 }
1714 
dump() const1715 void Fortran::lower::pft::Evaluation::dump() const {
1716   PFTDumper{}.dumpEvaluation(llvm::errs(), *this);
1717 }
1718 
dump() const1719 void Fortran::lower::pft::Variable::dump() const {
1720   if (auto *s = std::get_if<Nominal>(&var)) {
1721     llvm::errs() << "symbol: " << s->symbol->name();
1722     llvm::errs() << " (depth: " << s->depth << ')';
1723     if (s->global)
1724       llvm::errs() << ", global";
1725     if (s->heapAlloc)
1726       llvm::errs() << ", allocatable";
1727     if (s->pointer)
1728       llvm::errs() << ", pointer";
1729     if (s->target)
1730       llvm::errs() << ", target";
1731     if (s->aliaser)
1732       llvm::errs() << ", equivalence(" << s->aliasOffset << ')';
1733   } else if (auto *s = std::get_if<AggregateStore>(&var)) {
1734     llvm::errs() << "interval[" << std::get<0>(s->interval) << ", "
1735                  << std::get<1>(s->interval) << "]:";
1736     llvm::errs() << " name: " << toStringRef(s->getNamingSymbol().name());
1737     if (s->isGlobal())
1738       llvm::errs() << ", global";
1739     if (s->initialValueSymbol)
1740       llvm::errs() << ", initial value: {" << *s->initialValueSymbol << "}";
1741   } else {
1742     llvm_unreachable("not a Variable");
1743   }
1744   llvm::errs() << '\n';
1745 }
1746 
dump() const1747 void Fortran::lower::pft::FunctionLikeUnit::dump() const {
1748   PFTDumper{}.dumpFunctionLikeUnit(llvm::errs(), *this);
1749 }
1750 
dump() const1751 void Fortran::lower::pft::ModuleLikeUnit::dump() const {
1752   PFTDumper{}.dumpModuleLikeUnit(llvm::errs(), *this);
1753 }
1754 
1755 /// The BlockDataUnit dump is just the associated symbol table.
dump() const1756 void Fortran::lower::pft::BlockDataUnit::dump() const {
1757   llvm::errs() << "block data {\n" << symTab << "\n}\n";
1758 }
1759 
1760 std::vector<Fortran::lower::pft::Variable>
buildFuncResultDependencyList(const Fortran::semantics::Symbol & symbol)1761 Fortran::lower::pft::buildFuncResultDependencyList(
1762     const Fortran::semantics::Symbol &symbol) {
1763   std::vector<std::vector<pft::Variable>> variableList;
1764   SymbolDependenceDepth sdd(variableList);
1765   sdd.analyzeAliasesInCurrentScope(symbol.owner());
1766   sdd.analyze(symbol);
1767   sdd.finalize();
1768   // Remove the pft::variable for the result itself, only its dependencies
1769   // should be returned in the list.
1770   assert(!variableList[0].empty() && "must at least contain the result");
1771   assert(&variableList[0].back().getSymbol() == &symbol &&
1772          "result sym should be last");
1773   variableList[0].pop_back();
1774   return variableList[0];
1775 }
1776 
1777 namespace {
1778 /// Helper class to find all the symbols referenced in a FunctionLikeUnit.
1779 /// It defines a parse tree visitor doing a deep visit in all nodes with
1780 /// symbols (including evaluate::Expr).
1781 struct SymbolVisitor {
1782   template <typename A>
Pre__anon431f4f765611::SymbolVisitor1783   bool Pre(const A &x) {
1784     if constexpr (Fortran::parser::HasTypedExpr<A>::value)
1785       // Some parse tree Expr may legitimately be un-analyzed after semantics
1786       // (for instance PDT component initial value in the PDT definition body).
1787       if (const auto *expr = Fortran::semantics::GetExpr(nullptr, x))
1788         visitExpr(*expr);
1789     return true;
1790   }
1791 
Pre__anon431f4f765611::SymbolVisitor1792   bool Pre(const Fortran::parser::Name &name) {
1793     if (const semantics::Symbol *symbol = name.symbol)
1794       visitSymbol(*symbol);
1795     return false;
1796   }
1797 
1798   template <typename T>
visitExpr__anon431f4f765611::SymbolVisitor1799   void visitExpr(const Fortran::evaluate::Expr<T> &expr) {
1800     for (const semantics::Symbol &symbol :
1801          Fortran::evaluate::CollectSymbols(expr))
1802       visitSymbol(symbol);
1803   }
1804 
visitSymbol__anon431f4f765611::SymbolVisitor1805   void visitSymbol(const Fortran::semantics::Symbol &symbol) {
1806     callBack(symbol);
1807     // - Visit statement function body since it will be inlined in lowering.
1808     // - Visit function results specification expressions because allocations
1809     //   happens on the caller side.
1810     if (const auto *subprogramDetails =
1811             symbol.detailsIf<Fortran::semantics::SubprogramDetails>()) {
1812       if (const auto &maybeExpr = subprogramDetails->stmtFunction()) {
1813         visitExpr(*maybeExpr);
1814       } else {
1815         if (subprogramDetails->isFunction()) {
1816           // Visit result extents expressions that are explicit.
1817           const Fortran::semantics::Symbol &result =
1818               subprogramDetails->result();
1819           if (const auto *objectDetails =
1820                   result.detailsIf<Fortran::semantics::ObjectEntityDetails>())
1821             if (objectDetails->shape().IsExplicitShape())
1822               for (const Fortran::semantics::ShapeSpec &shapeSpec :
1823                    objectDetails->shape()) {
1824                 visitExpr(shapeSpec.lbound().GetExplicit().value());
1825                 visitExpr(shapeSpec.ubound().GetExplicit().value());
1826               }
1827         }
1828       }
1829     }
1830     if (Fortran::semantics::IsProcedure(symbol)) {
1831       if (auto dynamicType = Fortran::evaluate::DynamicType::From(symbol)) {
1832         // Visit result length specification expressions that are explicit.
1833         if (dynamicType->category() ==
1834             Fortran::common::TypeCategory::Character) {
1835           if (std::optional<Fortran::evaluate::ExtentExpr> length =
1836                   dynamicType->GetCharLength())
1837             visitExpr(*length);
1838         } else if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
1839                        Fortran::evaluate::GetDerivedTypeSpec(dynamicType)) {
1840           for (const auto &[_, param] : derivedTypeSpec->parameters())
1841             if (const Fortran::semantics::MaybeIntExpr &expr =
1842                     param.GetExplicit())
1843               visitExpr(expr.value());
1844         }
1845       }
1846     }
1847   }
1848 
1849   template <typename A>
Post__anon431f4f765611::SymbolVisitor1850   constexpr void Post(const A &) {}
1851 
1852   const std::function<void(const Fortran::semantics::Symbol &)> &callBack;
1853 };
1854 } // namespace
1855 
visitAllSymbols(const Fortran::lower::pft::FunctionLikeUnit & funit,const std::function<void (const Fortran::semantics::Symbol &)> callBack)1856 void Fortran::lower::pft::visitAllSymbols(
1857     const Fortran::lower::pft::FunctionLikeUnit &funit,
1858     const std::function<void(const Fortran::semantics::Symbol &)> callBack) {
1859   SymbolVisitor visitor{callBack};
1860   funit.visit([&](const auto &functionParserNode) {
1861     parser::Walk(functionParserNode, visitor);
1862   });
1863 }
1864 
visitAllSymbols(const Fortran::lower::pft::Evaluation & eval,const std::function<void (const Fortran::semantics::Symbol &)> callBack)1865 void Fortran::lower::pft::visitAllSymbols(
1866     const Fortran::lower::pft::Evaluation &eval,
1867     const std::function<void(const Fortran::semantics::Symbol &)> callBack) {
1868   SymbolVisitor visitor{callBack};
1869   eval.visit([&](const auto &functionParserNode) {
1870     parser::Walk(functionParserNode, visitor);
1871   });
1872 }
1873