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(), Signature(0), ASTFile(nullptr), VisibilityID(VisibilityID),
31 IsMissingRequirement(false), IsAvailable(true), IsFromModuleFile(false),
32 IsFramework(IsFramework), IsExplicit(IsExplicit), IsSystem(false),
33 IsExternC(false), IsInferred(false), InferSubmodules(false),
34 InferExplicitSubmodules(false), InferExportWildcard(false),
35 ConfigMacrosExhaustive(false), NameVisibility(Hidden) {
37 if (!Parent->isAvailable())
41 if (Parent->IsExternC)
43 IsMissingRequirement = Parent->IsMissingRequirement;
45 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
46 Parent->SubModules.push_back(this);
51 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
57 /// \brief Determine whether a translation unit built using the current
58 /// language options has the given feature.
59 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
60 const TargetInfo &Target) {
61 bool HasFeature = llvm::StringSwitch<bool>(Feature)
62 .Case("altivec", LangOpts.AltiVec)
63 .Case("blocks", LangOpts.Blocks)
64 .Case("cplusplus", LangOpts.CPlusPlus)
65 .Case("cplusplus11", LangOpts.CPlusPlus11)
66 .Case("objc", LangOpts.ObjC1)
67 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
68 .Case("opencl", LangOpts.OpenCL)
69 .Case("tls", Target.isTLSSupported())
70 .Default(Target.hasFeature(Feature));
72 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
73 LangOpts.ModuleFeatures.end(),
74 Feature) != LangOpts.ModuleFeatures.end();
78 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
80 UnresolvedHeaderDirective &MissingHeader) const {
84 for (const Module *Current = this; Current; Current = Current->Parent) {
85 if (!Current->MissingHeaders.empty()) {
86 MissingHeader = Current->MissingHeaders.front();
89 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
90 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
91 Current->Requirements[I].second) {
92 Req = Current->Requirements[I];
98 llvm_unreachable("could not find a reason why module is unavailable");
101 bool Module::isSubModuleOf(const Module *Other) const {
102 const Module *This = this;
113 const Module *Module::getTopLevelModule() const {
114 const Module *Result = this;
115 while (Result->Parent)
116 Result = Result->Parent;
121 std::string Module::getFullModuleName() const {
122 SmallVector<StringRef, 2> Names;
124 // Build up the set of module names (from innermost to outermost).
125 for (const Module *M = this; M; M = M->Parent)
126 Names.push_back(M->Name);
129 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
141 Module::DirectoryName Module::getUmbrellaDir() const {
142 if (Header U = getUmbrellaHeader())
143 return {"", U.Entry->getDir()};
145 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
148 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
149 if (!TopHeaderNames.empty()) {
150 for (std::vector<std::string>::iterator
151 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
152 if (const FileEntry *FE = FileMgr.getFile(*I))
153 TopHeaders.insert(FE);
155 TopHeaderNames.clear();
158 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
161 bool Module::directlyUses(const Module *Requested) const {
162 auto *Top = getTopLevelModule();
164 // A top-level module implicitly uses itself.
165 if (Requested->isSubModuleOf(Top))
168 for (auto *Use : Top->DirectUses)
169 if (Requested->isSubModuleOf(Use))
174 void Module::addRequirement(StringRef Feature, bool RequiredState,
175 const LangOptions &LangOpts,
176 const TargetInfo &Target) {
177 Requirements.push_back(Requirement(Feature, RequiredState));
179 // If this feature is currently available, we're done.
180 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
183 markUnavailable(/*MissingRequirement*/true);
186 void Module::markUnavailable(bool MissingRequirement) {
190 SmallVector<Module *, 2> Stack;
191 Stack.push_back(this);
192 while (!Stack.empty()) {
193 Module *Current = Stack.back();
196 if (!Current->IsAvailable)
199 Current->IsAvailable = false;
200 Current->IsMissingRequirement |= MissingRequirement;
201 for (submodule_iterator Sub = Current->submodule_begin(),
202 SubEnd = Current->submodule_end();
203 Sub != SubEnd; ++Sub) {
204 if ((*Sub)->IsAvailable)
205 Stack.push_back(*Sub);
210 Module *Module::findSubmodule(StringRef Name) const {
211 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
212 if (Pos == SubModuleIndex.end())
215 return SubModules[Pos->getValue()];
218 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
219 for (unsigned I = 0, N = Id.size(); I != N; ++I) {
226 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
227 // All non-explicit submodules are exported.
228 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
229 E = SubModules.end();
232 if (!Mod->IsExplicit)
233 Exported.push_back(Mod);
236 // Find re-exported modules by filtering the list of imported modules.
237 bool AnyWildcard = false;
238 bool UnrestrictedWildcard = false;
239 SmallVector<Module *, 4> WildcardRestrictions;
240 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
241 Module *Mod = Exports[I].getPointer();
242 if (!Exports[I].getInt()) {
243 // Export a named module directly; no wildcards involved.
244 Exported.push_back(Mod);
249 // Wildcard export: export all of the imported modules that match
250 // the given pattern.
252 if (UnrestrictedWildcard)
255 if (Module *Restriction = Exports[I].getPointer())
256 WildcardRestrictions.push_back(Restriction);
258 WildcardRestrictions.clear();
259 UnrestrictedWildcard = true;
263 // If there were any wildcards, push any imported modules that were
264 // re-exported by the wildcard restriction.
268 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
269 Module *Mod = Imports[I];
270 bool Acceptable = UnrestrictedWildcard;
272 // Check whether this module meets one of the restrictions.
273 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
274 Module *Restriction = WildcardRestrictions[R];
275 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
285 Exported.push_back(Mod);
289 void Module::buildVisibleModulesCache() const {
290 assert(VisibleModulesCache.empty() && "cache does not need building");
292 // This module is visible to itself.
293 VisibleModulesCache.insert(this);
295 // Every imported module is visible.
296 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
297 while (!Stack.empty()) {
298 Module *CurrModule = Stack.pop_back_val();
300 // Every module transitively exported by an imported module is visible.
301 if (VisibleModulesCache.insert(CurrModule).second)
302 CurrModule->getExportedModules(Stack);
306 void Module::print(raw_ostream &OS, unsigned Indent) const {
312 OS << "module " << Name;
314 if (IsSystem || IsExternC) {
315 OS.indent(Indent + 2);
324 if (!Requirements.empty()) {
325 OS.indent(Indent + 2);
327 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
330 if (!Requirements[I].second)
332 OS << Requirements[I].first;
337 if (Header H = getUmbrellaHeader()) {
338 OS.indent(Indent + 2);
339 OS << "umbrella header \"";
340 OS.write_escaped(H.NameAsWritten);
342 } else if (DirectoryName D = getUmbrellaDir()) {
343 OS.indent(Indent + 2);
345 OS.write_escaped(D.NameAsWritten);
349 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
350 OS.indent(Indent + 2);
351 OS << "config_macros ";
352 if (ConfigMacrosExhaustive)
353 OS << "[exhaustive]";
354 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
357 OS << ConfigMacros[I];
365 } Kinds[] = {{"", HK_Normal},
366 {"textual ", HK_Textual},
367 {"private ", HK_Private},
368 {"private textual ", HK_PrivateTextual},
369 {"exclude ", HK_Excluded}};
371 for (auto &K : Kinds) {
372 for (auto &H : Headers[K.Kind]) {
373 OS.indent(Indent + 2);
374 OS << K.Prefix << "header \"";
375 OS.write_escaped(H.NameAsWritten);
380 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
382 // Print inferred subframework modules so that we don't need to re-infer
383 // them (requires expensive directory iteration + stat calls) when we build
384 // the module. Regular inferred submodules are OK, as we need to look at all
385 // those header files anyway.
386 if (!(*MI)->IsInferred || (*MI)->IsFramework)
387 (*MI)->print(OS, Indent + 2);
389 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
390 OS.indent(Indent + 2);
392 if (Module *Restriction = Exports[I].getPointer()) {
393 OS << Restriction->getFullModuleName();
394 if (Exports[I].getInt())
402 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
403 OS.indent(Indent + 2);
405 printModuleId(OS, UnresolvedExports[I].Id);
406 if (UnresolvedExports[I].Wildcard) {
407 if (UnresolvedExports[I].Id.empty())
415 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
416 OS.indent(Indent + 2);
418 OS << DirectUses[I]->getFullModuleName();
422 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
423 OS.indent(Indent + 2);
425 printModuleId(OS, UnresolvedDirectUses[I]);
429 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
430 OS.indent(Indent + 2);
432 if (LinkLibraries[I].IsFramework)
435 OS.write_escaped(LinkLibraries[I].Library);
439 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
440 OS.indent(Indent + 2);
442 printModuleId(OS, UnresolvedConflicts[I].Id);
444 OS.write_escaped(UnresolvedConflicts[I].Message);
448 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
449 OS.indent(Indent + 2);
451 OS << Conflicts[I].Other->getFullModuleName();
453 OS.write_escaped(Conflicts[I].Message);
457 if (InferSubmodules) {
458 OS.indent(Indent + 2);
459 if (InferExplicitSubmodules)
461 OS << "module * {\n";
462 if (InferExportWildcard) {
463 OS.indent(Indent + 4);
466 OS.indent(Indent + 2);
474 void Module::dump() const {
478 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
479 VisibleCallback Vis, ConflictCallback Cb) {
487 Visiting *ExportedBy;
490 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
491 // Modules that aren't available cannot be made visible.
492 if (!V.M->isAvailable())
495 // Nothing to do for a module that's already visible.
496 unsigned ID = V.M->getVisibilityID();
497 if (ImportLocs.size() <= ID)
498 ImportLocs.resize(ID + 1);
499 else if (ImportLocs[ID].isValid())
502 ImportLocs[ID] = Loc;
505 // Make any exported modules visible.
506 SmallVector<Module *, 16> Exports;
507 V.M->getExportedModules(Exports);
508 for (Module *E : Exports)
509 VisitModule({E, &V});
511 for (auto &C : V.M->Conflicts) {
512 if (isVisible(C.Other)) {
513 llvm::SmallVector<Module*, 8> Path;
514 for (Visiting *I = &V; I; I = I->ExportedBy)
515 Path.push_back(I->M);
516 Cb(Path, C.Other, C.Message);
520 VisitModule({M, nullptr});