1 //===--- Module.cpp - Describe a module -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Module class, which describes a module in the source
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/Module.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
27 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
28 bool IsFramework, bool IsExplicit, unsigned VisibilityID)
29 : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
30 Umbrella(), ASTFile(nullptr), VisibilityID(VisibilityID),
31 IsMissingRequirement(false), HasIncompatibleModuleFile(false),
32 IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
33 IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
34 IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
35 InferExportWildcard(false), ConfigMacrosExhaustive(false),
36 NoUndeclaredIncludes(false), NameVisibility(Hidden) {
38 if (!Parent->isAvailable())
42 if (Parent->IsExternC)
44 if (Parent->NoUndeclaredIncludes)
45 NoUndeclaredIncludes = true;
46 IsMissingRequirement = Parent->IsMissingRequirement;
48 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
49 Parent->SubModules.push_back(this);
54 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
60 /// \brief Determine whether a translation unit built using the current
61 /// language options has the given feature.
62 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
63 const TargetInfo &Target) {
64 bool HasFeature = llvm::StringSwitch<bool>(Feature)
65 .Case("altivec", LangOpts.AltiVec)
66 .Case("blocks", LangOpts.Blocks)
67 .Case("coroutines", LangOpts.CoroutinesTS)
68 .Case("cplusplus", LangOpts.CPlusPlus)
69 .Case("cplusplus11", LangOpts.CPlusPlus11)
70 .Case("freestanding", LangOpts.Freestanding)
71 .Case("gnuinlineasm", LangOpts.GNUAsm)
72 .Case("objc", LangOpts.ObjC1)
73 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
74 .Case("opencl", LangOpts.OpenCL)
75 .Case("tls", Target.isTLSSupported())
76 .Case("zvector", LangOpts.ZVector)
77 .Default(Target.hasFeature(Feature));
79 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
80 LangOpts.ModuleFeatures.end(),
81 Feature) != LangOpts.ModuleFeatures.end();
85 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
87 UnresolvedHeaderDirective &MissingHeader) const {
91 for (const Module *Current = this; Current; Current = Current->Parent) {
92 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
93 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
94 Current->Requirements[I].second) {
95 Req = Current->Requirements[I];
99 if (!Current->MissingHeaders.empty()) {
100 MissingHeader = Current->MissingHeaders.front();
105 llvm_unreachable("could not find a reason why module is unavailable");
108 bool Module::isSubModuleOf(const Module *Other) const {
109 const Module *This = this;
120 const Module *Module::getTopLevelModule() const {
121 const Module *Result = this;
122 while (Result->Parent)
123 Result = Result->Parent;
128 std::string Module::getFullModuleName() const {
129 SmallVector<StringRef, 2> Names;
131 // Build up the set of module names (from innermost to outermost).
132 for (const Module *M = this; M; M = M->Parent)
133 Names.push_back(M->Name);
136 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
148 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
149 for (const Module *M = this; M; M = M->Parent) {
150 if (nameParts.empty() || M->Name != nameParts.back())
152 nameParts = nameParts.drop_back();
154 return nameParts.empty();
157 Module::DirectoryName Module::getUmbrellaDir() const {
158 if (Header U = getUmbrellaHeader())
159 return {"", U.Entry->getDir()};
161 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
164 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
165 if (!TopHeaderNames.empty()) {
166 for (std::vector<std::string>::iterator
167 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
168 if (const FileEntry *FE = FileMgr.getFile(*I))
169 TopHeaders.insert(FE);
171 TopHeaderNames.clear();
174 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
177 bool Module::directlyUses(const Module *Requested) const {
178 auto *Top = getTopLevelModule();
180 // A top-level module implicitly uses itself.
181 if (Requested->isSubModuleOf(Top))
184 for (auto *Use : Top->DirectUses)
185 if (Requested->isSubModuleOf(Use))
188 // Anyone is allowed to use our builtin stddef.h and its accompanying module.
189 if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
195 void Module::addRequirement(StringRef Feature, bool RequiredState,
196 const LangOptions &LangOpts,
197 const TargetInfo &Target) {
198 Requirements.push_back(Requirement(Feature, RequiredState));
200 // If this feature is currently available, we're done.
201 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
204 markUnavailable(/*MissingRequirement*/true);
207 void Module::markUnavailable(bool MissingRequirement) {
208 auto needUpdate = [MissingRequirement](Module *M) {
209 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
212 if (!needUpdate(this))
215 SmallVector<Module *, 2> Stack;
216 Stack.push_back(this);
217 while (!Stack.empty()) {
218 Module *Current = Stack.back();
221 if (!needUpdate(Current))
224 Current->IsAvailable = false;
225 Current->IsMissingRequirement |= MissingRequirement;
226 for (submodule_iterator Sub = Current->submodule_begin(),
227 SubEnd = Current->submodule_end();
228 Sub != SubEnd; ++Sub) {
229 if (needUpdate(*Sub))
230 Stack.push_back(*Sub);
235 Module *Module::findSubmodule(StringRef Name) const {
236 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
237 if (Pos == SubModuleIndex.end())
240 return SubModules[Pos->getValue()];
243 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
244 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
251 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
252 // All non-explicit submodules are exported.
253 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
254 E = SubModules.end();
257 if (!Mod->IsExplicit)
258 Exported.push_back(Mod);
261 // Find re-exported modules by filtering the list of imported modules.
262 bool AnyWildcard = false;
263 bool UnrestrictedWildcard = false;
264 SmallVector<Module *, 4> WildcardRestrictions;
265 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
266 Module *Mod = Exports[I].getPointer();
267 if (!Exports[I].getInt()) {
268 // Export a named module directly; no wildcards involved.
269 Exported.push_back(Mod);
274 // Wildcard export: export all of the imported modules that match
275 // the given pattern.
277 if (UnrestrictedWildcard)
280 if (Module *Restriction = Exports[I].getPointer())
281 WildcardRestrictions.push_back(Restriction);
283 WildcardRestrictions.clear();
284 UnrestrictedWildcard = true;
288 // If there were any wildcards, push any imported modules that were
289 // re-exported by the wildcard restriction.
293 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
294 Module *Mod = Imports[I];
295 bool Acceptable = UnrestrictedWildcard;
297 // Check whether this module meets one of the restrictions.
298 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
299 Module *Restriction = WildcardRestrictions[R];
300 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
310 Exported.push_back(Mod);
314 void Module::buildVisibleModulesCache() const {
315 assert(VisibleModulesCache.empty() && "cache does not need building");
317 // This module is visible to itself.
318 VisibleModulesCache.insert(this);
320 // Every imported module is visible.
321 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
322 while (!Stack.empty()) {
323 Module *CurrModule = Stack.pop_back_val();
325 // Every module transitively exported by an imported module is visible.
326 if (VisibleModulesCache.insert(CurrModule).second)
327 CurrModule->getExportedModules(Stack);
331 void Module::print(raw_ostream &OS, unsigned Indent) const {
337 OS << "module " << Name;
339 if (IsSystem || IsExternC) {
340 OS.indent(Indent + 2);
349 if (!Requirements.empty()) {
350 OS.indent(Indent + 2);
352 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
355 if (!Requirements[I].second)
357 OS << Requirements[I].first;
362 if (Header H = getUmbrellaHeader()) {
363 OS.indent(Indent + 2);
364 OS << "umbrella header \"";
365 OS.write_escaped(H.NameAsWritten);
367 } else if (DirectoryName D = getUmbrellaDir()) {
368 OS.indent(Indent + 2);
370 OS.write_escaped(D.NameAsWritten);
374 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
375 OS.indent(Indent + 2);
376 OS << "config_macros ";
377 if (ConfigMacrosExhaustive)
378 OS << "[exhaustive]";
379 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
382 OS << ConfigMacros[I];
390 } Kinds[] = {{"", HK_Normal},
391 {"textual ", HK_Textual},
392 {"private ", HK_Private},
393 {"private textual ", HK_PrivateTextual},
394 {"exclude ", HK_Excluded}};
396 for (auto &K : Kinds) {
397 assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
398 for (auto &H : Headers[K.Kind]) {
399 OS.indent(Indent + 2);
400 OS << K.Prefix << "header \"";
401 OS.write_escaped(H.NameAsWritten);
402 OS << "\" { size " << H.Entry->getSize()
403 << " mtime " << H.Entry->getModificationTime() << " }\n";
406 for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
407 for (auto &U : *Unresolved) {
408 OS.indent(Indent + 2);
409 OS << Kinds[U.Kind].Prefix << "header \"";
410 OS.write_escaped(U.FileName);
412 if (U.Size || U.ModTime) {
415 OS << " size " << *U.Size;
417 OS << " mtime " << *U.ModTime;
424 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
426 // Print inferred subframework modules so that we don't need to re-infer
427 // them (requires expensive directory iteration + stat calls) when we build
428 // the module. Regular inferred submodules are OK, as we need to look at all
429 // those header files anyway.
430 if (!(*MI)->IsInferred || (*MI)->IsFramework)
431 (*MI)->print(OS, Indent + 2);
433 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
434 OS.indent(Indent + 2);
436 if (Module *Restriction = Exports[I].getPointer()) {
437 OS << Restriction->getFullModuleName();
438 if (Exports[I].getInt())
446 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
447 OS.indent(Indent + 2);
449 printModuleId(OS, UnresolvedExports[I].Id);
450 if (UnresolvedExports[I].Wildcard)
451 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
455 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
456 OS.indent(Indent + 2);
458 OS << DirectUses[I]->getFullModuleName();
462 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
463 OS.indent(Indent + 2);
465 printModuleId(OS, UnresolvedDirectUses[I]);
469 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
470 OS.indent(Indent + 2);
472 if (LinkLibraries[I].IsFramework)
475 OS.write_escaped(LinkLibraries[I].Library);
479 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
480 OS.indent(Indent + 2);
482 printModuleId(OS, UnresolvedConflicts[I].Id);
484 OS.write_escaped(UnresolvedConflicts[I].Message);
488 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
489 OS.indent(Indent + 2);
491 OS << Conflicts[I].Other->getFullModuleName();
493 OS.write_escaped(Conflicts[I].Message);
497 if (InferSubmodules) {
498 OS.indent(Indent + 2);
499 if (InferExplicitSubmodules)
501 OS << "module * {\n";
502 if (InferExportWildcard) {
503 OS.indent(Indent + 4);
506 OS.indent(Indent + 2);
514 LLVM_DUMP_METHOD void Module::dump() const {
518 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
519 VisibleCallback Vis, ConflictCallback Cb) {
520 assert(Loc.isValid() && "setVisible expects a valid import location");
528 Visiting *ExportedBy;
531 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
532 // Modules that aren't available cannot be made visible.
533 if (!V.M->isAvailable())
536 // Nothing to do for a module that's already visible.
537 unsigned ID = V.M->getVisibilityID();
538 if (ImportLocs.size() <= ID)
539 ImportLocs.resize(ID + 1);
540 else if (ImportLocs[ID].isValid())
543 ImportLocs[ID] = Loc;
546 // Make any exported modules visible.
547 SmallVector<Module *, 16> Exports;
548 V.M->getExportedModules(Exports);
549 for (Module *E : Exports)
550 VisitModule({E, &V});
552 for (auto &C : V.M->Conflicts) {
553 if (isVisible(C.Other)) {
554 llvm::SmallVector<Module*, 8> Path;
555 for (Visiting *I = &V; I; I = I->ExportedBy)
556 Path.push_back(I->M);
557 Cb(Path, C.Other, C.Message);
561 VisitModule({M, nullptr});