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