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/SourceLocation.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
36 using namespace clang;
38 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
39 bool IsFramework, bool IsExplicit, unsigned VisibilityID)
40 : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
41 VisibilityID(VisibilityID), IsMissingRequirement(false),
42 HasIncompatibleModuleFile(false), IsAvailable(true),
43 IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
44 IsSystem(false), IsExternC(false), IsInferred(false),
45 InferSubmodules(false), InferExplicitSubmodules(false),
46 InferExportWildcard(false), ConfigMacrosExhaustive(false),
47 NoUndeclaredIncludes(false), NameVisibility(Hidden) {
49 if (!Parent->isAvailable())
53 if (Parent->IsExternC)
55 if (Parent->NoUndeclaredIncludes)
56 NoUndeclaredIncludes = true;
57 IsMissingRequirement = Parent->IsMissingRequirement;
59 Parent->SubModuleIndex[Name] = Parent->SubModules.size();
60 Parent->SubModules.push_back(this);
65 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
71 /// \brief Determine whether a translation unit built using the current
72 /// language options has the given feature.
73 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
74 const TargetInfo &Target) {
75 bool HasFeature = llvm::StringSwitch<bool>(Feature)
76 .Case("altivec", LangOpts.AltiVec)
77 .Case("blocks", LangOpts.Blocks)
78 .Case("coroutines", LangOpts.CoroutinesTS)
79 .Case("cplusplus", LangOpts.CPlusPlus)
80 .Case("cplusplus11", LangOpts.CPlusPlus11)
81 .Case("freestanding", LangOpts.Freestanding)
82 .Case("gnuinlineasm", LangOpts.GNUAsm)
83 .Case("objc", LangOpts.ObjC1)
84 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
85 .Case("opencl", LangOpts.OpenCL)
86 .Case("tls", Target.isTLSSupported())
87 .Case("zvector", LangOpts.ZVector)
88 .Default(Target.hasFeature(Feature));
90 HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
91 LangOpts.ModuleFeatures.end(),
92 Feature) != LangOpts.ModuleFeatures.end();
96 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
98 UnresolvedHeaderDirective &MissingHeader) const {
102 for (const Module *Current = this; Current; Current = Current->Parent) {
103 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
104 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
105 Current->Requirements[I].second) {
106 Req = Current->Requirements[I];
110 if (!Current->MissingHeaders.empty()) {
111 MissingHeader = Current->MissingHeaders.front();
116 llvm_unreachable("could not find a reason why module is unavailable");
119 bool Module::isSubModuleOf(const Module *Other) const {
120 const Module *This = this;
131 const Module *Module::getTopLevelModule() const {
132 const Module *Result = this;
133 while (Result->Parent)
134 Result = Result->Parent;
139 static StringRef getModuleNameFromComponent(
140 const std::pair<std::string, SourceLocation> &IdComponent) {
141 return IdComponent.first;
144 static StringRef getModuleNameFromComponent(StringRef R) { return R; }
146 template<typename InputIter>
147 static void printModuleId(raw_ostream &OS, InputIter Begin, InputIter End,
148 bool AllowStringLiterals = true) {
149 for (InputIter It = Begin; It != End; ++It) {
153 StringRef Name = getModuleNameFromComponent(*It);
154 if (!AllowStringLiterals || isValidIdentifier(Name))
158 OS.write_escaped(Name);
164 template<typename Container>
165 static void printModuleId(raw_ostream &OS, const Container &C) {
166 return printModuleId(OS, C.begin(), C.end());
169 std::string Module::getFullModuleName(bool AllowStringLiterals) const {
170 SmallVector<StringRef, 2> Names;
172 // Build up the set of module names (from innermost to outermost).
173 for (const Module *M = this; M; M = M->Parent)
174 Names.push_back(M->Name);
178 llvm::raw_string_ostream Out(Result);
179 printModuleId(Out, Names.rbegin(), Names.rend(), AllowStringLiterals);
185 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
186 for (const Module *M = this; M; M = M->Parent) {
187 if (nameParts.empty() || M->Name != nameParts.back())
189 nameParts = nameParts.drop_back();
191 return nameParts.empty();
194 Module::DirectoryName Module::getUmbrellaDir() const {
195 if (Header U = getUmbrellaHeader())
196 return {"", U.Entry->getDir()};
198 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
201 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
202 if (!TopHeaderNames.empty()) {
203 for (std::vector<std::string>::iterator
204 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
205 if (const FileEntry *FE = FileMgr.getFile(*I))
206 TopHeaders.insert(FE);
208 TopHeaderNames.clear();
211 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
214 bool Module::directlyUses(const Module *Requested) const {
215 auto *Top = getTopLevelModule();
217 // A top-level module implicitly uses itself.
218 if (Requested->isSubModuleOf(Top))
221 for (auto *Use : Top->DirectUses)
222 if (Requested->isSubModuleOf(Use))
225 // Anyone is allowed to use our builtin stddef.h and its accompanying module.
226 if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
232 void Module::addRequirement(StringRef Feature, bool RequiredState,
233 const LangOptions &LangOpts,
234 const TargetInfo &Target) {
235 Requirements.push_back(Requirement(Feature, RequiredState));
237 // If this feature is currently available, we're done.
238 if (hasFeature(Feature, LangOpts, Target) == RequiredState)
241 markUnavailable(/*MissingRequirement*/true);
244 void Module::markUnavailable(bool MissingRequirement) {
245 auto needUpdate = [MissingRequirement](Module *M) {
246 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
249 if (!needUpdate(this))
252 SmallVector<Module *, 2> Stack;
253 Stack.push_back(this);
254 while (!Stack.empty()) {
255 Module *Current = Stack.back();
258 if (!needUpdate(Current))
261 Current->IsAvailable = false;
262 Current->IsMissingRequirement |= MissingRequirement;
263 for (submodule_iterator Sub = Current->submodule_begin(),
264 SubEnd = Current->submodule_end();
265 Sub != SubEnd; ++Sub) {
266 if (needUpdate(*Sub))
267 Stack.push_back(*Sub);
272 Module *Module::findSubmodule(StringRef Name) const {
273 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
274 if (Pos == SubModuleIndex.end())
277 return SubModules[Pos->getValue()];
280 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
281 // All non-explicit submodules are exported.
282 for (std::vector<Module *>::const_iterator I = SubModules.begin(),
283 E = SubModules.end();
286 if (!Mod->IsExplicit)
287 Exported.push_back(Mod);
290 // Find re-exported modules by filtering the list of imported modules.
291 bool AnyWildcard = false;
292 bool UnrestrictedWildcard = false;
293 SmallVector<Module *, 4> WildcardRestrictions;
294 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
295 Module *Mod = Exports[I].getPointer();
296 if (!Exports[I].getInt()) {
297 // Export a named module directly; no wildcards involved.
298 Exported.push_back(Mod);
303 // Wildcard export: export all of the imported modules that match
304 // the given pattern.
306 if (UnrestrictedWildcard)
309 if (Module *Restriction = Exports[I].getPointer())
310 WildcardRestrictions.push_back(Restriction);
312 WildcardRestrictions.clear();
313 UnrestrictedWildcard = true;
317 // If there were any wildcards, push any imported modules that were
318 // re-exported by the wildcard restriction.
322 for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
323 Module *Mod = Imports[I];
324 bool Acceptable = UnrestrictedWildcard;
326 // Check whether this module meets one of the restrictions.
327 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
328 Module *Restriction = WildcardRestrictions[R];
329 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
339 Exported.push_back(Mod);
343 void Module::buildVisibleModulesCache() const {
344 assert(VisibleModulesCache.empty() && "cache does not need building");
346 // This module is visible to itself.
347 VisibleModulesCache.insert(this);
349 // Every imported module is visible.
350 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
351 while (!Stack.empty()) {
352 Module *CurrModule = Stack.pop_back_val();
354 // Every module transitively exported by an imported module is visible.
355 if (VisibleModulesCache.insert(CurrModule).second)
356 CurrModule->getExportedModules(Stack);
360 void Module::print(raw_ostream &OS, unsigned Indent) const {
367 printModuleId(OS, &Name, &Name + 1);
369 if (IsSystem || IsExternC) {
370 OS.indent(Indent + 2);
379 if (!Requirements.empty()) {
380 OS.indent(Indent + 2);
382 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
385 if (!Requirements[I].second)
387 OS << Requirements[I].first;
392 if (Header H = getUmbrellaHeader()) {
393 OS.indent(Indent + 2);
394 OS << "umbrella header \"";
395 OS.write_escaped(H.NameAsWritten);
397 } else if (DirectoryName D = getUmbrellaDir()) {
398 OS.indent(Indent + 2);
400 OS.write_escaped(D.NameAsWritten);
404 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
405 OS.indent(Indent + 2);
406 OS << "config_macros ";
407 if (ConfigMacrosExhaustive)
408 OS << "[exhaustive]";
409 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
412 OS << ConfigMacros[I];
420 } Kinds[] = {{"", HK_Normal},
421 {"textual ", HK_Textual},
422 {"private ", HK_Private},
423 {"private textual ", HK_PrivateTextual},
424 {"exclude ", HK_Excluded}};
426 for (auto &K : Kinds) {
427 assert(&K == &Kinds[K.Kind] && "kinds in wrong order");
428 for (auto &H : Headers[K.Kind]) {
429 OS.indent(Indent + 2);
430 OS << K.Prefix << "header \"";
431 OS.write_escaped(H.NameAsWritten);
432 OS << "\" { size " << H.Entry->getSize()
433 << " mtime " << H.Entry->getModificationTime() << " }\n";
436 for (auto *Unresolved : {&UnresolvedHeaders, &MissingHeaders}) {
437 for (auto &U : *Unresolved) {
438 OS.indent(Indent + 2);
439 OS << Kinds[U.Kind].Prefix << "header \"";
440 OS.write_escaped(U.FileName);
442 if (U.Size || U.ModTime) {
445 OS << " size " << *U.Size;
447 OS << " mtime " << *U.ModTime;
454 if (!ExportAsModule.empty()) {
455 OS.indent(Indent + 2);
456 OS << "export_as" << ExportAsModule << "\n";
459 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
461 // Print inferred subframework modules so that we don't need to re-infer
462 // them (requires expensive directory iteration + stat calls) when we build
463 // the module. Regular inferred submodules are OK, as we need to look at all
464 // those header files anyway.
465 if (!(*MI)->IsInferred || (*MI)->IsFramework)
466 (*MI)->print(OS, Indent + 2);
468 for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
469 OS.indent(Indent + 2);
471 if (Module *Restriction = Exports[I].getPointer()) {
472 OS << Restriction->getFullModuleName(true);
473 if (Exports[I].getInt())
481 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
482 OS.indent(Indent + 2);
484 printModuleId(OS, UnresolvedExports[I].Id);
485 if (UnresolvedExports[I].Wildcard)
486 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
490 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
491 OS.indent(Indent + 2);
493 OS << DirectUses[I]->getFullModuleName(true);
497 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
498 OS.indent(Indent + 2);
500 printModuleId(OS, UnresolvedDirectUses[I]);
504 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
505 OS.indent(Indent + 2);
507 if (LinkLibraries[I].IsFramework)
510 OS.write_escaped(LinkLibraries[I].Library);
514 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
515 OS.indent(Indent + 2);
517 printModuleId(OS, UnresolvedConflicts[I].Id);
519 OS.write_escaped(UnresolvedConflicts[I].Message);
523 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
524 OS.indent(Indent + 2);
526 OS << Conflicts[I].Other->getFullModuleName(true);
528 OS.write_escaped(Conflicts[I].Message);
532 if (InferSubmodules) {
533 OS.indent(Indent + 2);
534 if (InferExplicitSubmodules)
536 OS << "module * {\n";
537 if (InferExportWildcard) {
538 OS.indent(Indent + 4);
541 OS.indent(Indent + 2);
549 LLVM_DUMP_METHOD void Module::dump() const {
553 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
554 VisibleCallback Vis, ConflictCallback Cb) {
555 assert(Loc.isValid() && "setVisible expects a valid import location");
563 Visiting *ExportedBy;
566 std::function<void(Visiting)> VisitModule = [&](Visiting V) {
567 // Modules that aren't available cannot be made visible.
568 if (!V.M->isAvailable())
571 // Nothing to do for a module that's already visible.
572 unsigned ID = V.M->getVisibilityID();
573 if (ImportLocs.size() <= ID)
574 ImportLocs.resize(ID + 1);
575 else if (ImportLocs[ID].isValid())
578 ImportLocs[ID] = Loc;
581 // Make any exported modules visible.
582 SmallVector<Module *, 16> Exports;
583 V.M->getExportedModules(Exports);
584 for (Module *E : Exports)
585 VisitModule({E, &V});
587 for (auto &C : V.M->Conflicts) {
588 if (isVisible(C.Other)) {
589 llvm::SmallVector<Module*, 8> Path;
590 for (Visiting *I = &V; I; I = I->ExportedBy)
591 Path.push_back(I->M);
592 Cb(Path, C.Other, C.Message);
596 VisitModule({M, nullptr});