1 //===--- Module.cpp - Describe a module -----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the Module class, which describes a module in the source
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
24 
25 using namespace clang;
26 
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), 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       NameVisibility(Hidden) {
37   if (Parent) {
38     if (!Parent->isAvailable())
39       IsAvailable = false;
40     if (Parent->IsSystem)
41       IsSystem = true;
42     if (Parent->IsExternC)
43       IsExternC = true;
44     IsMissingRequirement = Parent->IsMissingRequirement;
45 
46     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
47     Parent->SubModules.push_back(this);
48   }
49 }
50 
51 Module::~Module() {
52   for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
53        I != IEnd; ++I) {
54     delete *I;
55   }
56 }
57 
58 /// \brief Determine whether a translation unit built using the current
59 /// language options has the given feature.
60 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
61                        const TargetInfo &Target) {
62   bool HasFeature = llvm::StringSwitch<bool>(Feature)
63                         .Case("altivec", LangOpts.AltiVec)
64                         .Case("blocks", LangOpts.Blocks)
65                         .Case("cplusplus", LangOpts.CPlusPlus)
66                         .Case("cplusplus11", LangOpts.CPlusPlus11)
67                         .Case("gnuinlineasm", LangOpts.GNUAsm)
68                         .Case("objc", LangOpts.ObjC1)
69                         .Case("objc_arc", LangOpts.ObjCAutoRefCount)
70                         .Case("opencl", LangOpts.OpenCL)
71                         .Case("tls", Target.isTLSSupported())
72                         .Case("zvector", LangOpts.ZVector)
73                         .Default(Target.hasFeature(Feature));
74   if (!HasFeature)
75     HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
76                            LangOpts.ModuleFeatures.end(),
77                            Feature) != LangOpts.ModuleFeatures.end();
78   return HasFeature;
79 }
80 
81 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
82                          Requirement &Req,
83                          UnresolvedHeaderDirective &MissingHeader) const {
84   if (IsAvailable)
85     return true;
86 
87   for (const Module *Current = this; Current; Current = Current->Parent) {
88     for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
89       if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
90               Current->Requirements[I].second) {
91         Req = Current->Requirements[I];
92         return false;
93       }
94     }
95     if (!Current->MissingHeaders.empty()) {
96       MissingHeader = Current->MissingHeaders.front();
97       return false;
98     }
99   }
100 
101   llvm_unreachable("could not find a reason why module is unavailable");
102 }
103 
104 bool Module::isSubModuleOf(const Module *Other) const {
105   const Module *This = this;
106   do {
107     if (This == Other)
108       return true;
109 
110     This = This->Parent;
111   } while (This);
112 
113   return false;
114 }
115 
116 const Module *Module::getTopLevelModule() const {
117   const Module *Result = this;
118   while (Result->Parent)
119     Result = Result->Parent;
120 
121   return Result;
122 }
123 
124 std::string Module::getFullModuleName() const {
125   SmallVector<StringRef, 2> Names;
126 
127   // Build up the set of module names (from innermost to outermost).
128   for (const Module *M = this; M; M = M->Parent)
129     Names.push_back(M->Name);
130 
131   std::string Result;
132   for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
133                                                  IEnd = Names.rend();
134        I != IEnd; ++I) {
135     if (!Result.empty())
136       Result += '.';
137 
138     Result += *I;
139   }
140 
141   return Result;
142 }
143 
144 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
145   for (const Module *M = this; M; M = M->Parent) {
146     if (nameParts.empty() || M->Name != nameParts.back())
147       return false;
148     nameParts = nameParts.drop_back();
149   }
150   return nameParts.empty();
151 }
152 
153 Module::DirectoryName Module::getUmbrellaDir() const {
154   if (Header U = getUmbrellaHeader())
155     return {"", U.Entry->getDir()};
156 
157   return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
158 }
159 
160 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
161   if (!TopHeaderNames.empty()) {
162     for (std::vector<std::string>::iterator
163            I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
164       if (const FileEntry *FE = FileMgr.getFile(*I))
165         TopHeaders.insert(FE);
166     }
167     TopHeaderNames.clear();
168   }
169 
170   return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
171 }
172 
173 bool Module::directlyUses(const Module *Requested) const {
174   auto *Top = getTopLevelModule();
175 
176   // A top-level module implicitly uses itself.
177   if (Requested->isSubModuleOf(Top))
178     return true;
179 
180   for (auto *Use : Top->DirectUses)
181     if (Requested->isSubModuleOf(Use))
182       return true;
183   return false;
184 }
185 
186 void Module::addRequirement(StringRef Feature, bool RequiredState,
187                             const LangOptions &LangOpts,
188                             const TargetInfo &Target) {
189   Requirements.push_back(Requirement(Feature, RequiredState));
190 
191   // If this feature is currently available, we're done.
192   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
193     return;
194 
195   markUnavailable(/*MissingRequirement*/true);
196 }
197 
198 void Module::markUnavailable(bool MissingRequirement) {
199   auto needUpdate = [MissingRequirement](Module *M) {
200     return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
201   };
202 
203   if (!needUpdate(this))
204     return;
205 
206   SmallVector<Module *, 2> Stack;
207   Stack.push_back(this);
208   while (!Stack.empty()) {
209     Module *Current = Stack.back();
210     Stack.pop_back();
211 
212     if (!needUpdate(Current))
213       continue;
214 
215     Current->IsAvailable = false;
216     Current->IsMissingRequirement |= MissingRequirement;
217     for (submodule_iterator Sub = Current->submodule_begin(),
218                          SubEnd = Current->submodule_end();
219          Sub != SubEnd; ++Sub) {
220       if (needUpdate(*Sub))
221         Stack.push_back(*Sub);
222     }
223   }
224 }
225 
226 Module *Module::findSubmodule(StringRef Name) const {
227   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
228   if (Pos == SubModuleIndex.end())
229     return nullptr;
230 
231   return SubModules[Pos->getValue()];
232 }
233 
234 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
235   for (unsigned I = 0, N = Id.size(); I != N; ++I) {
236     if (I)
237       OS << ".";
238     OS << Id[I].first;
239   }
240 }
241 
242 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
243   // All non-explicit submodules are exported.
244   for (std::vector<Module *>::const_iterator I = SubModules.begin(),
245                                              E = SubModules.end();
246        I != E; ++I) {
247     Module *Mod = *I;
248     if (!Mod->IsExplicit)
249       Exported.push_back(Mod);
250   }
251 
252   // Find re-exported modules by filtering the list of imported modules.
253   bool AnyWildcard = false;
254   bool UnrestrictedWildcard = false;
255   SmallVector<Module *, 4> WildcardRestrictions;
256   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
257     Module *Mod = Exports[I].getPointer();
258     if (!Exports[I].getInt()) {
259       // Export a named module directly; no wildcards involved.
260       Exported.push_back(Mod);
261 
262       continue;
263     }
264 
265     // Wildcard export: export all of the imported modules that match
266     // the given pattern.
267     AnyWildcard = true;
268     if (UnrestrictedWildcard)
269       continue;
270 
271     if (Module *Restriction = Exports[I].getPointer())
272       WildcardRestrictions.push_back(Restriction);
273     else {
274       WildcardRestrictions.clear();
275       UnrestrictedWildcard = true;
276     }
277   }
278 
279   // If there were any wildcards, push any imported modules that were
280   // re-exported by the wildcard restriction.
281   if (!AnyWildcard)
282     return;
283 
284   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
285     Module *Mod = Imports[I];
286     bool Acceptable = UnrestrictedWildcard;
287     if (!Acceptable) {
288       // Check whether this module meets one of the restrictions.
289       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
290         Module *Restriction = WildcardRestrictions[R];
291         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
292           Acceptable = true;
293           break;
294         }
295       }
296     }
297 
298     if (!Acceptable)
299       continue;
300 
301     Exported.push_back(Mod);
302   }
303 }
304 
305 void Module::buildVisibleModulesCache() const {
306   assert(VisibleModulesCache.empty() && "cache does not need building");
307 
308   // This module is visible to itself.
309   VisibleModulesCache.insert(this);
310 
311   // Every imported module is visible.
312   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
313   while (!Stack.empty()) {
314     Module *CurrModule = Stack.pop_back_val();
315 
316     // Every module transitively exported by an imported module is visible.
317     if (VisibleModulesCache.insert(CurrModule).second)
318       CurrModule->getExportedModules(Stack);
319   }
320 }
321 
322 void Module::print(raw_ostream &OS, unsigned Indent) const {
323   OS.indent(Indent);
324   if (IsFramework)
325     OS << "framework ";
326   if (IsExplicit)
327     OS << "explicit ";
328   OS << "module " << Name;
329 
330   if (IsSystem || IsExternC) {
331     OS.indent(Indent + 2);
332     if (IsSystem)
333       OS << " [system]";
334     if (IsExternC)
335       OS << " [extern_c]";
336   }
337 
338   OS << " {\n";
339 
340   if (!Requirements.empty()) {
341     OS.indent(Indent + 2);
342     OS << "requires ";
343     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
344       if (I)
345         OS << ", ";
346       if (!Requirements[I].second)
347         OS << "!";
348       OS << Requirements[I].first;
349     }
350     OS << "\n";
351   }
352 
353   if (Header H = getUmbrellaHeader()) {
354     OS.indent(Indent + 2);
355     OS << "umbrella header \"";
356     OS.write_escaped(H.NameAsWritten);
357     OS << "\"\n";
358   } else if (DirectoryName D = getUmbrellaDir()) {
359     OS.indent(Indent + 2);
360     OS << "umbrella \"";
361     OS.write_escaped(D.NameAsWritten);
362     OS << "\"\n";
363   }
364 
365   if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
366     OS.indent(Indent + 2);
367     OS << "config_macros ";
368     if (ConfigMacrosExhaustive)
369       OS << "[exhaustive]";
370     for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
371       if (I)
372         OS << ", ";
373       OS << ConfigMacros[I];
374     }
375     OS << "\n";
376   }
377 
378   struct {
379     StringRef Prefix;
380     HeaderKind Kind;
381   } Kinds[] = {{"", HK_Normal},
382                {"textual ", HK_Textual},
383                {"private ", HK_Private},
384                {"private textual ", HK_PrivateTextual},
385                {"exclude ", HK_Excluded}};
386 
387   for (auto &K : Kinds) {
388     for (auto &H : Headers[K.Kind]) {
389       OS.indent(Indent + 2);
390       OS << K.Prefix << "header \"";
391       OS.write_escaped(H.NameAsWritten);
392       OS << "\"\n";
393     }
394   }
395 
396   for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
397        MI != MIEnd; ++MI)
398     // Print inferred subframework modules so that we don't need to re-infer
399     // them (requires expensive directory iteration + stat calls) when we build
400     // the module. Regular inferred submodules are OK, as we need to look at all
401     // those header files anyway.
402     if (!(*MI)->IsInferred || (*MI)->IsFramework)
403       (*MI)->print(OS, Indent + 2);
404 
405   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
406     OS.indent(Indent + 2);
407     OS << "export ";
408     if (Module *Restriction = Exports[I].getPointer()) {
409       OS << Restriction->getFullModuleName();
410       if (Exports[I].getInt())
411         OS << ".*";
412     } else {
413       OS << "*";
414     }
415     OS << "\n";
416   }
417 
418   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
419     OS.indent(Indent + 2);
420     OS << "export ";
421     printModuleId(OS, UnresolvedExports[I].Id);
422     if (UnresolvedExports[I].Wildcard)
423       OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
424     OS << "\n";
425   }
426 
427   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
428     OS.indent(Indent + 2);
429     OS << "use ";
430     OS << DirectUses[I]->getFullModuleName();
431     OS << "\n";
432   }
433 
434   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
435     OS.indent(Indent + 2);
436     OS << "use ";
437     printModuleId(OS, UnresolvedDirectUses[I]);
438     OS << "\n";
439   }
440 
441   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
442     OS.indent(Indent + 2);
443     OS << "link ";
444     if (LinkLibraries[I].IsFramework)
445       OS << "framework ";
446     OS << "\"";
447     OS.write_escaped(LinkLibraries[I].Library);
448     OS << "\"";
449   }
450 
451   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
452     OS.indent(Indent + 2);
453     OS << "conflict ";
454     printModuleId(OS, UnresolvedConflicts[I].Id);
455     OS << ", \"";
456     OS.write_escaped(UnresolvedConflicts[I].Message);
457     OS << "\"\n";
458   }
459 
460   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
461     OS.indent(Indent + 2);
462     OS << "conflict ";
463     OS << Conflicts[I].Other->getFullModuleName();
464     OS << ", \"";
465     OS.write_escaped(Conflicts[I].Message);
466     OS << "\"\n";
467   }
468 
469   if (InferSubmodules) {
470     OS.indent(Indent + 2);
471     if (InferExplicitSubmodules)
472       OS << "explicit ";
473     OS << "module * {\n";
474     if (InferExportWildcard) {
475       OS.indent(Indent + 4);
476       OS << "export *\n";
477     }
478     OS.indent(Indent + 2);
479     OS << "}\n";
480   }
481 
482   OS.indent(Indent);
483   OS << "}\n";
484 }
485 
486 LLVM_DUMP_METHOD void Module::dump() const {
487   print(llvm::errs());
488 }
489 
490 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
491                                   VisibleCallback Vis, ConflictCallback Cb) {
492   assert(Loc.isValid() && "setVisible expects a valid import location");
493   if (isVisible(M))
494     return;
495 
496   ++Generation;
497 
498   struct Visiting {
499     Module *M;
500     Visiting *ExportedBy;
501   };
502 
503   std::function<void(Visiting)> VisitModule = [&](Visiting V) {
504     // Modules that aren't available cannot be made visible.
505     if (!V.M->isAvailable())
506       return;
507 
508     // Nothing to do for a module that's already visible.
509     unsigned ID = V.M->getVisibilityID();
510     if (ImportLocs.size() <= ID)
511       ImportLocs.resize(ID + 1);
512     else if (ImportLocs[ID].isValid())
513       return;
514 
515     ImportLocs[ID] = Loc;
516     Vis(M);
517 
518     // Make any exported modules visible.
519     SmallVector<Module *, 16> Exports;
520     V.M->getExportedModules(Exports);
521     for (Module *E : Exports)
522       VisitModule({E, &V});
523 
524     for (auto &C : V.M->Conflicts) {
525       if (isVisible(C.Other)) {
526         llvm::SmallVector<Module*, 8> Path;
527         for (Visiting *I = &V; I; I = I->ExportedBy)
528           Path.push_back(I->M);
529         Cb(Path, C.Other, C.Message);
530       }
531     }
532   };
533   VisitModule({M, nullptr});
534 }
535