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