| 1 |
//===-- lib/Semantics/mod-file.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 "mod-file.h" |
| 10 |
#include "resolve-names.h" |
| 11 |
#include "flang/Common/restorer.h" |
| 12 |
#include "flang/Evaluate/tools.h" |
| 13 |
#include "flang/Parser/message.h" |
| 14 |
#include "flang/Parser/parsing.h" |
| 15 |
#include "flang/Parser/unparse.h" |
| 16 |
#include "flang/Semantics/scope.h" |
| 17 |
#include "flang/Semantics/semantics.h" |
| 18 |
#include "flang/Semantics/symbol.h" |
| 19 |
#include "flang/Semantics/tools.h" |
| 20 |
#include "llvm/Support/FileSystem.h" |
| 21 |
#include "llvm/Support/MemoryBuffer.h" |
| 22 |
#include "llvm/Support/raw_ostream.h" |
| 23 |
#include <algorithm> |
| 24 |
#include <fstream> |
| 25 |
#include <set> |
| 26 |
#include <string_view> |
| 27 |
#include <vector> |
| 28 |
|
| 29 |
namespace Fortran::semantics { |
| 30 |
|
| 31 |
using namespace parser::literals; |
| 32 |
|
| 33 |
// The first line of a file that identifies it as a .mod file. |
| 34 |
// The first three bytes are a Unicode byte order mark that ensures |
| 35 |
// that the module file is decoded as UTF-8 even if source files |
| 36 |
// are using another encoding. |
| 37 |
struct ModHeader { |
| 38 |
static constexpr const char bom[3 + 1]{"\xef\xbb\xbf"}; |
| 39 |
static constexpr int magicLen{13}; |
| 40 |
static constexpr int sumLen{16}; |
| 41 |
static constexpr const char magic[magicLen + 1]{"!mod$ v1 sum:"}; |
| 42 |
static constexpr char terminator{'\n'}; |
| 43 |
static constexpr int len{magicLen + 1 + sumLen}; |
| 44 |
static constexpr int needLen{7}; |
| 45 |
static constexpr const char need[needLen + 1]{"!need$ "}; |
| 46 |
}; |
| 47 |
|
| 48 |
static std::optional<SourceName> GetSubmoduleParent(const parser::Program &); |
| 49 |
static void CollectSymbols( |
| 50 |
const Scope &, SymbolVector &, SymbolVector &, UnorderedSymbolSet &); |
| 51 |
static void PutPassName(llvm::raw_ostream &, const std::optional<SourceName> &); |
| 52 |
static void PutInit(llvm::raw_ostream &, const Symbol &, const MaybeExpr &, |
| 53 |
const parser::Expr *); |
| 54 |
static void PutInit(llvm::raw_ostream &, const MaybeIntExpr &); |
| 55 |
static void PutBound(llvm::raw_ostream &, const Bound &); |
| 56 |
static void PutShapeSpec(llvm::raw_ostream &, const ShapeSpec &); |
| 57 |
static void PutShape( |
| 58 |
llvm::raw_ostream &, const ArraySpec &, char open, char close); |
| 59 |
|
| 60 |
static llvm::raw_ostream &PutAttr(llvm::raw_ostream &, Attr); |
| 61 |
static llvm::raw_ostream &PutType(llvm::raw_ostream &, const DeclTypeSpec &); |
| 62 |
static llvm::raw_ostream &PutLower(llvm::raw_ostream &, std::string_view); |
| 63 |
static std::error_code WriteFile(const std::string &, const std::string &, |
| 64 |
ModuleCheckSumType &, bool debug = true); |
| 65 |
static bool FileContentsMatch( |
| 66 |
const std::string &, const std::string &, const std::string &); |
| 67 |
static ModuleCheckSumType ComputeCheckSum(const std::string_view &); |
| 68 |
static std::string CheckSumString(ModuleCheckSumType); |
| 69 |
|
| 70 |
// Collect symbols needed for a subprogram interface |
| 71 |
class SubprogramSymbolCollector { |
| 72 |
public: |
| 73 |
SubprogramSymbolCollector(const Symbol &symbol, const Scope &scope) |
| 74 |
: symbol_{symbol}, scope_{scope} {} |
| 75 |
const SymbolVector &symbols() const { return need_; } |
| 76 |
const std::set<SourceName> &imports() const { return imports_; } |
| 77 |
void Collect(); |
| 78 |
|
| 79 |
private: |
| 80 |
const Symbol &symbol_; |
| 81 |
const Scope &scope_; |
| 82 |
bool isInterface_{false}; |
| 83 |
SymbolVector need_; // symbols that are needed |
| 84 |
UnorderedSymbolSet needSet_; // symbols already in need_ |
| 85 |
UnorderedSymbolSet useSet_; // use-associations that might be needed |
| 86 |
std::set<SourceName> imports_; // imports from host that are needed |
| 87 |
|
| 88 |
void DoSymbol(const Symbol &); |
| 89 |
void DoSymbol(const SourceName &, const Symbol &); |
| 90 |
void DoType(const DeclTypeSpec *); |
| 91 |
void DoBound(const Bound &); |
| 92 |
void DoParamValue(const ParamValue &); |
| 93 |
bool NeedImport(const SourceName &, const Symbol &); |
| 94 |
|
| 95 |
template <typename T> void DoExpr(evaluate::Expr<T> expr) { |
| 96 |
for (const Symbol &symbol : evaluate::CollectSymbols(expr)) { |
| 97 |
DoSymbol(symbol); |
| 98 |
} |
| 99 |
} |
| 100 |
}; |
| 101 |
|
| 102 |
bool ModFileWriter::WriteAll() { |
| 103 |
// this flag affects character literals: force it to be consistent |
| 104 |
auto restorer{ |
| 105 |
common::ScopedSet(parser::useHexadecimalEscapeSequences, false)}; |
| 106 |
WriteAll(context_.globalScope()); |
| 107 |
return !context_.AnyFatalError(); |
| 108 |
} |
| 109 |
|
| 110 |
void ModFileWriter::WriteAll(const Scope &scope) { |
| 111 |
for (const auto &child : scope.children()) { |
| 112 |
WriteOne(child); |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
void ModFileWriter::WriteOne(const Scope &scope) { |
| 117 |
if (scope.kind() == Scope::Kind::Module) { |
| 118 |
auto *symbol{scope.symbol()}; |
| 119 |
if (!symbol->test(Symbol::Flag::ModFile)) { |
| 120 |
Write(*symbol); |
| 121 |
} |
| 122 |
WriteAll(scope); // write out submodules |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
// Construct the name of a module file. Non-empty ancestorName means submodule. |
| 127 |
static std::string ModFileName(const SourceName &name, |
| 128 |
const std::string &ancestorName, const std::string &suffix) { |
| 129 |
std::string result{name.ToString() + suffix}; |
| 130 |
return ancestorName.empty() ? result : ancestorName + '-' + result; |
| 131 |
} |
| 132 |
|
| 133 |
// Write the module file for symbol, which must be a module or submodule. |
| 134 |
void ModFileWriter::Write(const Symbol &symbol) { |
| 135 |
const auto &module{symbol.get<ModuleDetails>()}; |
| 136 |
if (module.moduleFileHash()) { |
| 137 |
return; // already written |
| 138 |
} |
| 139 |
const auto *ancestor{module.ancestor()}; |
| 140 |
isSubmodule_ = ancestor != nullptr; |
| 141 |
auto ancestorName{ancestor ? ancestor->GetName().value().ToString() : ""s}; |
| 142 |
auto path{context_.moduleDirectory() + '/' + |
| 143 |
ModFileName(symbol.name(), ancestorName, context_.moduleFileSuffix())}; |
| 144 |
|
| 145 |
UnorderedSymbolSet hermeticModules; |
| 146 |
hermeticModules.insert(symbol); |
| 147 |
UnorderedSymbolSet additionalModules; |
| 148 |
PutSymbols(DEREF(symbol.scope()), |
| 149 |
hermeticModuleFileOutput_ ? &additionalModules : nullptr); |
| 150 |
auto asStr{GetAsString(symbol)}; |
| 151 |
while (!additionalModules.empty()) { |
| 152 |
for (auto ref : UnorderedSymbolSet{std::move(additionalModules)}) { |
| 153 |
if (hermeticModules.insert(*ref).second && |
| 154 |
!ref->owner().IsIntrinsicModules()) { |
| 155 |
PutSymbols(DEREF(ref->scope()), &additionalModules); |
| 156 |
asStr += GetAsString(*ref); |
| 157 |
} |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
ModuleCheckSumType checkSum; |
| 162 |
if (std::error_code error{ |
| 163 |
WriteFile(path, asStr, checkSum, context_.debugModuleWriter())}) { |
| 164 |
context_.Say( |
| 165 |
symbol.name(), "Error writing %s: %s"_err_en_US, path, error.message()); |
| 166 |
} |
| 167 |
const_cast<ModuleDetails &>(module).set_moduleFileHash(checkSum); |
| 168 |
} |
| 169 |
|
| 170 |
void ModFileWriter::WriteClosure(llvm::raw_ostream &out, const Symbol &symbol, |
| 171 |
UnorderedSymbolSet &nonIntrinsicModulesWritten) { |
| 172 |
if (!symbol.has<ModuleDetails>() || symbol.owner().IsIntrinsicModules() || |
| 173 |
!nonIntrinsicModulesWritten.insert(symbol).second) { |
| 174 |
return; |
| 175 |
} |
| 176 |
PutSymbols(DEREF(symbol.scope()), /*hermeticModules=*/nullptr); |
| 177 |
needsBuf_.clear(); // omit module checksums |
| 178 |
auto str{GetAsString(symbol)}; |
| 179 |
for (auto depRef : std::move(usedNonIntrinsicModules_)) { |
| 180 |
WriteClosure(out, *depRef, nonIntrinsicModulesWritten); |
| 181 |
} |
| 182 |
out << std::move(str); |
| 183 |
} |
| 184 |
|
| 185 |
// Return the entire body of the module file |
| 186 |
// and clear saved uses, decls, and contains. |
| 187 |
std::string ModFileWriter::GetAsString(const Symbol &symbol) { |
| 188 |
std::string buf; |
| 189 |
llvm::raw_string_ostream all{buf}; |
| 190 |
all << needs_.str(); |
| 191 |
needs_.str().clear(); |
| 192 |
auto &details{symbol.get<ModuleDetails>()}; |
| 193 |
if (!details.isSubmodule()) { |
| 194 |
all << "module " << symbol.name(); |
| 195 |
} else { |
| 196 |
auto *parent{details.parent()->symbol()}; |
| 197 |
auto *ancestor{details.ancestor()->symbol()}; |
| 198 |
all << "submodule(" << ancestor->name(); |
| 199 |
if (parent != ancestor) { |
| 200 |
all << ':' << parent->name(); |
| 201 |
} |
| 202 |
all << ") " << symbol.name(); |
| 203 |
} |
| 204 |
all << '\n' << uses_.str(); |
| 205 |
uses_.str().clear(); |
| 206 |
all << useExtraAttrs_.str(); |
| 207 |
useExtraAttrs_.str().clear(); |
| 208 |
all << decls_.str(); |
| 209 |
decls_.str().clear(); |
| 210 |
auto str{contains_.str()}; |
| 211 |
contains_.str().clear(); |
| 212 |
if (!str.empty()) { |
| 213 |
all << "contains\n" << str; |
| 214 |
} |
| 215 |
all << "end\n"; |
| 216 |
return all.str(); |
| 217 |
} |
| 218 |
|
| 219 |
// Collect symbols from constant and specification expressions that are being |
| 220 |
// referenced directly from other modules; they may require new USE |
| 221 |
// associations. |
| 222 |
static void HarvestSymbolsNeededFromOtherModules( |
| 223 |
SourceOrderedSymbolSet &, const Scope &); |
| 224 |
static void HarvestSymbolsNeededFromOtherModules( |
| 225 |
SourceOrderedSymbolSet &set, const Symbol &symbol, const Scope &scope) { |
| 226 |
auto HarvestBound{[&](const Bound &bound) { |
| 227 |
if (const auto &expr{bound.GetExplicit()}) { |
| 228 |
for (SymbolRef ref : evaluate::CollectSymbols(*expr)) { |
| 229 |
set.emplace(*ref); |
| 230 |
} |
| 231 |
} |
| 232 |
}}; |
| 233 |
auto HarvestShapeSpec{[&](const ShapeSpec &shapeSpec) { |
| 234 |
HarvestBound(shapeSpec.lbound()); |
| 235 |
HarvestBound(shapeSpec.ubound()); |
| 236 |
}}; |
| 237 |
auto HarvestArraySpec{[&](const ArraySpec &arraySpec) { |
| 238 |
for (const auto &shapeSpec : arraySpec) { |
| 239 |
HarvestShapeSpec(shapeSpec); |
| 240 |
} |
| 241 |
}}; |
| 242 |
|
| 243 |
if (symbol.has<DerivedTypeDetails>()) { |
| 244 |
if (symbol.scope()) { |
| 245 |
HarvestSymbolsNeededFromOtherModules(set, *symbol.scope()); |
| 246 |
} |
| 247 |
} else if (const auto &generic{symbol.detailsIf<GenericDetails>()}; |
| 248 |
generic && generic->derivedType()) { |
| 249 |
const Symbol &dtSym{*generic->derivedType()}; |
| 250 |
if (dtSym.has<DerivedTypeDetails>()) { |
| 251 |
if (dtSym.scope()) { |
| 252 |
HarvestSymbolsNeededFromOtherModules(set, *dtSym.scope()); |
| 253 |
} |
| 254 |
} else { |
| 255 |
CHECK(dtSym.has<UseDetails>() || dtSym.has<UseErrorDetails>()); |
| 256 |
} |
| 257 |
} else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) { |
| 258 |
HarvestArraySpec(object->shape()); |
| 259 |
HarvestArraySpec(object->coshape()); |
| 260 |
if (IsNamedConstant(symbol) || scope.IsDerivedType()) { |
| 261 |
if (object->init()) { |
| 262 |
for (SymbolRef ref : evaluate::CollectSymbols(*object->init())) { |
| 263 |
set.emplace(*ref); |
| 264 |
} |
| 265 |
} |
| 266 |
} |
| 267 |
} else if (const auto *proc{symbol.detailsIf<ProcEntityDetails>()}) { |
| 268 |
if (proc->init() && *proc->init() && scope.IsDerivedType()) { |
| 269 |
set.emplace(**proc->init()); |
| 270 |
} |
| 271 |
} else if (const auto *subp{symbol.detailsIf<SubprogramDetails>()}) { |
| 272 |
for (const Symbol *dummy : subp->dummyArgs()) { |
| 273 |
if (dummy) { |
| 274 |
HarvestSymbolsNeededFromOtherModules(set, *dummy, scope); |
| 275 |
} |
| 276 |
} |
| 277 |
if (subp->isFunction()) { |
| 278 |
HarvestSymbolsNeededFromOtherModules(set, subp->result(), scope); |
| 279 |
} |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
static void HarvestSymbolsNeededFromOtherModules( |
| 284 |
SourceOrderedSymbolSet &set, const Scope &scope) { |
| 285 |
for (const auto &[_, symbol] : scope) { |
| 286 |
HarvestSymbolsNeededFromOtherModules(set, *symbol, scope); |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
void ModFileWriter::PrepareRenamings(const Scope &scope) { |
| 291 |
// Identify use-associated symbols already in scope under some name |
| 292 |
std::map<const Symbol *, const Symbol *> useMap; |
| 293 |
for (const auto &[name, symbolRef] : scope) { |
| 294 |
const Symbol *symbol{&*symbolRef}; |
| 295 |
while (const auto *hostAssoc{symbol->detailsIf<HostAssocDetails>()}) { |
| 296 |
symbol = &hostAssoc->symbol(); |
| 297 |
} |
| 298 |
if (const auto *use{symbol->detailsIf<UseDetails>()}) { |
| 299 |
useMap.emplace(&use->symbol(), symbol); |
| 300 |
} |
| 301 |
} |
| 302 |
// Collect symbols needed from other modules |
| 303 |
SourceOrderedSymbolSet symbolsNeeded; |
| 304 |
HarvestSymbolsNeededFromOtherModules(symbolsNeeded, scope); |
| 305 |
// Establish any necessary renamings of symbols in other modules |
| 306 |
// to their names in this scope, creating those new names when needed. |
| 307 |
auto &renamings{context_.moduleFileOutputRenamings()}; |
| 308 |
for (SymbolRef s : symbolsNeeded) { |
| 309 |
if (s->owner().kind() == Scope::Kind::DerivedType) { |
| 310 |
continue; // component or binding: ok |
| 311 |
} |
| 312 |
const Scope *sMod{FindModuleContaining(s->owner())}; |
| 313 |
if (!sMod || sMod == &scope) { |
| 314 |
continue; |
| 315 |
} |
| 316 |
if (auto iter{useMap.find(&*s)}; iter != useMap.end()) { |
| 317 |
renamings.emplace(&*s, iter->second->name()); |
| 318 |
continue; |
| 319 |
} |
| 320 |
SourceName rename{s->name()}; |
| 321 |
if (const Symbol * found{scope.FindSymbol(s->name())}) { |
| 322 |
if (found == &*s) { |
| 323 |
continue; // available in scope |
| 324 |
} |
| 325 |
if (const auto *generic{found->detailsIf<GenericDetails>()}) { |
| 326 |
if (generic->derivedType() == &*s || generic->specific() == &*s) { |
| 327 |
continue; |
| 328 |
} |
| 329 |
} else if (found->has<UseDetails>()) { |
| 330 |
if (&found->GetUltimate() == &*s) { |
| 331 |
continue; // already use-associated with same name |
| 332 |
} |
| 333 |
} |
| 334 |
if (&s->owner() != &found->owner()) { // Symbol needs renaming |
| 335 |
rename = scope.context().SaveTempName( |
| 336 |
DEREF(sMod->symbol()).name().ToString() + "$" + |
| 337 |
s->name().ToString()); |
| 338 |
} |
| 339 |
} |
| 340 |
// Symbol is used in this scope but not visible under its name |
| 341 |
if (sMod->parent().IsIntrinsicModules()) { |
| 342 |
uses_ << "use,intrinsic::"; |
| 343 |
} else { |
| 344 |
uses_ << "use "; |
| 345 |
} |
| 346 |
uses_ << DEREF(sMod->symbol()).name() << ",only:"; |
| 347 |
if (rename != s->name()) { |
| 348 |
uses_ << rename << "=>"; |
| 349 |
renamings.emplace(&*s, rename); |
| 350 |
} |
| 351 |
uses_ << s->name() << '\n'; |
| 352 |
useExtraAttrs_ << "private::" << rename << '\n'; |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
// Put out the visible symbols from scope. |
| 357 |
void ModFileWriter::PutSymbols( |
| 358 |
const Scope &scope, UnorderedSymbolSet *hermeticModules) { |
| 359 |
SymbolVector sorted; |
| 360 |
SymbolVector uses; |
| 361 |
auto &renamings{context_.moduleFileOutputRenamings()}; |
| 362 |
auto previousRenamings{std::move(renamings)}; |
| 363 |
PrepareRenamings(scope); |
| 364 |
UnorderedSymbolSet modules; |
| 365 |
CollectSymbols(scope, sorted, uses, modules); |
| 366 |
// Write module files for dependencies first so that their |
| 367 |
// hashes are known. |
| 368 |
for (auto ref : modules) { |
| 369 |
if (hermeticModules) { |
| 370 |
hermeticModules->insert(*ref); |
| 371 |
} else { |
| 372 |
Write(*ref); |
| 373 |
needs_ << ModHeader::need |
| 374 |
<< CheckSumString( |
| 375 |
ref->get<ModuleDetails>().moduleFileHash().value()) |
| 376 |
<< (ref->owner().IsIntrinsicModules() ? " i " : " n ") |
| 377 |
<< ref->name().ToString() << '\n'; |
| 378 |
} |
| 379 |
} |
| 380 |
std::string buf; // stuff after CONTAINS in derived type |
| 381 |
llvm::raw_string_ostream typeBindings{buf}; |
| 382 |
for (const Symbol &symbol : sorted) { |
| 383 |
if (!symbol.test(Symbol::Flag::CompilerCreated)) { |
| 384 |
PutSymbol(typeBindings, symbol); |
| 385 |
} |
| 386 |
} |
| 387 |
for (const Symbol &symbol : uses) { |
| 388 |
PutUse(symbol); |
| 389 |
} |
| 390 |
for (const auto &set : scope.equivalenceSets()) { |
| 391 |
if (!set.empty() && |
| 392 |
!set.front().symbol.test(Symbol::Flag::CompilerCreated)) { |
| 393 |
char punctuation{'('}; |
| 394 |
decls_ << "equivalence"; |
| 395 |
for (const auto &object : set) { |
| 396 |
decls_ << punctuation << object.AsFortran(); |
| 397 |
punctuation = ','; |
| 398 |
} |
| 399 |
decls_ << ")\n"; |
| 400 |
} |
| 401 |
} |
| 402 |
CHECK(typeBindings.str().empty()); |
| 403 |
renamings = std::move(previousRenamings); |
| 404 |
} |
| 405 |
|
| 406 |
// Emit components in order |
| 407 |
bool ModFileWriter::PutComponents(const Symbol &typeSymbol) { |
| 408 |
const auto &scope{DEREF(typeSymbol.scope())}; |
| 409 |
std::string buf; // stuff after CONTAINS in derived type |
| 410 |
llvm::raw_string_ostream typeBindings{buf}; |
| 411 |
UnorderedSymbolSet emitted; |
| 412 |
SymbolVector symbols{scope.GetSymbols()}; |
| 413 |
// Emit type parameters first |
| 414 |
for (const Symbol &symbol : symbols) { |
| 415 |
if (symbol.has<TypeParamDetails>()) { |
| 416 |
PutSymbol(typeBindings, symbol); |
| 417 |
emitted.emplace(symbol); |
| 418 |
} |
| 419 |
} |
| 420 |
// Emit components in component order. |
| 421 |
const auto &details{typeSymbol.get<DerivedTypeDetails>()}; |
| 422 |
for (SourceName name : details.componentNames()) { |
| 423 |
auto iter{scope.find(name)}; |
| 424 |
if (iter != scope.end()) { |
| 425 |
const Symbol &component{*iter->second}; |
| 426 |
if (!component.test(Symbol::Flag::ParentComp)) { |
| 427 |
PutSymbol(typeBindings, component); |
| 428 |
} |
| 429 |
emitted.emplace(component); |
| 430 |
} |
| 431 |
} |
| 432 |
// Emit remaining symbols from the type's scope |
| 433 |
for (const Symbol &symbol : symbols) { |
| 434 |
if (emitted.find(symbol) == emitted.end()) { |
| 435 |
PutSymbol(typeBindings, symbol); |
| 436 |
} |
| 437 |
} |
| 438 |
if (auto str{typeBindings.str()}; !str.empty()) { |
| 439 |
CHECK(scope.IsDerivedType()); |
| 440 |
decls_ << "contains\n" << str; |
| 441 |
return true; |
| 442 |
} else { |
| 443 |
return false; |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
// Return the symbol's attributes that should be written |
| 448 |
// into the mod file. |
| 449 |
static Attrs getSymbolAttrsToWrite(const Symbol &symbol) { |
| 450 |
// Is SAVE attribute is implicit, it should be omitted |
| 451 |
// to not violate F202x C862 for a common block member. |
| 452 |
return symbol.attrs() & ~(symbol.implicitAttrs() & Attrs{Attr::SAVE}); |
| 453 |
} |
| 454 |
|
| 455 |
static llvm::raw_ostream &PutGenericName( |
| 456 |
llvm::raw_ostream &os, const Symbol &symbol) { |
| 457 |
if (IsGenericDefinedOp(symbol)) { |
| 458 |
return os << "operator(" << symbol.name() << ')'; |
| 459 |
} else { |
| 460 |
return os << symbol.name(); |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
// Emit a symbol to decls_, except for bindings in a derived type (type-bound |
| 465 |
// procedures, type-bound generics, final procedures) which go to typeBindings. |
| 466 |
void ModFileWriter::PutSymbol( |
| 467 |
llvm::raw_ostream &typeBindings, const Symbol &symbol) { |
| 468 |
common::visit( |
| 469 |
common::visitors{ |
| 470 |
[&](const ModuleDetails &) { /* should be current module */ }, |
| 471 |
[&](const DerivedTypeDetails &) { PutDerivedType(symbol); }, |
| 472 |
[&](const SubprogramDetails &) { PutSubprogram(symbol); }, |
| 473 |
[&](const GenericDetails &x) { |
| 474 |
if (symbol.owner().IsDerivedType()) { |
| 475 |
// generic binding |
| 476 |
for (const Symbol &proc : x.specificProcs()) { |
| 477 |
PutGenericName(typeBindings << "generic::", symbol) |
| 478 |
<< "=>" << proc.name() << '\n'; |
| 479 |
} |
| 480 |
} else { |
| 481 |
PutGeneric(symbol); |
| 482 |
} |
| 483 |
}, |
| 484 |
[&](const UseDetails &) { PutUse(symbol); }, |
| 485 |
[](const UseErrorDetails &) {}, |
| 486 |
[&](const ProcBindingDetails &x) { |
| 487 |
bool deferred{symbol.attrs().test(Attr::DEFERRED)}; |
| 488 |
typeBindings << "procedure"; |
| 489 |
if (deferred) { |
| 490 |
typeBindings << '(' << x.symbol().name() << ')'; |
| 491 |
} |
| 492 |
PutPassName(typeBindings, x.passName()); |
| 493 |
auto attrs{symbol.attrs()}; |
| 494 |
if (x.passName()) { |
| 495 |
attrs.reset(Attr::PASS); |
| 496 |
} |
| 497 |
PutAttrs(typeBindings, attrs); |
| 498 |
typeBindings << "::" << symbol.name(); |
| 499 |
if (!deferred && x.symbol().name() != symbol.name()) { |
| 500 |
typeBindings << "=>" << x.symbol().name(); |
| 501 |
} |
| 502 |
typeBindings << '\n'; |
| 503 |
}, |
| 504 |
[&](const NamelistDetails &x) { |
| 505 |
decls_ << "namelist/" << symbol.name(); |
| 506 |
char sep{'/'}; |
| 507 |
for (const Symbol &object : x.objects()) { |
| 508 |
decls_ << sep << object.name(); |
| 509 |
sep = ','; |
| 510 |
} |
| 511 |
decls_ << '\n'; |
| 512 |
if (!isSubmodule_ && symbol.attrs().test(Attr::PRIVATE)) { |
| 513 |
decls_ << "private::" << symbol.name() << '\n'; |
| 514 |
} |
| 515 |
}, |
| 516 |
[&](const CommonBlockDetails &x) { |
| 517 |
decls_ << "common/" << symbol.name(); |
| 518 |
char sep = '/'; |
| 519 |
for (const auto &object : x.objects()) { |
| 520 |
decls_ << sep << object->name(); |
| 521 |
sep = ','; |
| 522 |
} |
| 523 |
decls_ << '\n'; |
| 524 |
if (symbol.attrs().test(Attr::BIND_C)) { |
| 525 |
PutAttrs(decls_, getSymbolAttrsToWrite(symbol), x.bindName(), |
| 526 |
x.isExplicitBindName(), ""s); |
| 527 |
decls_ << "::/" << symbol.name() << "/\n"; |
| 528 |
} |
| 529 |
}, |
| 530 |
[](const HostAssocDetails &) {}, |
| 531 |
[](const MiscDetails &) {}, |
| 532 |
[&](const auto &) { |
| 533 |
PutEntity(decls_, symbol); |
| 534 |
PutDirective(decls_, symbol); |
| 535 |
}, |
| 536 |
}, |
| 537 |
symbol.details()); |
| 538 |
} |
| 539 |
|
| 540 |
void ModFileWriter::PutDerivedType( |
| 541 |
const Symbol &typeSymbol, const Scope *scope) { |
| 542 |
auto &details{typeSymbol.get<DerivedTypeDetails>()}; |
| 543 |
if (details.isDECStructure()) { |
| 544 |
PutDECStructure(typeSymbol, scope); |
| 545 |
return; |
| 546 |
} |
| 547 |
PutAttrs(decls_ << "type", typeSymbol.attrs()); |
| 548 |
if (const DerivedTypeSpec * extends{typeSymbol.GetParentTypeSpec()}) { |
| 549 |
decls_ << ",extends(" << extends->name() << ')'; |
| 550 |
} |
| 551 |
decls_ << "::" << typeSymbol.name(); |
| 552 |
if (!details.paramNames().empty()) { |
| 553 |
char sep{'('}; |
| 554 |
for (const auto &name : details.paramNames()) { |
| 555 |
decls_ << sep << name; |
| 556 |
sep = ','; |
| 557 |
} |
| 558 |
decls_ << ')'; |
| 559 |
} |
| 560 |
decls_ << '\n'; |
| 561 |
if (details.sequence()) { |
| 562 |
decls_ << "sequence\n"; |
| 563 |
} |
| 564 |
bool contains{PutComponents(typeSymbol)}; |
| 565 |
if (!details.finals().empty()) { |
| 566 |
const char *sep{contains ? "final::" : "contains\nfinal::"}; |
| 567 |
for (const auto &pair : details.finals()) { |
| 568 |
decls_ << sep << pair.second->name(); |
| 569 |
sep = ","; |
| 570 |
} |
| 571 |
if (*sep == ',') { |
| 572 |
decls_ << '\n'; |
| 573 |
} |
| 574 |
} |
| 575 |
decls_ << "end type\n"; |
| 576 |
} |
| 577 |
|
| 578 |
void ModFileWriter::PutDECStructure( |
| 579 |
const Symbol &typeSymbol, const Scope *scope) { |
| 580 |
if (emittedDECStructures_.find(typeSymbol) != emittedDECStructures_.end()) { |
| 581 |
return; |
| 582 |
} |
| 583 |
if (!scope && context_.IsTempName(typeSymbol.name().ToString())) { |
| 584 |
return; // defer until used |
| 585 |
} |
| 586 |
emittedDECStructures_.insert(typeSymbol); |
| 587 |
decls_ << "structure "; |
| 588 |
if (!context_.IsTempName(typeSymbol.name().ToString())) { |
| 589 |
decls_ << typeSymbol.name(); |
| 590 |
} |
| 591 |
if (scope && scope->kind() == Scope::Kind::DerivedType) { |
| 592 |
// Nested STRUCTURE: emit entity declarations right now |
| 593 |
// on the STRUCTURE statement. |
| 594 |
bool any{false}; |
| 595 |
for (const auto &ref : scope->GetSymbols()) { |
| 596 |
const auto *object{ref->detailsIf<ObjectEntityDetails>()}; |
| 597 |
if (object && object->type() && |
| 598 |
object->type()->category() == DeclTypeSpec::TypeDerived && |
| 599 |
&object->type()->derivedTypeSpec().typeSymbol() == &typeSymbol) { |
| 600 |
if (any) { |
| 601 |
decls_ << ','; |
| 602 |
} else { |
| 603 |
any = true; |
| 604 |
} |
| 605 |
decls_ << ref->name(); |
| 606 |
PutShape(decls_, object->shape(), '(', ')'); |
| 607 |
PutInit(decls_, *ref, object->init(), nullptr); |
| 608 |
emittedDECFields_.insert(*ref); |
| 609 |
} else if (any) { |
| 610 |
break; // any later use of this structure will use RECORD/str/ |
| 611 |
} |
| 612 |
} |
| 613 |
} |
| 614 |
decls_ << '\n'; |
| 615 |
PutComponents(typeSymbol); |
| 616 |
decls_ << "end structure\n"; |
| 617 |
} |
| 618 |
|
| 619 |
// Attributes that may be in a subprogram prefix |
| 620 |
static const Attrs subprogramPrefixAttrs{Attr::ELEMENTAL, Attr::IMPURE, |
| 621 |
Attr::MODULE, Attr::NON_RECURSIVE, Attr::PURE, Attr::RECURSIVE}; |
| 622 |
|
| 623 |
static void PutOpenACCDeviceTypeRoutineInfo( |
| 624 |
llvm::raw_ostream &os, const OpenACCRoutineDeviceTypeInfo &info) { |
| 625 |
if (info.isSeq()) { |
| 626 |
os << " seq"; |
| 627 |
} |
| 628 |
if (info.isGang()) { |
| 629 |
os << " gang"; |
| 630 |
if (info.gangDim() > 0) { |
| 631 |
os << "(dim: " << info.gangDim() << ")"; |
| 632 |
} |
| 633 |
} |
| 634 |
if (info.isVector()) { |
| 635 |
os << " vector"; |
| 636 |
} |
| 637 |
if (info.isWorker()) { |
| 638 |
os << " worker"; |
| 639 |
} |
| 640 |
if (info.bindName()) { |
| 641 |
os << " bind(" << *info.bindName() << ")"; |
| 642 |
} |
| 643 |
} |
| 644 |
|
| 645 |
static void PutOpenACCRoutineInfo( |
| 646 |
llvm::raw_ostream &os, const SubprogramDetails &details) { |
| 647 |
for (auto info : details.openACCRoutineInfos()) { |
| 648 |
os << "!$acc routine"; |
| 649 |
|
| 650 |
PutOpenACCDeviceTypeRoutineInfo(os, info); |
| 651 |
|
| 652 |
if (info.isNohost()) { |
| 653 |
os << " nohost"; |
| 654 |
} |
| 655 |
|
| 656 |
for (auto dtype : info.deviceTypeInfos()) { |
| 657 |
os << " device_type("; |
| 658 |
if (dtype.dType() == common::OpenACCDeviceType::Star) { |
| 659 |
os << "*"; |
| 660 |
} else { |
| 661 |
os << parser::ToLowerCaseLetters(common::EnumToString(dtype.dType())); |
| 662 |
} |
| 663 |
os << ")"; |
| 664 |
|
| 665 |
PutOpenACCDeviceTypeRoutineInfo(os, dtype); |
| 666 |
} |
| 667 |
|
| 668 |
os << "\n"; |
| 669 |
} |
| 670 |
} |
| 671 |
|
| 672 |
void ModFileWriter::PutSubprogram(const Symbol &symbol) { |
| 673 |
auto &details{symbol.get<SubprogramDetails>()}; |
| 674 |
if (const Symbol * interface{details.moduleInterface()}) { |
| 675 |
const Scope *module{FindModuleContaining(interface->owner())}; |
| 676 |
if (module && module != &symbol.owner()) { |
| 677 |
// Interface is in ancestor module |
| 678 |
} else { |
| 679 |
PutSubprogram(*interface); |
| 680 |
} |
| 681 |
} |
| 682 |
auto attrs{symbol.attrs()}; |
| 683 |
Attrs bindAttrs{}; |
| 684 |
if (attrs.test(Attr::BIND_C)) { |
| 685 |
// bind(c) is a suffix, not prefix |
| 686 |
bindAttrs.set(Attr::BIND_C, true); |
| 687 |
attrs.set(Attr::BIND_C, false); |
| 688 |
} |
| 689 |
bool isAbstract{attrs.test(Attr::ABSTRACT)}; |
| 690 |
if (isAbstract) { |
| 691 |
attrs.set(Attr::ABSTRACT, false); |
| 692 |
} |
| 693 |
Attrs prefixAttrs{subprogramPrefixAttrs & attrs}; |
| 694 |
// emit any non-prefix attributes in an attribute statement |
| 695 |
attrs &= ~subprogramPrefixAttrs; |
| 696 |
std::string ssBuf; |
| 697 |
llvm::raw_string_ostream ss{ssBuf}; |
| 698 |
PutAttrs(ss, attrs); |
| 699 |
if (!ss.str().empty()) { |
| 700 |
decls_ << ss.str().substr(1) << "::" << symbol.name() << '\n'; |
| 701 |
} |
| 702 |
bool isInterface{details.isInterface()}; |
| 703 |
llvm::raw_ostream &os{isInterface ? decls_ : contains_}; |
| 704 |
if (isInterface) { |
| 705 |
os << (isAbstract ? "abstract " : "") << "interface\n"; |
| 706 |
} |
| 707 |
PutAttrs(os, prefixAttrs, nullptr, false, ""s, " "s); |
| 708 |
if (auto attrs{details.cudaSubprogramAttrs()}) { |
| 709 |
if (*attrs == common::CUDASubprogramAttrs::HostDevice) { |
| 710 |
os << "attributes(host,device) "; |
| 711 |
} else { |
| 712 |
PutLower(os << "attributes(", common::EnumToString(*attrs)) << ") "; |
| 713 |
} |
| 714 |
if (!details.cudaLaunchBounds().empty()) { |
| 715 |
os << "launch_bounds"; |
| 716 |
char sep{'('}; |
| 717 |
for (auto x : details.cudaLaunchBounds()) { |
| 718 |
os << sep << x; |
| 719 |
sep = ','; |
| 720 |
} |
| 721 |
os << ") "; |
| 722 |
} |
| 723 |
if (!details.cudaClusterDims().empty()) { |
| 724 |
os << "cluster_dims"; |
| 725 |
char sep{'('}; |
| 726 |
for (auto x : details.cudaClusterDims()) { |
| 727 |
os << sep << x; |
| 728 |
sep = ','; |
| 729 |
} |
| 730 |
os << ") "; |
| 731 |
} |
| 732 |
} |
| 733 |
os << (details.isFunction() ? "function " : "subroutine "); |
| 734 |
os << symbol.name() << '('; |
| 735 |
int n = 0; |
| 736 |
for (const auto &dummy : details.dummyArgs()) { |
| 737 |
if (n++ > 0) { |
| 738 |
os << ','; |
| 739 |
} |
| 740 |
if (dummy) { |
| 741 |
os << dummy->name(); |
| 742 |
} else { |
| 743 |
os << "*"; |
| 744 |
} |
| 745 |
} |
| 746 |
os << ')'; |
| 747 |
PutAttrs(os, bindAttrs, details.bindName(), details.isExplicitBindName(), |
| 748 |
" "s, ""s); |
| 749 |
if (details.isFunction()) { |
| 750 |
const Symbol &result{details.result()}; |
| 751 |
if (result.name() != symbol.name()) { |
| 752 |
os << " result(" << result.name() << ')'; |
| 753 |
} |
| 754 |
} |
| 755 |
os << '\n'; |
| 756 |
// walk symbols, collect ones needed for interface |
| 757 |
const Scope &scope{ |
| 758 |
details.entryScope() ? *details.entryScope() : DEREF(symbol.scope())}; |
| 759 |
SubprogramSymbolCollector collector{symbol, scope}; |
| 760 |
collector.Collect(); |
| 761 |
std::string typeBindingsBuf; |
| 762 |
llvm::raw_string_ostream typeBindings{typeBindingsBuf}; |
| 763 |
ModFileWriter writer{context_}; |
| 764 |
for (const Symbol &need : collector.symbols()) { |
| 765 |
writer.PutSymbol(typeBindings, need); |
| 766 |
} |
| 767 |
CHECK(typeBindings.str().empty()); |
| 768 |
os << writer.uses_.str(); |
| 769 |
for (const SourceName &import : collector.imports()) { |
| 770 |
decls_ << "import::" << import << "\n"; |
| 771 |
} |
| 772 |
os << writer.decls_.str(); |
| 773 |
PutOpenACCRoutineInfo(os, details); |
| 774 |
os << "end\n"; |
| 775 |
if (isInterface) { |
| 776 |
os << "end interface\n"; |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
static bool IsIntrinsicOp(const Symbol &symbol) { |
| 781 |
if (const auto *details{symbol.GetUltimate().detailsIf<GenericDetails>()}) { |
| 782 |
return details->kind().IsIntrinsicOperator(); |
| 783 |
} else { |
| 784 |
return false; |
| 785 |
} |
| 786 |
} |
| 787 |
|
| 788 |
void ModFileWriter::PutGeneric(const Symbol &symbol) { |
| 789 |
const auto &genericOwner{symbol.owner()}; |
| 790 |
auto &details{symbol.get<GenericDetails>()}; |
| 791 |
PutGenericName(decls_ << "interface ", symbol) << '\n'; |
| 792 |
for (const Symbol &specific : details.specificProcs()) { |
| 793 |
if (specific.owner() == genericOwner) { |
| 794 |
decls_ << "procedure::" << specific.name() << '\n'; |
| 795 |
} |
| 796 |
} |
| 797 |
decls_ << "end interface\n"; |
| 798 |
if (!isSubmodule_ && symbol.attrs().test(Attr::PRIVATE)) { |
| 799 |
PutGenericName(decls_ << "private::", symbol) << '\n'; |
| 800 |
} |
| 801 |
} |
| 802 |
|
| 803 |
void ModFileWriter::PutUse(const Symbol &symbol) { |
| 804 |
auto &details{symbol.get<UseDetails>()}; |
| 805 |
auto &use{details.symbol()}; |
| 806 |
const Symbol &module{GetUsedModule(details)}; |
| 807 |
if (use.owner().parent().IsIntrinsicModules()) { |
| 808 |
uses_ << "use,intrinsic::"; |
| 809 |
} else { |
| 810 |
uses_ << "use "; |
| 811 |
usedNonIntrinsicModules_.insert(module); |
| 812 |
} |
| 813 |
uses_ << module.name() << ",only:"; |
| 814 |
PutGenericName(uses_, symbol); |
| 815 |
// Can have intrinsic op with different local-name and use-name |
| 816 |
// (e.g. `operator(<)` and `operator(.lt.)`) but rename is not allowed |
| 817 |
if (!IsIntrinsicOp(symbol) && use.name() != symbol.name()) { |
| 818 |
PutGenericName(uses_ << "=>", use); |
| 819 |
} |
| 820 |
uses_ << '\n'; |
| 821 |
PutUseExtraAttr(Attr::VOLATILE, symbol, use); |
| 822 |
PutUseExtraAttr(Attr::ASYNCHRONOUS, symbol, use); |
| 823 |
if (!isSubmodule_ && symbol.attrs().test(Attr::PRIVATE)) { |
| 824 |
PutGenericName(useExtraAttrs_ << "private::", symbol) << '\n'; |
| 825 |
} |
| 826 |
} |
| 827 |
|
| 828 |
// We have "USE local => use" in this module. If attr was added locally |
| 829 |
// (i.e. on local but not on use), also write it out in the mod file. |
| 830 |
void ModFileWriter::PutUseExtraAttr( |
| 831 |
Attr attr, const Symbol &local, const Symbol &use) { |
| 832 |
if (local.attrs().test(attr) && !use.attrs().test(attr)) { |
| 833 |
PutAttr(useExtraAttrs_, attr) << "::"; |
| 834 |
useExtraAttrs_ << local.name() << '\n'; |
| 835 |
} |
| 836 |
} |
| 837 |
|
| 838 |
static inline SourceName NameInModuleFile(const Symbol &symbol) { |
| 839 |
if (const auto *use{symbol.detailsIf<UseDetails>()}) { |
| 840 |
if (use->symbol().attrs().test(Attr::PRIVATE)) { |
| 841 |
// Avoid the use in sorting of names created to access private |
| 842 |
// specific procedures as a result of generic resolution; |
| 843 |
// they're not in the cooked source. |
| 844 |
return use->symbol().name(); |
| 845 |
} |
| 846 |
} |
| 847 |
return symbol.name(); |
| 848 |
} |
| 849 |
|
| 850 |
// Collect the symbols of this scope sorted by their original order, not name. |
| 851 |
// Generics and namelists are exceptions: they are sorted after other symbols. |
| 852 |
void CollectSymbols(const Scope &scope, SymbolVector &sorted, |
| 853 |
SymbolVector &uses, UnorderedSymbolSet &modules) { |
| 854 |
SymbolVector namelist, generics; |
| 855 |
auto symbols{scope.GetSymbols()}; |
| 856 |
std::size_t commonSize{scope.commonBlocks().size()}; |
| 857 |
sorted.reserve(symbols.size() + commonSize); |
| 858 |
for (SymbolRef symbol : symbols) { |
| 859 |
const auto *generic{symbol->detailsIf<GenericDetails>()}; |
| 860 |
if (generic) { |
| 861 |
uses.insert(uses.end(), generic->uses().begin(), generic->uses().end()); |
| 862 |
for (auto ref : generic->uses()) { |
| 863 |
modules.insert(GetUsedModule(ref->get<UseDetails>())); |
| 864 |
} |
| 865 |
} else if (const auto *use{symbol->detailsIf<UseDetails>()}) { |
| 866 |
modules.insert(GetUsedModule(*use)); |
| 867 |
} |
| 868 |
if (symbol->test(Symbol::Flag::ParentComp)) { |
| 869 |
} else if (symbol->has<NamelistDetails>()) { |
| 870 |
namelist.push_back(symbol); |
| 871 |
} else if (generic) { |
| 872 |
if (generic->specific() && |
| 873 |
&generic->specific()->owner() == &symbol->owner()) { |
| 874 |
sorted.push_back(*generic->specific()); |
| 875 |
} else if (generic->derivedType() && |
| 876 |
&generic->derivedType()->owner() == &symbol->owner()) { |
| 877 |
sorted.push_back(*generic->derivedType()); |
| 878 |
} |
| 879 |
generics.push_back(symbol); |
| 880 |
} else { |
| 881 |
sorted.push_back(symbol); |
| 882 |
} |
| 883 |
} |
| 884 |
// Sort most symbols by name: use of Symbol::ReplaceName ensures the source |
| 885 |
// location of a symbol's name is the first "real" use. |
| 886 |
auto sorter{[](SymbolRef x, SymbolRef y) { |
| 887 |
return NameInModuleFile(*x).begin() < NameInModuleFile(*y).begin(); |
| 888 |
}}; |
| 889 |
std::sort(sorted.begin(), sorted.end(), sorter); |
| 890 |
std::sort(generics.begin(), generics.end(), sorter); |
| 891 |
sorted.insert(sorted.end(), generics.begin(), generics.end()); |
| 892 |
sorted.insert(sorted.end(), namelist.begin(), namelist.end()); |
| 893 |
for (const auto &pair : scope.commonBlocks()) { |
| 894 |
sorted.push_back(*pair.second); |
| 895 |
} |
| 896 |
std::sort( |
| 897 |
sorted.end() - commonSize, sorted.end(), SymbolSourcePositionCompare{}); |
| 898 |
} |
| 899 |
|
| 900 |
void ModFileWriter::PutEntity(llvm::raw_ostream &os, const Symbol &symbol) { |
| 901 |
common::visit( |
| 902 |
common::visitors{ |
| 903 |
[&](const ObjectEntityDetails &) { PutObjectEntity(os, symbol); }, |
| 904 |
[&](const ProcEntityDetails &) { PutProcEntity(os, symbol); }, |
| 905 |
[&](const TypeParamDetails &) { PutTypeParam(os, symbol); }, |
| 906 |
[&](const auto &) { |
| 907 |
common::die("PutEntity: unexpected details: %s", |
| 908 |
DetailsToString(symbol.details()).c_str()); |
| 909 |
}, |
| 910 |
}, |
| 911 |
symbol.details()); |
| 912 |
} |
| 913 |
|
| 914 |
void PutShapeSpec(llvm::raw_ostream &os, const ShapeSpec &x) { |
| 915 |
if (x.lbound().isStar()) { |
| 916 |
CHECK(x.ubound().isStar()); |
| 917 |
os << ".."; // assumed rank |
| 918 |
} else { |
| 919 |
if (!x.lbound().isColon()) { |
| 920 |
PutBound(os, x.lbound()); |
| 921 |
} |
| 922 |
os << ':'; |
| 923 |
if (!x.ubound().isColon()) { |
| 924 |
PutBound(os, x.ubound()); |
| 925 |
} |
| 926 |
} |
| 927 |
} |
| 928 |
void PutShape( |
| 929 |
llvm::raw_ostream &os, const ArraySpec &shape, char open, char close) { |
| 930 |
if (!shape.empty()) { |
| 931 |
os << open; |
| 932 |
bool first{true}; |
| 933 |
for (const auto &shapeSpec : shape) { |
| 934 |
if (first) { |
| 935 |
first = false; |
| 936 |
} else { |
| 937 |
os << ','; |
| 938 |
} |
| 939 |
PutShapeSpec(os, shapeSpec); |
| 940 |
} |
| 941 |
os << close; |
| 942 |
} |
| 943 |
} |
| 944 |
|
| 945 |
void ModFileWriter::PutObjectEntity( |
| 946 |
llvm::raw_ostream &os, const Symbol &symbol) { |
| 947 |
auto &details{symbol.get<ObjectEntityDetails>()}; |
| 948 |
if (details.type() && |
| 949 |
details.type()->category() == DeclTypeSpec::TypeDerived) { |
| 950 |
const Symbol &typeSymbol{details.type()->derivedTypeSpec().typeSymbol()}; |
| 951 |
if (typeSymbol.get<DerivedTypeDetails>().isDECStructure()) { |
| 952 |
PutDerivedType(typeSymbol, &symbol.owner()); |
| 953 |
if (emittedDECFields_.find(symbol) != emittedDECFields_.end()) { |
| 954 |
return; // symbol was emitted on STRUCTURE statement |
| 955 |
} |
| 956 |
} |
| 957 |
} |
| 958 |
PutEntity( |
| 959 |
os, symbol, [&]() { PutType(os, DEREF(symbol.GetType())); }, |
| 960 |
getSymbolAttrsToWrite(symbol)); |
| 961 |
PutShape(os, details.shape(), '(', ')'); |
| 962 |
PutShape(os, details.coshape(), '[', ']'); |
| 963 |
PutInit(os, symbol, details.init(), details.unanalyzedPDTComponentInit()); |
| 964 |
os << '\n'; |
| 965 |
if (auto tkr{GetIgnoreTKR(symbol)}; !tkr.empty()) { |
| 966 |
os << "!dir$ ignore_tkr("; |
| 967 |
tkr.IterateOverMembers([&](common::IgnoreTKR tkr) { |
| 968 |
switch (tkr) { |
| 969 |
SWITCH_COVERS_ALL_CASES |
| 970 |
case common::IgnoreTKR::Type: |
| 971 |
os << 't'; |
| 972 |
break; |
| 973 |
case common::IgnoreTKR::Kind: |
| 974 |
os << 'k'; |
| 975 |
break; |
| 976 |
case common::IgnoreTKR::Rank: |
| 977 |
os << 'r'; |
| 978 |
break; |
| 979 |
case common::IgnoreTKR::Device: |
| 980 |
os << 'd'; |
| 981 |
break; |
| 982 |
case common::IgnoreTKR::Managed: |
| 983 |
os << 'm'; |
| 984 |
break; |
| 985 |
case common::IgnoreTKR::Contiguous: |
| 986 |
os << 'c'; |
| 987 |
break; |
| 988 |
} |
| 989 |
}); |
| 990 |
os << ") " << symbol.name() << '\n'; |
| 991 |
} |
| 992 |
if (auto attr{details.cudaDataAttr()}) { |
| 993 |
PutLower(os << "attributes(", common::EnumToString(*attr)) |
| 994 |
<< ") " << symbol.name() << '\n'; |
| 995 |
} |
| 996 |
if (symbol.test(Fortran::semantics::Symbol::Flag::CrayPointer)) { |
| 997 |
if (!symbol.owner().crayPointers().empty()) { |
| 998 |
for (const auto &[pointee, pointer] : symbol.owner().crayPointers()) { |
| 999 |
if (pointer == symbol) { |
| 1000 |
os << "pointer(" << symbol.name() << "," << pointee << ")\n"; |
| 1001 |
} |
| 1002 |
} |
| 1003 |
} |
| 1004 |
} |
| 1005 |
} |
| 1006 |
|
| 1007 |
void ModFileWriter::PutProcEntity(llvm::raw_ostream &os, const Symbol &symbol) { |
| 1008 |
if (symbol.attrs().test(Attr::INTRINSIC)) { |
| 1009 |
os << "intrinsic::" << symbol.name() << '\n'; |
| 1010 |
if (!isSubmodule_ && symbol.attrs().test(Attr::PRIVATE)) { |
| 1011 |
os << "private::" << symbol.name() << '\n'; |
| 1012 |
} |
| 1013 |
return; |
| 1014 |
} |
| 1015 |
const auto &details{symbol.get<ProcEntityDetails>()}; |
| 1016 |
Attrs attrs{symbol.attrs()}; |
| 1017 |
if (details.passName()) { |
| 1018 |
attrs.reset(Attr::PASS); |
| 1019 |
} |
| 1020 |
PutEntity( |
| 1021 |
os, symbol, |
| 1022 |
[&]() { |
| 1023 |
os << "procedure("; |
| 1024 |
if (details.rawProcInterface()) { |
| 1025 |
os << details.rawProcInterface()->name(); |
| 1026 |
} else if (details.type()) { |
| 1027 |
PutType(os, *details.type()); |
| 1028 |
} |
| 1029 |
os << ')'; |
| 1030 |
PutPassName(os, details.passName()); |
| 1031 |
}, |
| 1032 |
attrs); |
| 1033 |
os << '\n'; |
| 1034 |
} |
| 1035 |
|
| 1036 |
void PutPassName( |
| 1037 |
llvm::raw_ostream &os, const std::optional<SourceName> &passName) { |
| 1038 |
if (passName) { |
| 1039 |
os << ",pass(" << *passName << ')'; |
| 1040 |
} |
| 1041 |
} |
| 1042 |
|
| 1043 |
void ModFileWriter::PutTypeParam(llvm::raw_ostream &os, const Symbol &symbol) { |
| 1044 |
auto &details{symbol.get<TypeParamDetails>()}; |
| 1045 |
PutEntity( |
| 1046 |
os, symbol, |
| 1047 |
[&]() { |
| 1048 |
PutType(os, DEREF(symbol.GetType())); |
| 1049 |
PutLower(os << ',', common::EnumToString(details.attr())); |
| 1050 |
}, |
| 1051 |
symbol.attrs()); |
| 1052 |
PutInit(os, details.init()); |
| 1053 |
os << '\n'; |
| 1054 |
} |
| 1055 |
|
| 1056 |
void PutInit(llvm::raw_ostream &os, const Symbol &symbol, const MaybeExpr &init, |
| 1057 |
const parser::Expr *unanalyzed) { |
| 1058 |
if (IsNamedConstant(symbol) || symbol.owner().IsDerivedType()) { |
| 1059 |
const char *assign{symbol.attrs().test(Attr::POINTER) ? "=>" : "="}; |
| 1060 |
if (unanalyzed) { |
| 1061 |
parser::Unparse(os << assign, *unanalyzed); |
| 1062 |
} else if (init) { |
| 1063 |
init->AsFortran(os << assign); |
| 1064 |
} |
| 1065 |
} |
| 1066 |
} |
| 1067 |
|
| 1068 |
void PutInit(llvm::raw_ostream &os, const MaybeIntExpr &init) { |
| 1069 |
if (init) { |
| 1070 |
init->AsFortran(os << '='); |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
void PutBound(llvm::raw_ostream &os, const Bound &x) { |
| 1075 |
if (x.isStar()) { |
| 1076 |
os << '*'; |
| 1077 |
} else if (x.isColon()) { |
| 1078 |
os << ':'; |
| 1079 |
} else { |
| 1080 |
x.GetExplicit()->AsFortran(os); |
| 1081 |
} |
| 1082 |
} |
| 1083 |
|
| 1084 |
// Write an entity (object or procedure) declaration. |
| 1085 |
// writeType is called to write out the type. |
| 1086 |
void ModFileWriter::PutEntity(llvm::raw_ostream &os, const Symbol &symbol, |
| 1087 |
std::function<void()> writeType, Attrs attrs) { |
| 1088 |
writeType(); |
| 1089 |
PutAttrs(os, attrs, symbol.GetBindName(), symbol.GetIsExplicitBindName()); |
| 1090 |
if (symbol.owner().kind() == Scope::Kind::DerivedType && |
| 1091 |
context_.IsTempName(symbol.name().ToString())) { |
| 1092 |
os << "::%FILL"; |
| 1093 |
} else { |
| 1094 |
os << "::" << symbol.name(); |
| 1095 |
} |
| 1096 |
} |
| 1097 |
|
| 1098 |
// Put out each attribute to os, surrounded by `before` and `after` and |
| 1099 |
// mapped to lower case. |
| 1100 |
llvm::raw_ostream &ModFileWriter::PutAttrs(llvm::raw_ostream &os, Attrs attrs, |
| 1101 |
const std::string *bindName, bool isExplicitBindName, std::string before, |
| 1102 |
std::string after) const { |
| 1103 |
attrs.set(Attr::PUBLIC, false); // no need to write PUBLIC |
| 1104 |
attrs.set(Attr::EXTERNAL, false); // no need to write EXTERNAL |
| 1105 |
if (isSubmodule_) { |
| 1106 |
attrs.set(Attr::PRIVATE, false); |
| 1107 |
} |
| 1108 |
if (bindName || isExplicitBindName) { |
| 1109 |
os << before << "bind(c"; |
| 1110 |
if (isExplicitBindName) { |
| 1111 |
os << ",name=\"" << (bindName ? *bindName : ""s) << '"'; |
| 1112 |
} |
| 1113 |
os << ')' << after; |
| 1114 |
attrs.set(Attr::BIND_C, false); |
| 1115 |
} |
| 1116 |
for (std::size_t i{0}; i < Attr_enumSize; ++i) { |
| 1117 |
Attr attr{static_cast<Attr>(i)}; |
| 1118 |
if (attrs.test(attr)) { |
| 1119 |
PutAttr(os << before, attr) << after; |
| 1120 |
} |
| 1121 |
} |
| 1122 |
return os; |
| 1123 |
} |
| 1124 |
|
| 1125 |
llvm::raw_ostream &PutAttr(llvm::raw_ostream &os, Attr attr) { |
| 1126 |
return PutLower(os, AttrToString(attr)); |
| 1127 |
} |
| 1128 |
|
| 1129 |
llvm::raw_ostream &PutType(llvm::raw_ostream &os, const DeclTypeSpec &type) { |
| 1130 |
return PutLower(os, type.AsFortran()); |
| 1131 |
} |
| 1132 |
|
| 1133 |
llvm::raw_ostream &PutLower(llvm::raw_ostream &os, std::string_view str) { |
| 1134 |
for (char c : str) { |
| 1135 |
os << parser::ToLowerCaseLetter(c); |
| 1136 |
} |
| 1137 |
return os; |
| 1138 |
} |
| 1139 |
|
| 1140 |
void PutOpenACCDirective(llvm::raw_ostream &os, const Symbol &symbol) { |
| 1141 |
if (symbol.test(Symbol::Flag::AccDeclare)) { |
| 1142 |
os << "!$acc declare "; |
| 1143 |
if (symbol.test(Symbol::Flag::AccCopy)) { |
| 1144 |
os << "copy"; |
| 1145 |
} else if (symbol.test(Symbol::Flag::AccCopyIn) || |
| 1146 |
symbol.test(Symbol::Flag::AccCopyInReadOnly)) { |
| 1147 |
os << "copyin"; |
| 1148 |
} else if (symbol.test(Symbol::Flag::AccCopyOut)) { |
| 1149 |
os << "copyout"; |
| 1150 |
} else if (symbol.test(Symbol::Flag::AccCreate)) { |
| 1151 |
os << "create"; |
| 1152 |
} else if (symbol.test(Symbol::Flag::AccPresent)) { |
| 1153 |
os << "present"; |
| 1154 |
} else if (symbol.test(Symbol::Flag::AccDevicePtr)) { |
| 1155 |
os << "deviceptr"; |
| 1156 |
} else if (symbol.test(Symbol::Flag::AccDeviceResident)) { |
| 1157 |
os << "device_resident"; |
| 1158 |
} else if (symbol.test(Symbol::Flag::AccLink)) { |
| 1159 |
os << "link"; |
| 1160 |
} |
| 1161 |
os << "("; |
| 1162 |
if (symbol.test(Symbol::Flag::AccCopyInReadOnly)) { |
| 1163 |
os << "readonly: "; |
| 1164 |
} |
| 1165 |
os << symbol.name() << ")\n"; |
| 1166 |
} |
| 1167 |
} |
| 1168 |
|
| 1169 |
void PutOpenMPDirective(llvm::raw_ostream &os, const Symbol &symbol) { |
| 1170 |
if (symbol.test(Symbol::Flag::OmpThreadprivate)) { |
| 1171 |
os << "!$omp threadprivate(" << symbol.name() << ")\n"; |
| 1172 |
} |
| 1173 |
} |
| 1174 |
|
| 1175 |
void ModFileWriter::PutDirective(llvm::raw_ostream &os, const Symbol &symbol) { |
| 1176 |
PutOpenACCDirective(os, symbol); |
| 1177 |
PutOpenMPDirective(os, symbol); |
| 1178 |
} |
| 1179 |
|
| 1180 |
struct Temp { |
| 1181 |
Temp(int fd, std::string path) : fd{fd}, path{path} {} |
| 1182 |
Temp(Temp &&t) : fd{std::exchange(t.fd, -1)}, path{std::move(t.path)} {} |
| 1183 |
~Temp() { |
| 1184 |
if (fd >= 0) { |
| 1185 |
llvm::sys::fs::file_t native{llvm::sys::fs::convertFDToNativeFile(fd)}; |
| 1186 |
llvm::sys::fs::closeFile(native); |
| 1187 |
llvm::sys::fs::remove(path.c_str()); |
| 1188 |
} |
| 1189 |
} |
| 1190 |
int fd; |
| 1191 |
std::string path; |
| 1192 |
}; |
| 1193 |
|
| 1194 |
// Create a temp file in the same directory and with the same suffix as path. |
| 1195 |
// Return an open file descriptor and its path. |
| 1196 |
static llvm::ErrorOr<Temp> MkTemp(const std::string &path) { |
| 1197 |
auto length{path.length()}; |
| 1198 |
auto dot{path.find_last_of("./")}; |
| 1199 |
std::string suffix{ |
| 1200 |
dot < length && path[dot] == '.' ? path.substr(dot + 1) : ""}; |
| 1201 |
CHECK(length > suffix.length() && |
| 1202 |
path.substr(length - suffix.length()) == suffix); |
| 1203 |
auto prefix{path.substr(0, length - suffix.length())}; |
| 1204 |
int fd; |
| 1205 |
llvm::SmallString<16> tempPath; |
| 1206 |
if (std::error_code err{llvm::sys::fs::createUniqueFile( |
| 1207 |
prefix + "%%%%%%" + suffix, fd, tempPath)}) { |
| 1208 |
return err; |
| 1209 |
} |
| 1210 |
return Temp{fd, tempPath.c_str()}; |
| 1211 |
} |
| 1212 |
|
| 1213 |
// Write the module file at path, prepending header. If an error occurs, |
| 1214 |
// return errno, otherwise 0. |
| 1215 |
static std::error_code WriteFile(const std::string &path, |
| 1216 |
const std::string &contents, ModuleCheckSumType &checkSum, bool debug) { |
| 1217 |
checkSum = ComputeCheckSum(contents); |
| 1218 |
auto header{std::string{ModHeader::bom} + ModHeader::magic + |
| 1219 |
CheckSumString(checkSum) + ModHeader::terminator}; |
| 1220 |
if (debug) { |
| 1221 |
llvm::dbgs() << "Processing module " << path << ": "; |
| 1222 |
} |
| 1223 |
if (FileContentsMatch(path, header, contents)) { |
| 1224 |
if (debug) { |
| 1225 |
llvm::dbgs() << "module unchanged, not writing\n"; |
| 1226 |
} |
| 1227 |
return {}; |
| 1228 |
} |
| 1229 |
llvm::ErrorOr<Temp> temp{MkTemp(path)}; |
| 1230 |
if (!temp) { |
| 1231 |
return temp.getError(); |
| 1232 |
} |
| 1233 |
llvm::raw_fd_ostream writer(temp->fd, /*shouldClose=*/false); |
| 1234 |
writer << header; |
| 1235 |
writer << contents; |
| 1236 |
writer.flush(); |
| 1237 |
if (writer.has_error()) { |
| 1238 |
return writer.error(); |
| 1239 |
} |
| 1240 |
if (debug) { |
| 1241 |
llvm::dbgs() << "module written\n"; |
| 1242 |
} |
| 1243 |
return llvm::sys::fs::rename(temp->path, path); |
| 1244 |
} |
| 1245 |
|
| 1246 |
// Return true if the stream matches what we would write for the mod file. |
| 1247 |
static bool FileContentsMatch(const std::string &path, |
| 1248 |
const std::string &header, const std::string &contents) { |
| 1249 |
std::size_t hsize{header.size()}; |
| 1250 |
std::size_t csize{contents.size()}; |
| 1251 |
auto buf_or{llvm::MemoryBuffer::getFile(path)}; |
| 1252 |
if (!buf_or) { |
| 1253 |
return false; |
| 1254 |
} |
| 1255 |
auto buf = std::move(buf_or.get()); |
| 1256 |
if (buf->getBufferSize() != hsize + csize) { |
| 1257 |
return false; |
| 1258 |
} |
| 1259 |
if (!std::equal(header.begin(), header.end(), buf->getBufferStart(), |
| 1260 |
buf->getBufferStart() + hsize)) { |
| 1261 |
return false; |
| 1262 |
} |
| 1263 |
|
| 1264 |
return std::equal(contents.begin(), contents.end(), |
| 1265 |
buf->getBufferStart() + hsize, buf->getBufferEnd()); |
| 1266 |
} |
| 1267 |
|
| 1268 |
// Compute a simple hash of the contents of a module file and |
| 1269 |
// return it as a string of hex digits. |
| 1270 |
// This uses the Fowler-Noll-Vo hash function. |
| 1271 |
static ModuleCheckSumType ComputeCheckSum(const std::string_view &contents) { |
| 1272 |
ModuleCheckSumType hash{0xcbf29ce484222325ull}; |
| 1273 |
for (char c : contents) { |
| 1274 |
hash ^= c & 0xff; |
| 1275 |
hash *= 0x100000001b3; |
| 1276 |
} |
| 1277 |
return hash; |
| 1278 |
} |
| 1279 |
|
| 1280 |
static std::string CheckSumString(ModuleCheckSumType hash) { |
| 1281 |
static const char *digits = "0123456789abcdef"; |
| 1282 |
std::string result(ModHeader::sumLen, '0'); |
| 1283 |
for (size_t i{ModHeader::sumLen}; hash != 0; hash >>= 4) { |
| 1284 |
result[--i] = digits[hash & 0xf]; |
| 1285 |
} |
| 1286 |
return result; |
| 1287 |
} |
| 1288 |
|
| 1289 |
std::optional<ModuleCheckSumType> ExtractCheckSum(const std::string_view &str) { |
| 1290 |
if (str.size() == ModHeader::sumLen) { |
| 1291 |
ModuleCheckSumType hash{0}; |
| 1292 |
for (size_t j{0}; j < ModHeader::sumLen; ++j) { |
| 1293 |
hash <<= 4; |
| 1294 |
char ch{str.at(j)}; |
| 1295 |
if (ch >= '0' && ch <= '9') { |
| 1296 |
hash += ch - '0'; |
| 1297 |
} else if (ch >= 'a' && ch <= 'f') { |
| 1298 |
hash += ch - 'a' + 10; |
| 1299 |
} else { |
| 1300 |
return std::nullopt; |
| 1301 |
} |
| 1302 |
} |
| 1303 |
return hash; |
| 1304 |
} |
| 1305 |
return std::nullopt; |
| 1306 |
} |
| 1307 |
|
| 1308 |
static std::optional<ModuleCheckSumType> VerifyHeader( |
| 1309 |
llvm::ArrayRef<char> content) { |
| 1310 |
std::string_view sv{content.data(), content.size()}; |
| 1311 |
if (sv.substr(0, ModHeader::magicLen) != ModHeader::magic) { |
| 1312 |
return std::nullopt; |
| 1313 |
} |
| 1314 |
ModuleCheckSumType checkSum{ComputeCheckSum(sv.substr(ModHeader::len))}; |
| 1315 |
std::string_view expectSum{sv.substr(ModHeader::magicLen, ModHeader::sumLen)}; |
| 1316 |
if (auto extracted{ExtractCheckSum(expectSum)}; |
| 1317 |
extracted && *extracted == checkSum) { |
| 1318 |
return checkSum; |
| 1319 |
} else { |
| 1320 |
return std::nullopt; |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
static void GetModuleDependences( |
| 1325 |
ModuleDependences &dependences, llvm::ArrayRef<char> content) { |
| 1326 |
std::size_t limit{content.size()}; |
| 1327 |
std::string_view str{content.data(), limit}; |
| 1328 |
for (std::size_t j{ModHeader::len}; |
| 1329 |
str.substr(j, ModHeader::needLen) == ModHeader::need; ++j) { |
| 1330 |
j += 7; |
| 1331 |
auto checkSum{ExtractCheckSum(str.substr(j, ModHeader::sumLen))}; |
| 1332 |
if (!checkSum) { |
| 1333 |
break; |
| 1334 |
} |
| 1335 |
j += ModHeader::sumLen; |
| 1336 |
bool intrinsic{false}; |
| 1337 |
if (str.substr(j, 3) == " i ") { |
| 1338 |
intrinsic = true; |
| 1339 |
} else if (str.substr(j, 3) != " n ") { |
| 1340 |
break; |
| 1341 |
} |
| 1342 |
j += 3; |
| 1343 |
std::size_t start{j}; |
| 1344 |
for (; j < limit && str.at(j) != '\n'; ++j) { |
| 1345 |
} |
| 1346 |
if (j > start && j < limit && str.at(j) == '\n') { |
| 1347 |
std::string depModName{str.substr(start, j - start)}; |
| 1348 |
dependences.AddDependence(std::move(depModName), intrinsic, *checkSum); |
| 1349 |
} else { |
| 1350 |
break; |
| 1351 |
} |
| 1352 |
} |
| 1353 |
} |
| 1354 |
|
| 1355 |
Scope *ModFileReader::Read(SourceName name, std::optional<bool> isIntrinsic, |
| 1356 |
Scope *ancestor, bool silent) { |
| 1357 |
std::string ancestorName; // empty for module |
| 1358 |
const Symbol *notAModule{nullptr}; |
| 1359 |
bool fatalError{false}; |
| 1360 |
if (ancestor) { |
| 1361 |
if (auto *scope{ancestor->FindSubmodule(name)}) { |
| 1362 |
return scope; |
| 1363 |
} |
| 1364 |
ancestorName = ancestor->GetName().value().ToString(); |
| 1365 |
} |
| 1366 |
auto requiredHash{context_.moduleDependences().GetRequiredHash( |
| 1367 |
name.ToString(), isIntrinsic.value_or(false))}; |
| 1368 |
if (!isIntrinsic.value_or(false) && !ancestor) { |
| 1369 |
// Already present in the symbol table as a usable non-intrinsic module? |
| 1370 |
auto it{context_.globalScope().find(name)}; |
| 1371 |
if (it != context_.globalScope().end()) { |
| 1372 |
Scope *scope{it->second->scope()}; |
| 1373 |
if (scope->kind() == Scope::Kind::Module) { |
| 1374 |
for (const Symbol *found{scope->symbol()}; found;) { |
| 1375 |
if (const auto *module{found->detailsIf<ModuleDetails>()}) { |
| 1376 |
if (!requiredHash || |
| 1377 |
*requiredHash == |
| 1378 |
module->moduleFileHash().value_or(*requiredHash)) { |
| 1379 |
return const_cast<Scope *>(found->scope()); |
| 1380 |
} |
| 1381 |
found = module->previous(); // same name, distinct hash |
| 1382 |
} else { |
| 1383 |
notAModule = found; |
| 1384 |
break; |
| 1385 |
} |
| 1386 |
} |
| 1387 |
} else { |
| 1388 |
notAModule = scope->symbol(); |
| 1389 |
} |
| 1390 |
} |
| 1391 |
} |
| 1392 |
if (notAModule) { |
| 1393 |
// USE, NON_INTRINSIC global name isn't a module? |
| 1394 |
fatalError = isIntrinsic.has_value(); |
| 1395 |
} |
| 1396 |
auto path{ModFileName(name, ancestorName, context_.moduleFileSuffix())}; |
| 1397 |
parser::Parsing parsing{context_.allCookedSources()}; |
| 1398 |
parser::Options options; |
| 1399 |
options.isModuleFile = true; |
| 1400 |
options.features.Enable(common::LanguageFeature::BackslashEscapes); |
| 1401 |
options.features.Enable(common::LanguageFeature::OpenMP); |
| 1402 |
options.features.Enable(common::LanguageFeature::CUDA); |
| 1403 |
if (!isIntrinsic.value_or(false) && !notAModule) { |
| 1404 |
// The search for this module file will scan non-intrinsic module |
| 1405 |
// directories. If a directory is in both the intrinsic and non-intrinsic |
| 1406 |
// directory lists, the intrinsic module directory takes precedence. |
| 1407 |
options.searchDirectories = context_.searchDirectories(); |
| 1408 |
for (const auto &dir : context_.intrinsicModuleDirectories()) { |
| 1409 |
options.searchDirectories.erase( |
| 1410 |
std::remove(options.searchDirectories.begin(), |
| 1411 |
options.searchDirectories.end(), dir), |
| 1412 |
options.searchDirectories.end()); |
| 1413 |
} |
| 1414 |
options.searchDirectories.insert(options.searchDirectories.begin(), "."s); |
| 1415 |
} |
| 1416 |
bool foundNonIntrinsicModuleFile{false}; |
| 1417 |
if (!isIntrinsic) { |
| 1418 |
std::list<std::string> searchDirs; |
| 1419 |
for (const auto &d : options.searchDirectories) { |
| 1420 |
searchDirs.push_back(d); |
| 1421 |
} |
| 1422 |
foundNonIntrinsicModuleFile = |
| 1423 |
parser::LocateSourceFile(path, searchDirs).has_value(); |
| 1424 |
} |
| 1425 |
if (isIntrinsic.value_or(!foundNonIntrinsicModuleFile)) { |
| 1426 |
// Explicitly intrinsic, or not specified and not found in the search |
| 1427 |
// path; see whether it's already in the symbol table as an intrinsic |
| 1428 |
// module. |
| 1429 |
auto it{context_.intrinsicModulesScope().find(name)}; |
| 1430 |
if (it != context_.intrinsicModulesScope().end()) { |
| 1431 |
return it->second->scope(); |
| 1432 |
} |
| 1433 |
} |
| 1434 |
// We don't have this module in the symbol table yet. |
| 1435 |
// Find its module file and parse it. Define or extend the search |
| 1436 |
// path with intrinsic module directories, if appropriate. |
| 1437 |
if (isIntrinsic.value_or(true)) { |
| 1438 |
for (const auto &dir : context_.intrinsicModuleDirectories()) { |
| 1439 |
options.searchDirectories.push_back(dir); |
| 1440 |
} |
| 1441 |
if (!requiredHash) { |
| 1442 |
requiredHash = |
| 1443 |
context_.moduleDependences().GetRequiredHash(name.ToString(), true); |
| 1444 |
} |
| 1445 |
} |
| 1446 |
|
| 1447 |
// Look for the right module file if its hash is known |
| 1448 |
if (requiredHash && !fatalError) { |
| 1449 |
for (const std::string &maybe : |
| 1450 |
parser::LocateSourceFileAll(path, options.searchDirectories)) { |
| 1451 |
if (const auto *srcFile{context_.allCookedSources().allSources().OpenPath( |
| 1452 |
maybe, llvm::errs())}) { |
| 1453 |
if (auto checkSum{VerifyHeader(srcFile->content())}; |
| 1454 |
checkSum && *checkSum == *requiredHash) { |
| 1455 |
path = maybe; |
| 1456 |
break; |
| 1457 |
} |
| 1458 |
} |
| 1459 |
} |
| 1460 |
} |
| 1461 |
const auto *sourceFile{fatalError ? nullptr : parsing.Prescan(path, options)}; |
| 1462 |
if (fatalError || parsing.messages().AnyFatalError()) { |
| 1463 |
if (!silent) { |
| 1464 |
if (notAModule) { |
| 1465 |
// Module is not explicitly INTRINSIC, and there's already a global |
| 1466 |
// symbol of the same name that is not a module. |
| 1467 |
context_.SayWithDecl( |
| 1468 |
*notAModule, name, "'%s' is not a module"_err_en_US, name); |
| 1469 |
} else { |
| 1470 |
for (auto &msg : parsing.messages().messages()) { |
| 1471 |
std::string str{msg.ToString()}; |
| 1472 |
Say(name, ancestorName, |
| 1473 |
parser::MessageFixedText{str.c_str(), str.size(), msg.severity()}, |
| 1474 |
path); |
| 1475 |
} |
| 1476 |
} |
| 1477 |
} |
| 1478 |
return nullptr; |
| 1479 |
} |
| 1480 |
CHECK(sourceFile); |
| 1481 |
std::optional<ModuleCheckSumType> checkSum{ |
| 1482 |
VerifyHeader(sourceFile->content())}; |
| 1483 |
if (!checkSum) { |
| 1484 |
if (context_.ShouldWarn(common::UsageWarning::ModuleFile)) { |
| 1485 |
Say(name, ancestorName, "File has invalid checksum: %s"_warn_en_US, |
| 1486 |
sourceFile->path()); |
| 1487 |
} |
| 1488 |
return nullptr; |
| 1489 |
} else if (requiredHash && *requiredHash != *checkSum) { |
| 1490 |
if (context_.ShouldWarn(common::UsageWarning::ModuleFile)) { |
| 1491 |
Say(name, ancestorName, |
| 1492 |
"File is not the right module file for %s"_warn_en_US, |
| 1493 |
"'"s + name.ToString() + "': "s + sourceFile->path()); |
| 1494 |
} |
| 1495 |
return nullptr; |
| 1496 |
} |
| 1497 |
llvm::raw_null_ostream NullStream; |
| 1498 |
parsing.Parse(NullStream); |
| 1499 |
std::optional<parser::Program> &parsedProgram{parsing.parseTree()}; |
| 1500 |
if (!parsing.messages().empty() || !parsing.consumedWholeFile() || |
| 1501 |
!parsedProgram) { |
| 1502 |
Say(name, ancestorName, "Module file is corrupt: %s"_err_en_US, |
| 1503 |
sourceFile->path()); |
| 1504 |
return nullptr; |
| 1505 |
} |
| 1506 |
parser::Program &parseTree{context_.SaveParseTree(std::move(*parsedProgram))}; |
| 1507 |
Scope *parentScope; // the scope this module/submodule goes into |
| 1508 |
if (!isIntrinsic.has_value()) { |
| 1509 |
for (const auto &dir : context_.intrinsicModuleDirectories()) { |
| 1510 |
if (sourceFile->path().size() > dir.size() && |
| 1511 |
sourceFile->path().find(dir) == 0) { |
| 1512 |
isIntrinsic = true; |
| 1513 |
break; |
| 1514 |
} |
| 1515 |
} |
| 1516 |
} |
| 1517 |
Scope &topScope{isIntrinsic.value_or(false) ? context_.intrinsicModulesScope() |
| 1518 |
: context_.globalScope()}; |
| 1519 |
Symbol *moduleSymbol{nullptr}; |
| 1520 |
const Symbol *previousModuleSymbol{nullptr}; |
| 1521 |
if (!ancestor) { // module, not submodule |
| 1522 |
parentScope = &topScope; |
| 1523 |
auto pair{parentScope->try_emplace(name, UnknownDetails{})}; |
| 1524 |
if (!pair.second) { |
| 1525 |
// There is already a global symbol or intrinsic module of the same name. |
| 1526 |
previousModuleSymbol = &*pair.first->second; |
| 1527 |
if (const auto *details{ |
| 1528 |
previousModuleSymbol->detailsIf<ModuleDetails>()}) { |
| 1529 |
if (!details->moduleFileHash().has_value()) { |
| 1530 |
return nullptr; |
| 1531 |
} |
| 1532 |
} else { |
| 1533 |
return nullptr; |
| 1534 |
} |
| 1535 |
CHECK(parentScope->erase(name) != 0); |
| 1536 |
pair = parentScope->try_emplace(name, UnknownDetails{}); |
| 1537 |
CHECK(pair.second); |
| 1538 |
} |
| 1539 |
moduleSymbol = &*pair.first->second; |
| 1540 |
moduleSymbol->set(Symbol::Flag::ModFile); |
| 1541 |
} else if (std::optional<SourceName> parent{GetSubmoduleParent(parseTree)}) { |
| 1542 |
// submodule with submodule parent |
| 1543 |
parentScope = Read(*parent, false /*not intrinsic*/, ancestor, silent); |
| 1544 |
} else { |
| 1545 |
// submodule with module parent |
| 1546 |
parentScope = ancestor; |
| 1547 |
} |
| 1548 |
// Process declarations from the module file |
| 1549 |
auto wasModuleFileName{context_.foldingContext().moduleFileName()}; |
| 1550 |
context_.foldingContext().set_moduleFileName(name); |
| 1551 |
GetModuleDependences(context_.moduleDependences(), sourceFile->content()); |
| 1552 |
ResolveNames(context_, parseTree, topScope); |
| 1553 |
context_.foldingContext().set_moduleFileName(wasModuleFileName); |
| 1554 |
if (!moduleSymbol) { |
| 1555 |
// Submodule symbols' storage are owned by their parents' scopes, |
| 1556 |
// but their names are not in their parents' dictionaries -- we |
| 1557 |
// don't want to report bogus errors about clashes between submodule |
| 1558 |
// names and other objects in the parent scopes. |
| 1559 |
if (Scope * submoduleScope{ancestor->FindSubmodule(name)}) { |
| 1560 |
moduleSymbol = submoduleScope->symbol(); |
| 1561 |
if (moduleSymbol) { |
| 1562 |
moduleSymbol->set(Symbol::Flag::ModFile); |
| 1563 |
} |
| 1564 |
} |
| 1565 |
} |
| 1566 |
if (moduleSymbol) { |
| 1567 |
CHECK(moduleSymbol->test(Symbol::Flag::ModFile)); |
| 1568 |
auto &details{moduleSymbol->get<ModuleDetails>()}; |
| 1569 |
details.set_moduleFileHash(checkSum.value()); |
| 1570 |
details.set_previous(previousModuleSymbol); |
| 1571 |
if (isIntrinsic.value_or(false)) { |
| 1572 |
moduleSymbol->attrs().set(Attr::INTRINSIC); |
| 1573 |
} |
| 1574 |
return moduleSymbol->scope(); |
| 1575 |
} else { |
| 1576 |
return nullptr; |
| 1577 |
} |
| 1578 |
} |
| 1579 |
|
| 1580 |
parser::Message &ModFileReader::Say(SourceName name, |
| 1581 |
const std::string &ancestor, parser::MessageFixedText &&msg, |
| 1582 |
const std::string &arg) { |
| 1583 |
return context_.Say(name, "Cannot read module file for %s: %s"_err_en_US, |
| 1584 |
parser::MessageFormattedText{ancestor.empty() |
| 1585 |
? "module '%s'"_en_US |
| 1586 |
: "submodule '%s' of module '%s'"_en_US, |
| 1587 |
name, ancestor} |
| 1588 |
.MoveString(), |
| 1589 |
parser::MessageFormattedText{std::move(msg), arg}.MoveString()); |
| 1590 |
} |
| 1591 |
|
| 1592 |
// program was read from a .mod file for a submodule; return the name of the |
| 1593 |
// submodule's parent submodule, nullptr if none. |
| 1594 |
static std::optional<SourceName> GetSubmoduleParent( |
| 1595 |
const parser::Program &program) { |
| 1596 |
CHECK(program.v.size() == 1); |
| 1597 |
auto &unit{program.v.front()}; |
| 1598 |
auto &submod{std::get<common::Indirection<parser::Submodule>>(unit.u)}; |
| 1599 |
auto &stmt{ |
| 1600 |
std::get<parser::Statement<parser::SubmoduleStmt>>(submod.value().t)}; |
| 1601 |
auto &parentId{std::get<parser::ParentIdentifier>(stmt.statement.t)}; |
| 1602 |
if (auto &parent{std::get<std::optional<parser::Name>>(parentId.t)}) { |
| 1603 |
return parent->source; |
| 1604 |
} else { |
| 1605 |
return std::nullopt; |
| 1606 |
} |
| 1607 |
} |
| 1608 |
|
| 1609 |
void SubprogramSymbolCollector::Collect() { |
| 1610 |
const auto &details{symbol_.get<SubprogramDetails>()}; |
| 1611 |
isInterface_ = details.isInterface(); |
| 1612 |
for (const Symbol *dummyArg : details.dummyArgs()) { |
| 1613 |
if (dummyArg) { |
| 1614 |
DoSymbol(*dummyArg); |
| 1615 |
} |
| 1616 |
} |
| 1617 |
if (details.isFunction()) { |
| 1618 |
DoSymbol(details.result()); |
| 1619 |
} |
| 1620 |
for (const auto &pair : scope_) { |
| 1621 |
const Symbol &symbol{*pair.second}; |
| 1622 |
if (const auto *useDetails{symbol.detailsIf<UseDetails>()}) { |
| 1623 |
const Symbol &ultimate{useDetails->symbol().GetUltimate()}; |
| 1624 |
bool needed{useSet_.count(ultimate) > 0}; |
| 1625 |
if (const auto *generic{ultimate.detailsIf<GenericDetails>()}) { |
| 1626 |
// The generic may not be needed itself, but the specific procedure |
| 1627 |
// &/or derived type that it shadows may be needed. |
| 1628 |
const Symbol *spec{generic->specific()}; |
| 1629 |
const Symbol *dt{generic->derivedType()}; |
| 1630 |
needed = needed || (spec && useSet_.count(*spec) > 0) || |
| 1631 |
(dt && useSet_.count(*dt) > 0); |
| 1632 |
} else if (const auto *subp{ultimate.detailsIf<SubprogramDetails>()}) { |
| 1633 |
const Symbol *interface { subp->moduleInterface() }; |
| 1634 |
needed = needed || (interface && useSet_.count(*interface) > 0); |
| 1635 |
} |
| 1636 |
if (needed) { |
| 1637 |
need_.push_back(symbol); |
| 1638 |
} |
| 1639 |
} else if (symbol.has<SubprogramDetails>()) { |
| 1640 |
// An internal subprogram is needed if it is used as interface |
| 1641 |
// for a dummy or return value procedure. |
| 1642 |
bool needed{false}; |
| 1643 |
const auto hasInterface{[&symbol](const Symbol *s) -> bool { |
| 1644 |
// Is 's' a procedure with interface 'symbol'? |
| 1645 |
if (s) { |
| 1646 |
if (const auto *sDetails{s->detailsIf<ProcEntityDetails>()}) { |
| 1647 |
if (sDetails->procInterface() == &symbol) { |
| 1648 |
return true; |
| 1649 |
} |
| 1650 |
} |
| 1651 |
} |
| 1652 |
return false; |
| 1653 |
}}; |
| 1654 |
for (const Symbol *dummyArg : details.dummyArgs()) { |
| 1655 |
needed = needed || hasInterface(dummyArg); |
| 1656 |
} |
| 1657 |
needed = |
| 1658 |
needed || (details.isFunction() && hasInterface(&details.result())); |
| 1659 |
if (needed && needSet_.insert(symbol).second) { |
| 1660 |
need_.push_back(symbol); |
| 1661 |
} |
| 1662 |
} |
| 1663 |
} |
| 1664 |
} |
| 1665 |
|
| 1666 |
void SubprogramSymbolCollector::DoSymbol(const Symbol &symbol) { |
| 1667 |
DoSymbol(symbol.name(), symbol); |
| 1668 |
} |
| 1669 |
|
| 1670 |
// Do symbols this one depends on; then add to need_ |
| 1671 |
void SubprogramSymbolCollector::DoSymbol( |
| 1672 |
const SourceName &name, const Symbol &symbol) { |
| 1673 |
const auto &scope{symbol.owner()}; |
| 1674 |
if (scope != scope_ && !scope.IsDerivedType()) { |
| 1675 |
if (scope != scope_.parent()) { |
| 1676 |
useSet_.insert(symbol); |
| 1677 |
} |
| 1678 |
if (NeedImport(name, symbol)) { |
| 1679 |
imports_.insert(name); |
| 1680 |
} |
| 1681 |
return; |
| 1682 |
} |
| 1683 |
if (!needSet_.insert(symbol).second) { |
| 1684 |
return; // already done |
| 1685 |
} |
| 1686 |
common::visit(common::visitors{ |
| 1687 |
[this](const ObjectEntityDetails &details) { |
| 1688 |
for (const ShapeSpec &spec : details.shape()) { |
| 1689 |
DoBound(spec.lbound()); |
| 1690 |
DoBound(spec.ubound()); |
| 1691 |
} |
| 1692 |
for (const ShapeSpec &spec : details.coshape()) { |
| 1693 |
DoBound(spec.lbound()); |
| 1694 |
DoBound(spec.ubound()); |
| 1695 |
} |
| 1696 |
if (const Symbol * commonBlock{details.commonBlock()}) { |
| 1697 |
DoSymbol(*commonBlock); |
| 1698 |
} |
| 1699 |
}, |
| 1700 |
[this](const CommonBlockDetails &details) { |
| 1701 |
for (const auto &object : details.objects()) { |
| 1702 |
DoSymbol(*object); |
| 1703 |
} |
| 1704 |
}, |
| 1705 |
[this](const ProcEntityDetails &details) { |
| 1706 |
if (details.rawProcInterface()) { |
| 1707 |
DoSymbol(*details.rawProcInterface()); |
| 1708 |
} else { |
| 1709 |
DoType(details.type()); |
| 1710 |
} |
| 1711 |
}, |
| 1712 |
[this](const ProcBindingDetails &details) { |
| 1713 |
DoSymbol(details.symbol()); |
| 1714 |
}, |
| 1715 |
[](const auto &) {}, |
| 1716 |
}, |
| 1717 |
symbol.details()); |
| 1718 |
if (!symbol.has<UseDetails>()) { |
| 1719 |
DoType(symbol.GetType()); |
| 1720 |
} |
| 1721 |
if (!scope.IsDerivedType()) { |
| 1722 |
need_.push_back(symbol); |
| 1723 |
} |
| 1724 |
} |
| 1725 |
|
| 1726 |
void SubprogramSymbolCollector::DoType(const DeclTypeSpec *type) { |
| 1727 |
if (!type) { |
| 1728 |
return; |
| 1729 |
} |
| 1730 |
switch (type->category()) { |
| 1731 |
case DeclTypeSpec::Numeric: |
| 1732 |
case DeclTypeSpec::Logical: |
| 1733 |
break; // nothing to do |
| 1734 |
case DeclTypeSpec::Character: |
| 1735 |
DoParamValue(type->characterTypeSpec().length()); |
| 1736 |
break; |
| 1737 |
default: |
| 1738 |
if (const DerivedTypeSpec * derived{type->AsDerived()}) { |
| 1739 |
const auto &typeSymbol{derived->typeSymbol()}; |
| 1740 |
for (const auto &pair : derived->parameters()) { |
| 1741 |
DoParamValue(pair.second); |
| 1742 |
} |
| 1743 |
// The components of the type (including its parent component, if |
| 1744 |
// any) matter to IMPORT symbol collection only for derived types |
| 1745 |
// defined in the subprogram. |
| 1746 |
if (typeSymbol.owner() == scope_) { |
| 1747 |
if (const DerivedTypeSpec * extends{typeSymbol.GetParentTypeSpec()}) { |
| 1748 |
DoSymbol(extends->name(), extends->typeSymbol()); |
| 1749 |
} |
| 1750 |
for (const auto &pair : *typeSymbol.scope()) { |
| 1751 |
DoSymbol(*pair.second); |
| 1752 |
} |
| 1753 |
} |
| 1754 |
DoSymbol(derived->name(), typeSymbol); |
| 1755 |
} |
| 1756 |
} |
| 1757 |
} |
| 1758 |
|
| 1759 |
void SubprogramSymbolCollector::DoBound(const Bound &bound) { |
| 1760 |
if (const MaybeSubscriptIntExpr & expr{bound.GetExplicit()}) { |
| 1761 |
DoExpr(*expr); |
| 1762 |
} |
| 1763 |
} |
| 1764 |
void SubprogramSymbolCollector::DoParamValue(const ParamValue ¶mValue) { |
| 1765 |
if (const auto &expr{paramValue.GetExplicit()}) { |
| 1766 |
DoExpr(*expr); |
| 1767 |
} |
| 1768 |
} |
| 1769 |
|
| 1770 |
// Do we need a IMPORT of this symbol into an interface block? |
| 1771 |
bool SubprogramSymbolCollector::NeedImport( |
| 1772 |
const SourceName &name, const Symbol &symbol) { |
| 1773 |
if (!isInterface_) { |
| 1774 |
return false; |
| 1775 |
} else if (IsSeparateModuleProcedureInterface(&symbol_)) { |
| 1776 |
return false; // IMPORT needed only for external and dummy procedure |
| 1777 |
// interfaces |
| 1778 |
} else if (&symbol == scope_.symbol()) { |
| 1779 |
return false; |
| 1780 |
} else if (symbol.owner().Contains(scope_)) { |
| 1781 |
return true; |
| 1782 |
} else if (const Symbol *found{scope_.FindSymbol(name)}) { |
| 1783 |
// detect import from ancestor of use-associated symbol |
| 1784 |
return found->has<UseDetails>() && found->owner() != scope_; |
| 1785 |
} else { |
| 1786 |
// "found" can be null in the case of a use-associated derived type's |
| 1787 |
// parent type |
| 1788 |
CHECK(symbol.has<DerivedTypeDetails>()); |
| 1789 |
return false; |
| 1790 |
} |
| 1791 |
} |
| 1792 |
|
| 1793 |
} // namespace Fortran::semantics |