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/CharInfo.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
28 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
29 bool IsFramework, bool IsExplicit, unsigned VisibilityID)
30 : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
31 Umbrella(), ASTFile(nullptr), VisibilityID(VisibilityID),
32 IsMissingRequirement(false), HasIncompatibleModuleFile(false),
33 IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
34 IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
35 IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
36 InferExportWildcard(false), ConfigMacrosExhaustive(false),
37 NoUndeclaredIncludes(false), NameVisibility(Hidden) {
39 if (!Parent->isAvailable())
43 if (Parent->IsExternC)
45 if (Parent->NoUndeclaredIncludes)
46 NoUndeclaredIncludes = true;
47 IsMissingRequirement = Parent->IsMissingRequirement;
49 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
50 Parent->SubModules.push_back(this);
55 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
61 /// \brief Determine whether a translation unit built using the current
62 /// language options has the given feature.
63 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
64 const TargetInfo &Target) {
65 bool HasFeature = llvm::StringSwitch<bool>(Feature)
66 .Case("altivec", LangOpts.AltiVec)
67 .Case("blocks", LangOpts.Blocks)
68 .Case("coroutines", LangOpts.CoroutinesTS)
69 .Case("cplusplus", LangOpts.CPlusPlus)
70 .Case("cplusplus11", LangOpts.CPlusPlus11)
71 .Case("freestanding", LangOpts.Freestanding)
72 .Case("gnuinlineasm", LangOpts.GNUAsm)
73 .Case("objc", LangOpts.ObjC1)
74 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
75 .Case("opencl", LangOpts.OpenCL)
76 .Case("tls", Target.isTLSSupported())
77 .Case("zvector", LangOpts.ZVector)
78 .Default(Target.hasFeature(Feature));
80 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
81 LangOpts.ModuleFeatures.end(),
82 Feature) != LangOpts.ModuleFeatures.end();
86 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
88 UnresolvedHeaderDirective &MissingHeader) const {
92 for (const Module *Current = this; Current; Current = Current->Parent) {
93 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
94 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
95 Current->Requirements[I].second) {
96 Req = Current->Requirements[I];
100 if (!Current->MissingHeaders.empty()) {
101 MissingHeader = Current->MissingHeaders.front();
106 llvm_unreachable("could not find a reason why module is unavailable");
109 bool Module::isSubModuleOf(const Module *Other) const {
110 const Module *This = this;
121 const Module *Module::getTopLevelModule() const {
122 const Module *Result = this;
123 while (Result->Parent)
124 Result = Result->Parent;
129 static StringRef getModuleNameFromComponent(
130 const std::pair<std::string, SourceLocation> &IdComponent) {
131 return IdComponent.first;
133 static StringRef getModuleNameFromComponent(StringRef R) { return R; }
135 template<typename InputIter>
136 static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
137 bool AllowStringLiterals = true) {
138 for (InputIter It = Begin; It != End; ++It) {
142 StringRef Name = getModuleNameFromComponent(*It);
143 if (!AllowStringLiterals || isValidIdentifier(Name))
147 OS.write_escaped(Name);
153 template<typename Container>
154 static void printModuleId(raw_ostream &OS, const Container &C) {
155 return printModuleId(OS, C.begin(), C.end());
158 std::string Module::getFullModuleName(bool AllowStringLiterals) const {
159 SmallVector<StringRef, 2> Names;
161 // Build up the set of module names (from innermost to outermost).
162 for (const Module *M = this; M; M = M->Parent)
163 Names.push_back(M->Name);
167 llvm::raw_string_ostream Out(Result);
168 printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals);
174 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
175 for (const Module *M = this; M; M = M->Parent) {
176 if (nameParts.empty() || M->Name != nameParts.back())
178 nameParts = nameParts.drop_back();
180 return nameParts.empty();
183 Module::DirectoryName Module::getUmbrellaDir() const {
184 if (Header U = getUmbrellaHeader())
185 return {"", U.Entry->getDir()};
187 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
190 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
191 if (!TopHeaderNames.empty()) {
192 for (std::vector<std::string>::iterator
193 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
194 if (const FileEntry *FE = FileMgr.getFile(*I))
195 TopHeaders.insert(FE);
197 TopHeaderNames.clear();
200 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
203 bool Module::directlyUses(const Module *Requested) const {
204 auto *Top = getTopLevelModule();
206 // A top-level module implicitly uses itself.
207 if (Requested->isSubModuleOf(Top))
210 for (auto *Use : Top->DirectUses)
211 if (Requested->isSubModuleOf(Use))
214 // Anyone is allowed to use our builtin stddef.h and its accompanying module.
215 if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
221 void Module::addRequirement(StringRef Feature, bool RequiredState,
222 const LangOptions &LangOpts,
223 const TargetInfo &Target) {
224 Requirements.push_back(Requirement(Feature, RequiredState));
226 // If this feature is currently available, we're done.
227 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
230 markUnavailable(/*MissingRequirement*/true);
233 void Module::markUnavailable(bool MissingRequirement) {
234 auto needUpdate = [MissingRequirement](Module *M) {
235 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
238 if (!needUpdate(this))
241 SmallVector<Module *, 2> Stack;
242 Stack.push_back(this);
243 while (!Stack.empty()) {
244 Module *Current = Stack.back();
247 if (!needUpdate(Current))
250 Current->IsAvailable = false;
251 Current->IsMissingRequirement |= MissingRequirement;
252 for (submodule_iterator Sub = Current->submodule_begin(),
253 SubEnd = Current->submodule_end();
254 Sub != SubEnd; ++Sub) {
255 if (needUpdate(*Sub))
256 Stack.push_back(*Sub);
261 Module *Module::findSubmodule(StringRef Name) const {
262 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
263 if (Pos == SubModuleIndex.end())
266 return SubModules[Pos->getValue()];
269 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
270 // All non-explicit submodules are exported.
271 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
272 E = SubModules.end();
275 if (!Mod->IsExplicit)
276 Exported.push_back(Mod);
279 // Find re-exported modules by filtering the list of imported modules.
280 bool AnyWildcard = false;
281 bool UnrestrictedWildcard = false;
282 SmallVector<Module *, 4> WildcardRestrictions;
283 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
284 Module *Mod = Exports[I].getPointer();
285 if (!Exports[I].getInt()) {
286 // Export a named module directly; no wildcards involved.
287 Exported.push_back(Mod);
292 // Wildcard export: export all of the imported modules that match
293 // the given pattern.
295 if (UnrestrictedWildcard)
298 if (Module *Restriction = Exports[I].getPointer())
299 WildcardRestrictions.push_back(Restriction);
301 WildcardRestrictions.clear();
302 UnrestrictedWildcard = true;
306 // If there were any wildcards, push any imported modules that were
307 // re-exported by the wildcard restriction.
311 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
312 Module *Mod = Imports[I];
313 bool Acceptable = UnrestrictedWildcard;
315 // Check whether this module meets one of the restrictions.
316 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
317 Module *Restriction = WildcardRestrictions[R];
318 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
328 Exported.push_back(Mod);
332 void Module::buildVisibleModulesCache() const {
333 assert(VisibleModulesCache.empty() && "cache does not need building");
335 // This module is visible to itself.
336 VisibleModulesCache.insert(this);
338 // Every imported module is visible.
339 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
340 while (!Stack.empty()) {
341 Module *CurrModule = Stack.pop_back_val();
343 // Every module transitively exported by an imported module is visible.
344 if (VisibleModulesCache.insert(CurrModule).second)
345 CurrModule->getExportedModules(Stack);
349 void Module::print(raw_ostream &OS, unsigned Indent) const {
356 printModuleId(OS, &Name, &Name + 1);
358 if (IsSystem || IsExternC) {
359 OS.indent(Indent + 2);
368 if (!Requirements.empty()) {
369 OS.indent(Indent + 2);
371 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
374 if (!Requirements[I].second)
376 OS << Requirements[I].first;
381 if (Header H = getUmbrellaHeader()) {
382 OS.indent(Indent + 2);
383 OS << "umbrella header \"";
384 OS.write_escaped(H.NameAsWritten);
386 } else if (DirectoryName D = getUmbrellaDir()) {
387 OS.indent(Indent + 2);
389 OS.write_escaped(D.NameAsWritten);
393 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
394 OS.indent(Indent + 2);
395 OS << "config_macros ";
396 if (ConfigMacrosExhaustive)
397 OS << "[exhaustive]";
398 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
401 OS << ConfigMacros[I];
409 } Kinds[] = {{"", HK_Normal},
410 {"textual ", HK_Textual},
411 {"private ", HK_Private},
412 {"private textual ", HK_PrivateTextual},
413 {"exclude ", HK_Excluded}};
415 for (auto &K : Kinds) {
416 assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
417 for (auto &H : Headers[K.Kind]) {
418 OS.indent(Indent + 2);
419 OS << K.Prefix << "header \"";
420 OS.write_escaped(H.NameAsWritten);
421 OS << "\" { size " << H.Entry->getSize()
422 << " mtime " << H.Entry->getModificationTime() << " }\n";
425 for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
426 for (auto &U : *Unresolved) {
427 OS.indent(Indent + 2);
428 OS << Kinds[U.Kind].Prefix << "header \"";
429 OS.write_escaped(U.FileName);
431 if (U.Size || U.ModTime) {
434 OS << " size " << *U.Size;
436 OS << " mtime " << *U.ModTime;
443 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
445 // Print inferred subframework modules so that we don't need to re-infer
446 // them (requires expensive directory iteration + stat calls) when we build
447 // the module. Regular inferred submodules are OK, as we need to look at all
448 // those header files anyway.
449 if (!(*MI)->IsInferred || (*MI)->IsFramework)
450 (*MI)->print(OS, Indent + 2);
452 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
453 OS.indent(Indent + 2);
455 if (Module *Restriction = Exports[I].getPointer()) {
456 OS << Restriction->getFullModuleName(true);
457 if (Exports[I].getInt())
465 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
466 OS.indent(Indent + 2);
468 printModuleId(OS, UnresolvedExports[I].Id);
469 if (UnresolvedExports[I].Wildcard)
470 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
474 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
475 OS.indent(Indent + 2);
477 OS << DirectUses[I]->getFullModuleName(true);
481 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
482 OS.indent(Indent + 2);
484 printModuleId(OS, UnresolvedDirectUses[I]);
488 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
489 OS.indent(Indent + 2);
491 if (LinkLibraries[I].IsFramework)
494 OS.write_escaped(LinkLibraries[I].Library);
498 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
499 OS.indent(Indent + 2);
501 printModuleId(OS, UnresolvedConflicts[I].Id);
503 OS.write_escaped(UnresolvedConflicts[I].Message);
507 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
508 OS.indent(Indent + 2);
510 OS << Conflicts[I].Other->getFullModuleName(true);
512 OS.write_escaped(Conflicts[I].Message);
516 if (InferSubmodules) {
517 OS.indent(Indent + 2);
518 if (InferExplicitSubmodules)
520 OS << "module * {\n";
521 if (InferExportWildcard) {
522 OS.indent(Indent + 4);
525 OS.indent(Indent + 2);
533 LLVM_DUMP_METHOD void Module::dump() const {
537 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
538 VisibleCallback Vis, ConflictCallback Cb) {
539 assert(Loc.isValid() && "setVisible expects a valid import location");
547 Visiting *ExportedBy;
550 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
551 // Modules that aren't available cannot be made visible.
552 if (!V.M->isAvailable())
555 // Nothing to do for a module that's already visible.
556 unsigned ID = V.M->getVisibilityID();
557 if (ImportLocs.size() <= ID)
558 ImportLocs.resize(ID + 1);
559 else if (ImportLocs[ID].isValid())
562 ImportLocs[ID] = Loc;
565 // Make any exported modules visible.
566 SmallVector<Module *, 16> Exports;
567 V.M->getExportedModules(Exports);
568 for (Module *E : Exports)
569 VisitModule({E, &V});
571 for (auto &C : V.M->Conflicts) {
572 if (isVisible(C.Other)) {
573 llvm::SmallVector<Module*, 8> Path;
574 for (Visiting *I = &V; I; I = I->ExportedBy)
575 Path.push_back(I->M);
576 Cb(Path, C.Other, C.Message);
580 VisitModule({M, nullptr});