]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Basic/Module.cpp
Merge ^/head r313896 through r314128.
[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       NoUndeclaredIncludes(false), 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     if (Parent->NoUndeclaredIncludes)
45       NoUndeclaredIncludes = true;
46     IsMissingRequirement = Parent->IsMissingRequirement;
47     
48     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
49     Parent->SubModules.push_back(this);
50   }
51 }
52
53 Module::~Module() {
54   for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
55        I != IEnd; ++I) {
56     delete *I;
57   }
58 }
59
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));
77   if (!HasFeature)
78     HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
79                            LangOpts.ModuleFeatures.end(),
80                            Feature) != LangOpts.ModuleFeatures.end();
81   return HasFeature;
82 }
83
84 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
85                          Requirement &Req,
86                          UnresolvedHeaderDirective &MissingHeader) const {
87   if (IsAvailable)
88     return true;
89
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];
95         return false;
96       }
97     }
98     if (!Current->MissingHeaders.empty()) {
99       MissingHeader = Current->MissingHeaders.front();
100       return false;
101     }
102   }
103
104   llvm_unreachable("could not find a reason why module is unavailable");
105 }
106
107 bool Module::isSubModuleOf(const Module *Other) const {
108   const Module *This = this;
109   do {
110     if (This == Other)
111       return true;
112     
113     This = This->Parent;
114   } while (This);
115   
116   return false;
117 }
118
119 const Module *Module::getTopLevelModule() const {
120   const Module *Result = this;
121   while (Result->Parent)
122     Result = Result->Parent;
123   
124   return Result;
125 }
126
127 std::string Module::getFullModuleName() const {
128   SmallVector<StringRef, 2> Names;
129   
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);
133   
134   std::string Result;
135   for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
136                                                  IEnd = Names.rend();
137        I != IEnd; ++I) {
138     if (!Result.empty())
139       Result += '.';
140     
141     Result += *I;
142   }
143   
144   return Result;
145 }
146
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())
150       return false;
151     nameParts = nameParts.drop_back();
152   }
153   return nameParts.empty();
154 }
155
156 Module::DirectoryName Module::getUmbrellaDir() const {
157   if (Header U = getUmbrellaHeader())
158     return {"", U.Entry->getDir()};
159   
160   return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
161 }
162
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);
169     }
170     TopHeaderNames.clear();
171   }
172
173   return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
174 }
175
176 bool Module::directlyUses(const Module *Requested) const {
177   auto *Top = getTopLevelModule();
178
179   // A top-level module implicitly uses itself.
180   if (Requested->isSubModuleOf(Top))
181     return true;
182
183   for (auto *Use : Top->DirectUses)
184     if (Requested->isSubModuleOf(Use))
185       return true;
186
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")
189     return true;
190
191   return false;
192 }
193
194 void Module::addRequirement(StringRef Feature, bool RequiredState,
195                             const LangOptions &LangOpts,
196                             const TargetInfo &Target) {
197   Requirements.push_back(Requirement(Feature, RequiredState));
198
199   // If this feature is currently available, we're done.
200   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
201     return;
202
203   markUnavailable(/*MissingRequirement*/true);
204 }
205
206 void Module::markUnavailable(bool MissingRequirement) {
207   auto needUpdate = [MissingRequirement](Module *M) {
208     return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
209   };
210
211   if (!needUpdate(this))
212     return;
213
214   SmallVector<Module *, 2> Stack;
215   Stack.push_back(this);
216   while (!Stack.empty()) {
217     Module *Current = Stack.back();
218     Stack.pop_back();
219
220     if (!needUpdate(Current))
221       continue;
222
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);
230     }
231   }
232 }
233
234 Module *Module::findSubmodule(StringRef Name) const {
235   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
236   if (Pos == SubModuleIndex.end())
237     return nullptr;
238
239   return SubModules[Pos->getValue()];
240 }
241
242 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
243   for (unsigned I = 0, N = Id.size(); I != N; ++I) {
244     if (I)
245       OS << ".";
246     OS << Id[I].first;
247   }
248 }
249
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();
254        I != E; ++I) {
255     Module *Mod = *I;
256     if (!Mod->IsExplicit)
257       Exported.push_back(Mod);
258   }
259
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);
269
270       continue;
271     }
272
273     // Wildcard export: export all of the imported modules that match
274     // the given pattern.
275     AnyWildcard = true;
276     if (UnrestrictedWildcard)
277       continue;
278
279     if (Module *Restriction = Exports[I].getPointer())
280       WildcardRestrictions.push_back(Restriction);
281     else {
282       WildcardRestrictions.clear();
283       UnrestrictedWildcard = true;
284     }
285   }
286
287   // If there were any wildcards, push any imported modules that were
288   // re-exported by the wildcard restriction.
289   if (!AnyWildcard)
290     return;
291
292   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
293     Module *Mod = Imports[I];
294     bool Acceptable = UnrestrictedWildcard;
295     if (!Acceptable) {
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)) {
300           Acceptable = true;
301           break;
302         }
303       }
304     }
305
306     if (!Acceptable)
307       continue;
308
309     Exported.push_back(Mod);
310   }
311 }
312
313 void Module::buildVisibleModulesCache() const {
314   assert(VisibleModulesCache.empty() && "cache does not need building");
315
316   // This module is visible to itself.
317   VisibleModulesCache.insert(this);
318
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();
323
324     // Every module transitively exported by an imported module is visible.
325     if (VisibleModulesCache.insert(CurrModule).second)
326       CurrModule->getExportedModules(Stack);
327   }
328 }
329
330 void Module::print(raw_ostream &OS, unsigned Indent) const {
331   OS.indent(Indent);
332   if (IsFramework)
333     OS << "framework ";
334   if (IsExplicit)
335     OS << "explicit ";
336   OS << "module " << Name;
337
338   if (IsSystem || IsExternC) {
339     OS.indent(Indent + 2);
340     if (IsSystem)
341       OS << " [system]";
342     if (IsExternC)
343       OS << " [extern_c]";
344   }
345
346   OS << " {\n";
347   
348   if (!Requirements.empty()) {
349     OS.indent(Indent + 2);
350     OS << "requires ";
351     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
352       if (I)
353         OS << ", ";
354       if (!Requirements[I].second)
355         OS << "!";
356       OS << Requirements[I].first;
357     }
358     OS << "\n";
359   }
360   
361   if (Header H = getUmbrellaHeader()) {
362     OS.indent(Indent + 2);
363     OS << "umbrella header \"";
364     OS.write_escaped(H.NameAsWritten);
365     OS << "\"\n";
366   } else if (DirectoryName D = getUmbrellaDir()) {
367     OS.indent(Indent + 2);
368     OS << "umbrella \"";
369     OS.write_escaped(D.NameAsWritten);
370     OS << "\"\n";    
371   }
372
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) {
379       if (I)
380         OS << ", ";
381       OS << ConfigMacros[I];
382     }
383     OS << "\n";
384   }
385
386   struct {
387     StringRef Prefix;
388     HeaderKind Kind;
389   } Kinds[] = {{"", HK_Normal},
390                {"textual ", HK_Textual},
391                {"private ", HK_Private},
392                {"private textual ", HK_PrivateTextual},
393                {"exclude ", HK_Excluded}};
394
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);
400       OS << "\"\n";
401     }
402   }
403
404   for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
405        MI != MIEnd; ++MI)
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);
412   
413   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
414     OS.indent(Indent + 2);
415     OS << "export ";
416     if (Module *Restriction = Exports[I].getPointer()) {
417       OS << Restriction->getFullModuleName();
418       if (Exports[I].getInt())
419         OS << ".*";
420     } else {
421       OS << "*";
422     }
423     OS << "\n";
424   }
425
426   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
427     OS.indent(Indent + 2);
428     OS << "export ";
429     printModuleId(OS, UnresolvedExports[I].Id);
430     if (UnresolvedExports[I].Wildcard)
431       OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
432     OS << "\n";
433   }
434
435   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
436     OS.indent(Indent + 2);
437     OS << "use ";
438     OS << DirectUses[I]->getFullModuleName();
439     OS << "\n";
440   }
441
442   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
443     OS.indent(Indent + 2);
444     OS << "use ";
445     printModuleId(OS, UnresolvedDirectUses[I]);
446     OS << "\n";
447   }
448
449   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
450     OS.indent(Indent + 2);
451     OS << "link ";
452     if (LinkLibraries[I].IsFramework)
453       OS << "framework ";
454     OS << "\"";
455     OS.write_escaped(LinkLibraries[I].Library);
456     OS << "\"";
457   }
458
459   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
460     OS.indent(Indent + 2);
461     OS << "conflict ";
462     printModuleId(OS, UnresolvedConflicts[I].Id);
463     OS << ", \"";
464     OS.write_escaped(UnresolvedConflicts[I].Message);
465     OS << "\"\n";
466   }
467
468   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
469     OS.indent(Indent + 2);
470     OS << "conflict ";
471     OS << Conflicts[I].Other->getFullModuleName();
472     OS << ", \"";
473     OS.write_escaped(Conflicts[I].Message);
474     OS << "\"\n";
475   }
476
477   if (InferSubmodules) {
478     OS.indent(Indent + 2);
479     if (InferExplicitSubmodules)
480       OS << "explicit ";
481     OS << "module * {\n";
482     if (InferExportWildcard) {
483       OS.indent(Indent + 4);
484       OS << "export *\n";
485     }
486     OS.indent(Indent + 2);
487     OS << "}\n";
488   }
489   
490   OS.indent(Indent);
491   OS << "}\n";
492 }
493
494 LLVM_DUMP_METHOD void Module::dump() const {
495   print(llvm::errs());
496 }
497
498 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
499                                   VisibleCallback Vis, ConflictCallback Cb) {
500   assert(Loc.isValid() && "setVisible expects a valid import location");
501   if (isVisible(M))
502     return;
503
504   ++Generation;
505
506   struct Visiting {
507     Module *M;
508     Visiting *ExportedBy;
509   };
510
511   std::function<void(Visiting)> VisitModule = [&](Visiting V) {
512     // Modules that aren't available cannot be made visible.
513     if (!V.M->isAvailable())
514       return;
515
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())
521       return;
522
523     ImportLocs[ID] = Loc;
524     Vis(M);
525
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});
531
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);
538       }
539     }
540   };
541   VisitModule({M, nullptr});
542 }