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("cplusplus", LangOpts.CPlusPlus)
68 .Case("cplusplus11", LangOpts.CPlusPlus11)
69 .Case("freestanding", LangOpts.Freestanding)
70 .Case("gnuinlineasm", LangOpts.GNUAsm)
71 .Case("objc", LangOpts.ObjC1)
72 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
73 .Case("opencl", LangOpts.OpenCL)
74 .Case("tls", Target.isTLSSupported())
75 .Case("zvector", LangOpts.ZVector)
76 .Default(Target.hasFeature(Feature));
78 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
79 LangOpts.ModuleFeatures.end(),
80 Feature) != LangOpts.ModuleFeatures.end();
84 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
86 UnresolvedHeaderDirective &MissingHeader) const {
90 for (const Module *Current = this; Current; Current = Current->Parent) {
91 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
92 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
93 Current->Requirements[I].second) {
94 Req = Current->Requirements[I];
98 if (!Current->MissingHeaders.empty()) {
99 MissingHeader = Current->MissingHeaders.front();
104 llvm_unreachable("could not find a reason why module is unavailable");
107 bool Module::isSubModuleOf(const Module *Other) const {
108 const Module *This = this;
119 const Module *Module::getTopLevelModule() const {
120 const Module *Result = this;
121 while (Result->Parent)
122 Result = Result->Parent;
127 std::string Module::getFullModuleName() const {
128 SmallVector<StringRef, 2> Names;
130 // Build up the set of module names (from innermost to outermost).
131 for (const Module *M = this; M; M = M->Parent)
132 Names.push_back(M->Name);
135 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
147 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
148 for (const Module *M = this; M; M = M->Parent) {
149 if (nameParts.empty() || M->Name != nameParts.back())
151 nameParts = nameParts.drop_back();
153 return nameParts.empty();
156 Module::DirectoryName Module::getUmbrellaDir() const {
157 if (Header U = getUmbrellaHeader())
158 return {"", U.Entry->getDir()};
160 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
163 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
164 if (!TopHeaderNames.empty()) {
165 for (std::vector<std::string>::iterator
166 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
167 if (const FileEntry *FE = FileMgr.getFile(*I))
168 TopHeaders.insert(FE);
170 TopHeaderNames.clear();
173 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
176 bool Module::directlyUses(const Module *Requested) const {
177 auto *Top = getTopLevelModule();
179 // A top-level module implicitly uses itself.
180 if (Requested->isSubModuleOf(Top))
183 for (auto *Use : Top->DirectUses)
184 if (Requested->isSubModuleOf(Use))
187 // Anyone is allowed to use our builtin stddef.h and its accompanying module.
188 if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
194 void Module::addRequirement(StringRef Feature, bool RequiredState,
195 const LangOptions &LangOpts,
196 const TargetInfo &Target) {
197 Requirements.push_back(Requirement(Feature, RequiredState));
199 // If this feature is currently available, we're done.
200 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
203 markUnavailable(/*MissingRequirement*/true);
206 void Module::markUnavailable(bool MissingRequirement) {
207 auto needUpdate = [MissingRequirement](Module *M) {
208 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
211 if (!needUpdate(this))
214 SmallVector<Module *, 2> Stack;
215 Stack.push_back(this);
216 while (!Stack.empty()) {
217 Module *Current = Stack.back();
220 if (!needUpdate(Current))
223 Current->IsAvailable = false;
224 Current->IsMissingRequirement |= MissingRequirement;
225 for (submodule_iterator Sub = Current->submodule_begin(),
226 SubEnd = Current->submodule_end();
227 Sub != SubEnd; ++Sub) {
228 if (needUpdate(*Sub))
229 Stack.push_back(*Sub);
234 Module *Module::findSubmodule(StringRef Name) const {
235 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
236 if (Pos == SubModuleIndex.end())
239 return SubModules[Pos->getValue()];
242 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
243 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
250 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
251 // All non-explicit submodules are exported.
252 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
253 E = SubModules.end();
256 if (!Mod->IsExplicit)
257 Exported.push_back(Mod);
260 // Find re-exported modules by filtering the list of imported modules.
261 bool AnyWildcard = false;
262 bool UnrestrictedWildcard = false;
263 SmallVector<Module *, 4> WildcardRestrictions;
264 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
265 Module *Mod = Exports[I].getPointer();
266 if (!Exports[I].getInt()) {
267 // Export a named module directly; no wildcards involved.
268 Exported.push_back(Mod);
273 // Wildcard export: export all of the imported modules that match
274 // the given pattern.
276 if (UnrestrictedWildcard)
279 if (Module *Restriction = Exports[I].getPointer())
280 WildcardRestrictions.push_back(Restriction);
282 WildcardRestrictions.clear();
283 UnrestrictedWildcard = true;
287 // If there were any wildcards, push any imported modules that were
288 // re-exported by the wildcard restriction.
292 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
293 Module *Mod = Imports[I];
294 bool Acceptable = UnrestrictedWildcard;
296 // Check whether this module meets one of the restrictions.
297 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
298 Module *Restriction = WildcardRestrictions[R];
299 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
309 Exported.push_back(Mod);
313 void Module::buildVisibleModulesCache() const {
314 assert(VisibleModulesCache.empty() && "cache does not need building");
316 // This module is visible to itself.
317 VisibleModulesCache.insert(this);
319 // Every imported module is visible.
320 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
321 while (!Stack.empty()) {
322 Module *CurrModule = Stack.pop_back_val();
324 // Every module transitively exported by an imported module is visible.
325 if (VisibleModulesCache.insert(CurrModule).second)
326 CurrModule->getExportedModules(Stack);
330 void Module::print(raw_ostream &OS, unsigned Indent) const {
336 OS << "module " << Name;
338 if (IsSystem || IsExternC) {
339 OS.indent(Indent + 2);
348 if (!Requirements.empty()) {
349 OS.indent(Indent + 2);
351 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
354 if (!Requirements[I].second)
356 OS << Requirements[I].first;
361 if (Header H = getUmbrellaHeader()) {
362 OS.indent(Indent + 2);
363 OS << "umbrella header \"";
364 OS.write_escaped(H.NameAsWritten);
366 } else if (DirectoryName D = getUmbrellaDir()) {
367 OS.indent(Indent + 2);
369 OS.write_escaped(D.NameAsWritten);
373 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
374 OS.indent(Indent + 2);
375 OS << "config_macros ";
376 if (ConfigMacrosExhaustive)
377 OS << "[exhaustive]";
378 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
381 OS << ConfigMacros[I];
389 } Kinds[] = {{"", HK_Normal},
390 {"textual ", HK_Textual},
391 {"private ", HK_Private},
392 {"private textual ", HK_PrivateTextual},
393 {"exclude ", HK_Excluded}};
395 for (auto &K : Kinds) {
396 for (auto &H : Headers[K.Kind]) {
397 OS.indent(Indent + 2);
398 OS << K.Prefix << "header \"";
399 OS.write_escaped(H.NameAsWritten);
404 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
406 // Print inferred subframework modules so that we don't need to re-infer
407 // them (requires expensive directory iteration + stat calls) when we build
408 // the module. Regular inferred submodules are OK, as we need to look at all
409 // those header files anyway.
410 if (!(*MI)->IsInferred || (*MI)->IsFramework)
411 (*MI)->print(OS, Indent + 2);
413 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
414 OS.indent(Indent + 2);
416 if (Module *Restriction = Exports[I].getPointer()) {
417 OS << Restriction->getFullModuleName();
418 if (Exports[I].getInt())
426 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
427 OS.indent(Indent + 2);
429 printModuleId(OS, UnresolvedExports[I].Id);
430 if (UnresolvedExports[I].Wildcard)
431 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
435 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
436 OS.indent(Indent + 2);
438 OS << DirectUses[I]->getFullModuleName();
442 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
443 OS.indent(Indent + 2);
445 printModuleId(OS, UnresolvedDirectUses[I]);
449 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
450 OS.indent(Indent + 2);
452 if (LinkLibraries[I].IsFramework)
455 OS.write_escaped(LinkLibraries[I].Library);
459 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
460 OS.indent(Indent + 2);
462 printModuleId(OS, UnresolvedConflicts[I].Id);
464 OS.write_escaped(UnresolvedConflicts[I].Message);
468 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
469 OS.indent(Indent + 2);
471 OS << Conflicts[I].Other->getFullModuleName();
473 OS.write_escaped(Conflicts[I].Message);
477 if (InferSubmodules) {
478 OS.indent(Indent + 2);
479 if (InferExplicitSubmodules)
481 OS << "module * {\n";
482 if (InferExportWildcard) {
483 OS.indent(Indent + 4);
486 OS.indent(Indent + 2);
494 LLVM_DUMP_METHOD void Module::dump() const {
498 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
499 VisibleCallback Vis, ConflictCallback Cb) {
500 assert(Loc.isValid() && "setVisible expects a valid import location");
508 Visiting *ExportedBy;
511 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
512 // Modules that aren't available cannot be made visible.
513 if (!V.M->isAvailable())
516 // Nothing to do for a module that's already visible.
517 unsigned ID = V.M->getVisibilityID();
518 if (ImportLocs.size() <= ID)
519 ImportLocs.resize(ID + 1);
520 else if (ImportLocs[ID].isValid())
523 ImportLocs[ID] = Loc;
526 // Make any exported modules visible.
527 SmallVector<Module *, 16> Exports;
528 V.M->getExportedModules(Exports);
529 for (Module *E : Exports)
530 VisitModule({E, &V});
532 for (auto &C : V.M->Conflicts) {
533 if (isVisible(C.Other)) {
534 llvm::SmallVector<Module*, 8> Path;
535 for (Visiting *I = &V; I; I = I->ExportedBy)
536 Path.push_back(I->M);
537 Cb(Path, C.Other, C.Message);
541 VisitModule({M, nullptr});