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