1 //===-- lib/Semantics/semantics.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/Semantics/semantics.h"
10 #include "assignment.h"
11 #include "canonicalize-acc.h"
12 #include "canonicalize-do.h"
13 #include "canonicalize-omp.h"
14 #include "check-acc-structure.h"
15 #include "check-allocate.h"
16 #include "check-arithmeticif.h"
17 #include "check-case.h"
18 #include "check-coarray.h"
19 #include "check-data.h"
20 #include "check-deallocate.h"
21 #include "check-declarations.h"
22 #include "check-do-forall.h"
23 #include "check-if-stmt.h"
24 #include "check-io.h"
25 #include "check-namelist.h"
26 #include "check-nullify.h"
27 #include "check-omp-structure.h"
28 #include "check-purity.h"
29 #include "check-return.h"
30 #include "check-select-rank.h"
31 #include "check-select-type.h"
32 #include "check-stop.h"
33 #include "compute-offsets.h"
34 #include "mod-file.h"
35 #include "resolve-labels.h"
36 #include "resolve-names.h"
37 #include "rewrite-parse-tree.h"
38 #include "flang/Common/default-kinds.h"
39 #include "flang/Parser/parse-tree-visitor.h"
40 #include "flang/Parser/tools.h"
41 #include "flang/Semantics/expression.h"
42 #include "flang/Semantics/scope.h"
43 #include "flang/Semantics/symbol.h"
44 #include "llvm/Support/raw_ostream.h"
45 
46 namespace Fortran::semantics {
47 
48 using NameToSymbolMap = std::multimap<parser::CharBlock, SymbolRef>;
49 static void DoDumpSymbols(llvm::raw_ostream &, const Scope &, int indent = 0);
50 static void PutIndent(llvm::raw_ostream &, int indent);
51 
GetSymbolNames(const Scope & scope,NameToSymbolMap & symbols)52 static void GetSymbolNames(const Scope &scope, NameToSymbolMap &symbols) {
53   // Finds all symbol names in the scope without collecting duplicates.
54   for (const auto &pair : scope) {
55     symbols.emplace(pair.second->name(), *pair.second);
56   }
57   for (const auto &pair : scope.commonBlocks()) {
58     symbols.emplace(pair.second->name(), *pair.second);
59   }
60   for (const auto &child : scope.children()) {
61     GetSymbolNames(child, symbols);
62   }
63 }
64 
65 // A parse tree visitor that calls Enter/Leave functions from each checker
66 // class C supplied as template parameters. Enter is called before the node's
67 // children are visited, Leave is called after. No two checkers may have the
68 // same Enter or Leave function. Each checker must be constructible from
69 // SemanticsContext and have BaseChecker as a virtual base class.
70 template <typename... C> class SemanticsVisitor : public virtual C... {
71 public:
72   using C::Enter...;
73   using C::Leave...;
74   using BaseChecker::Enter;
75   using BaseChecker::Leave;
SemanticsVisitor(SemanticsContext & context)76   SemanticsVisitor(SemanticsContext &context)
77       : C{context}..., context_{context} {}
78 
Pre(const N & node)79   template <typename N> bool Pre(const N &node) {
80     if constexpr (common::HasMember<const N *, ConstructNode>) {
81       context_.PushConstruct(node);
82     }
83     Enter(node);
84     return true;
85   }
Post(const N & node)86   template <typename N> void Post(const N &node) {
87     Leave(node);
88     if constexpr (common::HasMember<const N *, ConstructNode>) {
89       context_.PopConstruct();
90     }
91   }
92 
Pre(const parser::Statement<T> & node)93   template <typename T> bool Pre(const parser::Statement<T> &node) {
94     context_.set_location(node.source);
95     Enter(node);
96     return true;
97   }
Pre(const parser::UnlabeledStatement<T> & node)98   template <typename T> bool Pre(const parser::UnlabeledStatement<T> &node) {
99     context_.set_location(node.source);
100     Enter(node);
101     return true;
102   }
Post(const parser::Statement<T> & node)103   template <typename T> void Post(const parser::Statement<T> &node) {
104     Leave(node);
105     context_.set_location(std::nullopt);
106   }
Post(const parser::UnlabeledStatement<T> & node)107   template <typename T> void Post(const parser::UnlabeledStatement<T> &node) {
108     Leave(node);
109     context_.set_location(std::nullopt);
110   }
111 
Walk(const parser::Program & program)112   bool Walk(const parser::Program &program) {
113     parser::Walk(program, *this);
114     return !context_.AnyFatalError();
115   }
116 
117 private:
118   SemanticsContext &context_;
119 };
120 
121 class MiscChecker : public virtual BaseChecker {
122 public:
MiscChecker(SemanticsContext & context)123   explicit MiscChecker(SemanticsContext &context) : context_{context} {}
Leave(const parser::EntryStmt &)124   void Leave(const parser::EntryStmt &) {
125     if (!context_.constructStack().empty()) { // C1571
126       context_.Say("ENTRY may not appear in an executable construct"_err_en_US);
127     }
128   }
Leave(const parser::AssignStmt & stmt)129   void Leave(const parser::AssignStmt &stmt) {
130     CheckAssignGotoName(std::get<parser::Name>(stmt.t));
131   }
Leave(const parser::AssignedGotoStmt & stmt)132   void Leave(const parser::AssignedGotoStmt &stmt) {
133     CheckAssignGotoName(std::get<parser::Name>(stmt.t));
134   }
135 
136 private:
CheckAssignGotoName(const parser::Name & name)137   void CheckAssignGotoName(const parser::Name &name) {
138     if (context_.HasError(name.symbol)) {
139       return;
140     }
141     const Symbol &symbol{DEREF(name.symbol)};
142     auto type{evaluate::DynamicType::From(symbol)};
143     if (!IsVariableName(symbol) || symbol.Rank() != 0 || !type ||
144         type->category() != TypeCategory::Integer ||
145         type->kind() !=
146             context_.defaultKinds().GetDefaultKind(TypeCategory::Integer)) {
147       context_
148           .Say(name.source,
149               "'%s' must be a default integer scalar variable"_err_en_US,
150               name.source)
151           .Attach(symbol.name(), "Declaration of '%s'"_en_US, symbol.name());
152     }
153   }
154 
155   SemanticsContext &context_;
156 };
157 
158 using StatementSemanticsPass1 = ExprChecker;
159 using StatementSemanticsPass2 = SemanticsVisitor<AccStructureChecker,
160     AllocateChecker, ArithmeticIfStmtChecker, AssignmentChecker, CaseChecker,
161     CoarrayChecker, DataChecker, DeallocateChecker, DoForallChecker,
162     IfStmtChecker, IoChecker, MiscChecker, NamelistChecker, NullifyChecker,
163     OmpStructureChecker, PurityChecker, ReturnStmtChecker,
164     SelectRankConstructChecker, SelectTypeChecker, StopChecker>;
165 
PerformStatementSemantics(SemanticsContext & context,parser::Program & program)166 static bool PerformStatementSemantics(
167     SemanticsContext &context, parser::Program &program) {
168   ResolveNames(context, program);
169   RewriteParseTree(context, program);
170   ComputeOffsets(context);
171   CheckDeclarations(context);
172   StatementSemanticsPass1{context}.Walk(program);
173   StatementSemanticsPass2 pass2{context};
174   pass2.Walk(program);
175   if (!context.AnyFatalError()) {
176     pass2.CompileDataInitializationsIntoInitializers();
177   }
178   return !context.AnyFatalError();
179 }
180 
SemanticsContext(const common::IntrinsicTypeDefaultKinds & defaultKinds,const common::LanguageFeatureControl & languageFeatures,parser::AllCookedSources & allCookedSources)181 SemanticsContext::SemanticsContext(
182     const common::IntrinsicTypeDefaultKinds &defaultKinds,
183     const common::LanguageFeatureControl &languageFeatures,
184     parser::AllCookedSources &allCookedSources)
185     : defaultKinds_{defaultKinds}, languageFeatures_{languageFeatures},
186       allCookedSources_{allCookedSources},
187       intrinsics_{evaluate::IntrinsicProcTable::Configure(defaultKinds_)},
188       foldingContext_{
189           parser::ContextualMessages{&messages_}, defaultKinds_, intrinsics_} {}
190 
~SemanticsContext()191 SemanticsContext::~SemanticsContext() {}
192 
GetDefaultKind(TypeCategory category) const193 int SemanticsContext::GetDefaultKind(TypeCategory category) const {
194   return defaultKinds_.GetDefaultKind(category);
195 }
196 
IsEnabled(common::LanguageFeature feature) const197 bool SemanticsContext::IsEnabled(common::LanguageFeature feature) const {
198   return languageFeatures_.IsEnabled(feature);
199 }
200 
ShouldWarn(common::LanguageFeature feature) const201 bool SemanticsContext::ShouldWarn(common::LanguageFeature feature) const {
202   return languageFeatures_.ShouldWarn(feature);
203 }
204 
MakeNumericType(TypeCategory category,int kind)205 const DeclTypeSpec &SemanticsContext::MakeNumericType(
206     TypeCategory category, int kind) {
207   if (kind == 0) {
208     kind = GetDefaultKind(category);
209   }
210   return globalScope_.MakeNumericType(category, KindExpr{kind});
211 }
MakeLogicalType(int kind)212 const DeclTypeSpec &SemanticsContext::MakeLogicalType(int kind) {
213   if (kind == 0) {
214     kind = GetDefaultKind(TypeCategory::Logical);
215   }
216   return globalScope_.MakeLogicalType(KindExpr{kind});
217 }
218 
AnyFatalError() const219 bool SemanticsContext::AnyFatalError() const {
220   return !messages_.empty() &&
221       (warningsAreErrors_ || messages_.AnyFatalError());
222 }
HasError(const Symbol & symbol)223 bool SemanticsContext::HasError(const Symbol &symbol) {
224   return errorSymbols_.count(symbol) > 0;
225 }
HasError(const Symbol * symbol)226 bool SemanticsContext::HasError(const Symbol *symbol) {
227   return !symbol || HasError(*symbol);
228 }
HasError(const parser::Name & name)229 bool SemanticsContext::HasError(const parser::Name &name) {
230   return HasError(name.symbol);
231 }
SetError(const Symbol & symbol,bool value)232 void SemanticsContext::SetError(const Symbol &symbol, bool value) {
233   if (value) {
234     CheckError(symbol);
235     errorSymbols_.emplace(symbol);
236   }
237 }
CheckError(const Symbol & symbol)238 void SemanticsContext::CheckError(const Symbol &symbol) {
239   if (!AnyFatalError()) {
240     std::string buf;
241     llvm::raw_string_ostream ss{buf};
242     ss << symbol;
243     common::die(
244         "No error was reported but setting error on: %s", ss.str().c_str());
245   }
246 }
247 
FindScope(parser::CharBlock source) const248 const Scope &SemanticsContext::FindScope(parser::CharBlock source) const {
249   return const_cast<SemanticsContext *>(this)->FindScope(source);
250 }
251 
FindScope(parser::CharBlock source)252 Scope &SemanticsContext::FindScope(parser::CharBlock source) {
253   if (auto *scope{globalScope_.FindScope(source)}) {
254     return *scope;
255   } else {
256     common::die("SemanticsContext::FindScope(): invalid source location");
257   }
258 }
259 
PopConstruct()260 void SemanticsContext::PopConstruct() {
261   CHECK(!constructStack_.empty());
262   constructStack_.pop_back();
263 }
264 
CheckIndexVarRedefine(const parser::CharBlock & location,const Symbol & variable,parser::MessageFixedText && message)265 void SemanticsContext::CheckIndexVarRedefine(const parser::CharBlock &location,
266     const Symbol &variable, parser::MessageFixedText &&message) {
267   if (const Symbol * root{GetAssociationRoot(variable)}) {
268     auto it{activeIndexVars_.find(*root)};
269     if (it != activeIndexVars_.end()) {
270       std::string kind{EnumToString(it->second.kind)};
271       Say(location, std::move(message), kind, root->name())
272           .Attach(it->second.location, "Enclosing %s construct"_en_US, kind);
273     }
274   }
275 }
276 
WarnIndexVarRedefine(const parser::CharBlock & location,const Symbol & variable)277 void SemanticsContext::WarnIndexVarRedefine(
278     const parser::CharBlock &location, const Symbol &variable) {
279   CheckIndexVarRedefine(
280       location, variable, "Possible redefinition of %s variable '%s'"_en_US);
281 }
282 
CheckIndexVarRedefine(const parser::CharBlock & location,const Symbol & variable)283 void SemanticsContext::CheckIndexVarRedefine(
284     const parser::CharBlock &location, const Symbol &variable) {
285   CheckIndexVarRedefine(
286       location, variable, "Cannot redefine %s variable '%s'"_err_en_US);
287 }
288 
CheckIndexVarRedefine(const parser::Variable & variable)289 void SemanticsContext::CheckIndexVarRedefine(const parser::Variable &variable) {
290   if (const Symbol * entity{GetLastName(variable).symbol}) {
291     CheckIndexVarRedefine(variable.GetSource(), *entity);
292   }
293 }
294 
CheckIndexVarRedefine(const parser::Name & name)295 void SemanticsContext::CheckIndexVarRedefine(const parser::Name &name) {
296   if (const Symbol * entity{name.symbol}) {
297     CheckIndexVarRedefine(name.source, *entity);
298   }
299 }
300 
ActivateIndexVar(const parser::Name & name,IndexVarKind kind)301 void SemanticsContext::ActivateIndexVar(
302     const parser::Name &name, IndexVarKind kind) {
303   CheckIndexVarRedefine(name);
304   if (const Symbol * indexVar{name.symbol}) {
305     if (const Symbol * root{GetAssociationRoot(*indexVar)}) {
306       activeIndexVars_.emplace(*root, IndexVarInfo{name.source, kind});
307     }
308   }
309 }
310 
DeactivateIndexVar(const parser::Name & name)311 void SemanticsContext::DeactivateIndexVar(const parser::Name &name) {
312   if (Symbol * indexVar{name.symbol}) {
313     if (const Symbol * root{GetAssociationRoot(*indexVar)}) {
314       auto it{activeIndexVars_.find(*root)};
315       if (it != activeIndexVars_.end() && it->second.location == name.source) {
316         activeIndexVars_.erase(it);
317       }
318     }
319   }
320 }
321 
GetIndexVars(IndexVarKind kind)322 SymbolVector SemanticsContext::GetIndexVars(IndexVarKind kind) {
323   SymbolVector result;
324   for (const auto &[symbol, info] : activeIndexVars_) {
325     if (info.kind == kind) {
326       result.push_back(symbol);
327     }
328   }
329   return result;
330 }
331 
GetTempName(const Scope & scope)332 SourceName SemanticsContext::GetTempName(const Scope &scope) {
333   for (const auto &str : tempNames_) {
334     SourceName name{str};
335     if (scope.find(name) == scope.end()) {
336       return name;
337     }
338   }
339   tempNames_.emplace_back(".F18.");
340   tempNames_.back() += std::to_string(tempNames_.size());
341   return {tempNames_.back()};
342 }
343 
Perform()344 bool Semantics::Perform() {
345   return ValidateLabels(context_, program_) &&
346       parser::CanonicalizeDo(program_) && // force line break
347       CanonicalizeAcc(context_.messages(), program_) &&
348       CanonicalizeOmp(context_.messages(), program_) &&
349       PerformStatementSemantics(context_, program_) &&
350       ModFileWriter{context_}.WriteAll();
351 }
352 
EmitMessages(llvm::raw_ostream & os) const353 void Semantics::EmitMessages(llvm::raw_ostream &os) const {
354   context_.messages().Emit(os, context_.allCookedSources());
355 }
356 
DumpSymbols(llvm::raw_ostream & os)357 void Semantics::DumpSymbols(llvm::raw_ostream &os) {
358   DoDumpSymbols(os, context_.globalScope());
359 }
360 
DumpSymbolsSources(llvm::raw_ostream & os) const361 void Semantics::DumpSymbolsSources(llvm::raw_ostream &os) const {
362   NameToSymbolMap symbols;
363   GetSymbolNames(context_.globalScope(), symbols);
364   const parser::AllCookedSources &allCooked{context_.allCookedSources()};
365   for (const auto &pair : symbols) {
366     const Symbol &symbol{pair.second};
367     if (auto sourceInfo{allCooked.GetSourcePositionRange(symbol.name())}) {
368       os << symbol.name().ToString() << ": " << sourceInfo->first.file.path()
369          << ", " << sourceInfo->first.line << ", " << sourceInfo->first.column
370          << "-" << sourceInfo->second.column << "\n";
371     } else if (symbol.has<semantics::UseDetails>()) {
372       os << symbol.name().ToString() << ": "
373          << symbol.GetUltimate().owner().symbol()->name().ToString() << "\n";
374     }
375   }
376 }
377 
DoDumpSymbols(llvm::raw_ostream & os,const Scope & scope,int indent)378 void DoDumpSymbols(llvm::raw_ostream &os, const Scope &scope, int indent) {
379   PutIndent(os, indent);
380   os << Scope::EnumToString(scope.kind()) << " scope:";
381   if (const auto *symbol{scope.symbol()}) {
382     os << ' ' << symbol->name();
383   }
384   if (scope.alignment().has_value()) {
385     os << " size=" << scope.size() << " alignment=" << *scope.alignment();
386   }
387   if (scope.derivedTypeSpec()) {
388     os << " instantiation of " << *scope.derivedTypeSpec();
389   }
390   os << '\n';
391   ++indent;
392   for (const auto &pair : scope) {
393     const auto &symbol{*pair.second};
394     PutIndent(os, indent);
395     os << symbol << '\n';
396     if (const auto *details{symbol.detailsIf<GenericDetails>()}) {
397       if (const auto &type{details->derivedType()}) {
398         PutIndent(os, indent);
399         os << *type << '\n';
400       }
401     }
402   }
403   if (!scope.equivalenceSets().empty()) {
404     PutIndent(os, indent);
405     os << "Equivalence Sets:";
406     for (const auto &set : scope.equivalenceSets()) {
407       os << ' ';
408       char sep = '(';
409       for (const auto &object : set) {
410         os << sep << object.AsFortran();
411         sep = ',';
412       }
413       os << ')';
414     }
415     os << '\n';
416   }
417   if (!scope.crayPointers().empty()) {
418     PutIndent(os, indent);
419     os << "Cray Pointers:";
420     for (const auto &[pointee, pointer] : scope.crayPointers()) {
421       os << " (" << pointer->name() << ',' << pointee << ')';
422     }
423   }
424   for (const auto &pair : scope.commonBlocks()) {
425     const auto &symbol{*pair.second};
426     PutIndent(os, indent);
427     os << symbol << '\n';
428   }
429   for (const auto &child : scope.children()) {
430     DoDumpSymbols(os, child, indent);
431   }
432   --indent;
433 }
434 
PutIndent(llvm::raw_ostream & os,int indent)435 static void PutIndent(llvm::raw_ostream &os, int indent) {
436   for (int i = 0; i < indent; ++i) {
437     os << "  ";
438   }
439 }
440 } // namespace Fortran::semantics
441