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                const FileEntry *File, bool IsFramework, bool IsExplicit)
29     : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), ModuleMap(File),
30       Umbrella(), ASTFile(0), IsMissingRequirement(false), IsAvailable(true),
31       IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit),
32       IsSystem(false), IsExternC(false), InferSubmodules(false),
33       InferExplicitSubmodules(false), InferExportWildcard(false),
34       ConfigMacrosExhaustive(false), NameVisibility(Hidden) {
35   if (Parent) {
36     if (!Parent->isAvailable())
37       IsAvailable = false;
38     if (Parent->IsSystem)
39       IsSystem = true;
40     if (Parent->IsExternC)
41       IsExternC = true;
42     IsMissingRequirement = Parent->IsMissingRequirement;
43 
44     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
45     Parent->SubModules.push_back(this);
46   }
47 }
48 
49 Module::~Module() {
50   for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
51        I != IEnd; ++I) {
52     delete *I;
53   }
54 }
55 
56 /// \brief Determine whether a translation unit built using the current
57 /// language options has the given feature.
58 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
59                        const TargetInfo &Target) {
60   return llvm::StringSwitch<bool>(Feature)
61            .Case("altivec", LangOpts.AltiVec)
62            .Case("blocks", LangOpts.Blocks)
63            .Case("cplusplus", LangOpts.CPlusPlus)
64            .Case("cplusplus11", LangOpts.CPlusPlus11)
65            .Case("objc", LangOpts.ObjC1)
66            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
67            .Case("opencl", LangOpts.OpenCL)
68            .Case("tls", Target.isTLSSupported())
69            .Default(Target.hasFeature(Feature));
70 }
71 
72 bool
73 Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
74                     Requirement &Req, HeaderDirective &MissingHeader) const {
75   if (IsAvailable)
76     return true;
77 
78   for (const Module *Current = this; Current; Current = Current->Parent) {
79     if (!Current->MissingHeaders.empty()) {
80       MissingHeader = Current->MissingHeaders.front();
81       return false;
82     }
83     for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
84       if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
85               Current->Requirements[I].second) {
86         Req = Current->Requirements[I];
87         return false;
88       }
89     }
90   }
91 
92   llvm_unreachable("could not find a reason why module is unavailable");
93 }
94 
95 bool Module::isSubModuleOf(const Module *Other) const {
96   const Module *This = this;
97   do {
98     if (This == Other)
99       return true;
100 
101     This = This->Parent;
102   } while (This);
103 
104   return false;
105 }
106 
107 const Module *Module::getTopLevelModule() const {
108   const Module *Result = this;
109   while (Result->Parent)
110     Result = Result->Parent;
111 
112   return Result;
113 }
114 
115 std::string Module::getFullModuleName() const {
116   SmallVector<StringRef, 2> Names;
117 
118   // Build up the set of module names (from innermost to outermost).
119   for (const Module *M = this; M; M = M->Parent)
120     Names.push_back(M->Name);
121 
122   std::string Result;
123   for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
124                                                  IEnd = Names.rend();
125        I != IEnd; ++I) {
126     if (!Result.empty())
127       Result += '.';
128 
129     Result += *I;
130   }
131 
132   return Result;
133 }
134 
135 const DirectoryEntry *Module::getUmbrellaDir() const {
136   if (const FileEntry *Header = getUmbrellaHeader())
137     return Header->getDir();
138 
139   return Umbrella.dyn_cast<const DirectoryEntry *>();
140 }
141 
142 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
143   if (!TopHeaderNames.empty()) {
144     for (std::vector<std::string>::iterator
145            I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
146       if (const FileEntry *FE = FileMgr.getFile(*I))
147         TopHeaders.insert(FE);
148     }
149     TopHeaderNames.clear();
150   }
151 
152   return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
153 }
154 
155 void Module::addRequirement(StringRef Feature, bool RequiredState,
156                             const LangOptions &LangOpts,
157                             const TargetInfo &Target) {
158   Requirements.push_back(Requirement(Feature, RequiredState));
159 
160   // If this feature is currently available, we're done.
161   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
162     return;
163 
164   markUnavailable(/*MissingRequirement*/true);
165 }
166 
167 void Module::markUnavailable(bool MissingRequirement) {
168   if (!IsAvailable)
169     return;
170 
171   SmallVector<Module *, 2> Stack;
172   Stack.push_back(this);
173   while (!Stack.empty()) {
174     Module *Current = Stack.back();
175     Stack.pop_back();
176 
177     if (!Current->IsAvailable)
178       continue;
179 
180     Current->IsAvailable = false;
181     Current->IsMissingRequirement |= MissingRequirement;
182     for (submodule_iterator Sub = Current->submodule_begin(),
183                          SubEnd = Current->submodule_end();
184          Sub != SubEnd; ++Sub) {
185       if ((*Sub)->IsAvailable)
186         Stack.push_back(*Sub);
187     }
188   }
189 }
190 
191 Module *Module::findSubmodule(StringRef Name) const {
192   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
193   if (Pos == SubModuleIndex.end())
194     return 0;
195 
196   return SubModules[Pos->getValue()];
197 }
198 
199 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
200   for (unsigned I = 0, N = Id.size(); I != N; ++I) {
201     if (I)
202       OS << ".";
203     OS << Id[I].first;
204   }
205 }
206 
207 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
208   // All non-explicit submodules are exported.
209   for (std::vector<Module *>::const_iterator I = SubModules.begin(),
210                                              E = SubModules.end();
211        I != E; ++I) {
212     Module *Mod = *I;
213     if (!Mod->IsExplicit)
214       Exported.push_back(Mod);
215   }
216 
217   // Find re-exported modules by filtering the list of imported modules.
218   bool AnyWildcard = false;
219   bool UnrestrictedWildcard = false;
220   SmallVector<Module *, 4> WildcardRestrictions;
221   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
222     Module *Mod = Exports[I].getPointer();
223     if (!Exports[I].getInt()) {
224       // Export a named module directly; no wildcards involved.
225       Exported.push_back(Mod);
226 
227       continue;
228     }
229 
230     // Wildcard export: export all of the imported modules that match
231     // the given pattern.
232     AnyWildcard = true;
233     if (UnrestrictedWildcard)
234       continue;
235 
236     if (Module *Restriction = Exports[I].getPointer())
237       WildcardRestrictions.push_back(Restriction);
238     else {
239       WildcardRestrictions.clear();
240       UnrestrictedWildcard = true;
241     }
242   }
243 
244   // If there were any wildcards, push any imported modules that were
245   // re-exported by the wildcard restriction.
246   if (!AnyWildcard)
247     return;
248 
249   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
250     Module *Mod = Imports[I];
251     bool Acceptable = UnrestrictedWildcard;
252     if (!Acceptable) {
253       // Check whether this module meets one of the restrictions.
254       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
255         Module *Restriction = WildcardRestrictions[R];
256         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
257           Acceptable = true;
258           break;
259         }
260       }
261     }
262 
263     if (!Acceptable)
264       continue;
265 
266     Exported.push_back(Mod);
267   }
268 }
269 
270 void Module::buildVisibleModulesCache() const {
271   assert(VisibleModulesCache.empty() && "cache does not need building");
272 
273   // This module is visible to itself.
274   VisibleModulesCache.insert(this);
275 
276   // Every imported module is visible.
277   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
278   while (!Stack.empty()) {
279     Module *CurrModule = Stack.pop_back_val();
280 
281     // Every module transitively exported by an imported module is visible.
282     if (VisibleModulesCache.insert(CurrModule).second)
283       CurrModule->getExportedModules(Stack);
284   }
285 }
286 
287 void Module::print(raw_ostream &OS, unsigned Indent) const {
288   OS.indent(Indent);
289   if (IsFramework)
290     OS << "framework ";
291   if (IsExplicit)
292     OS << "explicit ";
293   OS << "module " << Name;
294 
295   if (IsSystem) {
296     OS.indent(Indent + 2);
297     OS << " [system]";
298   }
299 
300   OS << " {\n";
301 
302   if (!Requirements.empty()) {
303     OS.indent(Indent + 2);
304     OS << "requires ";
305     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
306       if (I)
307         OS << ", ";
308       if (!Requirements[I].second)
309         OS << "!";
310       OS << Requirements[I].first;
311     }
312     OS << "\n";
313   }
314 
315   if (const FileEntry *UmbrellaHeader = getUmbrellaHeader()) {
316     OS.indent(Indent + 2);
317     OS << "umbrella header \"";
318     OS.write_escaped(UmbrellaHeader->getName());
319     OS << "\"\n";
320   } else if (const DirectoryEntry *UmbrellaDir = getUmbrellaDir()) {
321     OS.indent(Indent + 2);
322     OS << "umbrella \"";
323     OS.write_escaped(UmbrellaDir->getName());
324     OS << "\"\n";
325   }
326 
327   if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
328     OS.indent(Indent + 2);
329     OS << "config_macros ";
330     if (ConfigMacrosExhaustive)
331       OS << "[exhaustive]";
332     for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
333       if (I)
334         OS << ", ";
335       OS << ConfigMacros[I];
336     }
337     OS << "\n";
338   }
339 
340   for (unsigned I = 0, N = NormalHeaders.size(); I != N; ++I) {
341     OS.indent(Indent + 2);
342     OS << "header \"";
343     OS.write_escaped(NormalHeaders[I]->getName());
344     OS << "\"\n";
345   }
346 
347   for (unsigned I = 0, N = ExcludedHeaders.size(); I != N; ++I) {
348     OS.indent(Indent + 2);
349     OS << "exclude header \"";
350     OS.write_escaped(ExcludedHeaders[I]->getName());
351     OS << "\"\n";
352   }
353 
354   for (unsigned I = 0, N = PrivateHeaders.size(); I != N; ++I) {
355     OS.indent(Indent + 2);
356     OS << "private header \"";
357     OS.write_escaped(PrivateHeaders[I]->getName());
358     OS << "\"\n";
359   }
360 
361   for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
362        MI != MIEnd; ++MI)
363     (*MI)->print(OS, Indent + 2);
364 
365   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
366     OS.indent(Indent + 2);
367     OS << "export ";
368     if (Module *Restriction = Exports[I].getPointer()) {
369       OS << Restriction->getFullModuleName();
370       if (Exports[I].getInt())
371         OS << ".*";
372     } else {
373       OS << "*";
374     }
375     OS << "\n";
376   }
377 
378   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
379     OS.indent(Indent + 2);
380     OS << "export ";
381     printModuleId(OS, UnresolvedExports[I].Id);
382     if (UnresolvedExports[I].Wildcard) {
383       if (UnresolvedExports[I].Id.empty())
384         OS << "*";
385       else
386         OS << ".*";
387     }
388     OS << "\n";
389   }
390 
391   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
392     OS.indent(Indent + 2);
393     OS << "use ";
394     OS << DirectUses[I]->getFullModuleName();
395     OS << "\n";
396   }
397 
398   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
399     OS.indent(Indent + 2);
400     OS << "use ";
401     printModuleId(OS, UnresolvedDirectUses[I]);
402     OS << "\n";
403   }
404 
405   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
406     OS.indent(Indent + 2);
407     OS << "link ";
408     if (LinkLibraries[I].IsFramework)
409       OS << "framework ";
410     OS << "\"";
411     OS.write_escaped(LinkLibraries[I].Library);
412     OS << "\"";
413   }
414 
415   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
416     OS.indent(Indent + 2);
417     OS << "conflict ";
418     printModuleId(OS, UnresolvedConflicts[I].Id);
419     OS << ", \"";
420     OS.write_escaped(UnresolvedConflicts[I].Message);
421     OS << "\"\n";
422   }
423 
424   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
425     OS.indent(Indent + 2);
426     OS << "conflict ";
427     OS << Conflicts[I].Other->getFullModuleName();
428     OS << ", \"";
429     OS.write_escaped(Conflicts[I].Message);
430     OS << "\"\n";
431   }
432 
433   if (InferSubmodules) {
434     OS.indent(Indent + 2);
435     if (InferExplicitSubmodules)
436       OS << "explicit ";
437     OS << "module * {\n";
438     if (InferExportWildcard) {
439       OS.indent(Indent + 4);
440       OS << "export *\n";
441     }
442     OS.indent(Indent + 2);
443     OS << "}\n";
444   }
445 
446   OS.indent(Indent);
447   OS << "}\n";
448 }
449 
450 void Module::dump() const {
451   print(llvm::errs());
452 }
453 
454 
455