1 //===--- Module.h - Describe a module ---------------------------*- C++ -*-===//
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 /// \file
11 /// \brief Defines the clang::Module class, which describes a module in the
12 /// source code.
13 ///
14 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_MODULE_H
16 #define LLVM_CLANG_BASIC_MODULE_H
17 
18 #include "clang/Basic/SourceLocation.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/PointerIntPair.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringRef.h"
27 #include <string>
28 #include <utility>
29 #include <vector>
30 
31 namespace llvm {
32   class raw_ostream;
33 }
34 
35 namespace clang {
36 
37 class DirectoryEntry;
38 class FileEntry;
39 class FileManager;
40 class LangOptions;
41 class TargetInfo;
42 class IdentifierInfo;
43 
44 /// \brief Describes the name of a module.
45 typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId;
46 
47 /// \brief Describes a module or submodule.
48 class Module {
49 public:
50   /// \brief The name of this module.
51   std::string Name;
52 
53   /// \brief The location of the module definition.
54   SourceLocation DefinitionLoc;
55 
56   /// \brief The parent of this module. This will be NULL for the top-level
57   /// module.
58   Module *Parent;
59 
60   /// \brief The build directory of this module. This is the directory in
61   /// which the module is notionally built, and relative to which its headers
62   /// are found.
63   const DirectoryEntry *Directory;
64 
65   /// \brief The umbrella header or directory.
66   llvm::PointerUnion<const DirectoryEntry *, const FileEntry *> Umbrella;
67 
68 private:
69   /// \brief The submodules of this module, indexed by name.
70   std::vector<Module *> SubModules;
71 
72   /// \brief A mapping from the submodule name to the index into the
73   /// \c SubModules vector at which that submodule resides.
74   llvm::StringMap<unsigned> SubModuleIndex;
75 
76   /// \brief The AST file if this is a top-level module which has a
77   /// corresponding serialized AST file, or null otherwise.
78   const FileEntry *ASTFile;
79 
80   /// \brief The top-level headers associated with this module.
81   llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
82 
83   /// \brief top-level header filenames that aren't resolved to FileEntries yet.
84   std::vector<std::string> TopHeaderNames;
85 
86   /// \brief Cache of modules visible to lookup in this module.
87   mutable llvm::DenseSet<const Module*> VisibleModulesCache;
88 
89   /// The ID used when referencing this module within a VisibleModuleSet.
90   unsigned VisibilityID;
91 
92 public:
93   enum HeaderKind {
94     HK_Normal,
95     HK_Textual,
96     HK_Private,
97     HK_PrivateTextual,
98     HK_Excluded
99   };
100   static const int NumHeaderKinds = HK_Excluded + 1;
101 
102   /// \brief Information about a header directive as found in the module map
103   /// file.
104   struct Header {
105     std::string NameAsWritten;
106     const FileEntry *Entry;
107   };
108 
109   /// \brief The headers that are part of this module.
110   SmallVector<Header, 2> Headers[5];
111 
112   /// \brief Stored information about a header directive that was found in the
113   /// module map file but has not been resolved to a file.
114   struct UnresolvedHeaderDirective {
115     SourceLocation FileNameLoc;
116     std::string FileName;
117     bool IsUmbrella;
118   };
119 
120   /// \brief Headers that are mentioned in the module map file but could not be
121   /// found on the file system.
122   SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
123 
124   /// \brief An individual requirement: a feature name and a flag indicating
125   /// the required state of that feature.
126   typedef std::pair<std::string, bool> Requirement;
127 
128   /// \brief The set of language features required to use this module.
129   ///
130   /// If any of these requirements are not available, the \c IsAvailable bit
131   /// will be false to indicate that this (sub)module is not available.
132   SmallVector<Requirement, 2> Requirements;
133 
134   /// \brief Whether this module is missing a feature from \c Requirements.
135   unsigned IsMissingRequirement : 1;
136 
137   /// \brief Whether this module is available in the current translation unit.
138   ///
139   /// If the module is missing headers or does not meet all requirements then
140   /// this bit will be 0.
141   unsigned IsAvailable : 1;
142 
143   /// \brief Whether this module was loaded from a module file.
144   unsigned IsFromModuleFile : 1;
145 
146   /// \brief Whether this is a framework module.
147   unsigned IsFramework : 1;
148 
149   /// \brief Whether this is an explicit submodule.
150   unsigned IsExplicit : 1;
151 
152   /// \brief Whether this is a "system" module (which assumes that all
153   /// headers in it are system headers).
154   unsigned IsSystem : 1;
155 
156   /// \brief Whether this is an 'extern "C"' module (which implicitly puts all
157   /// headers in it within an 'extern "C"' block, and allows the module to be
158   /// imported within such a block).
159   unsigned IsExternC : 1;
160 
161   /// \brief Whether this is an inferred submodule (module * { ... }).
162   unsigned IsInferred : 1;
163 
164   /// \brief Whether we should infer submodules for this module based on
165   /// the headers.
166   ///
167   /// Submodules can only be inferred for modules with an umbrella header.
168   unsigned InferSubmodules : 1;
169 
170   /// \brief Whether, when inferring submodules, the inferred submodules
171   /// should be explicit.
172   unsigned InferExplicitSubmodules : 1;
173 
174   /// \brief Whether, when inferring submodules, the inferr submodules should
175   /// export all modules they import (e.g., the equivalent of "export *").
176   unsigned InferExportWildcard : 1;
177 
178   /// \brief Whether the set of configuration macros is exhaustive.
179   ///
180   /// When the set of configuration macros is exhaustive, meaning
181   /// that no identifier not in this list should affect how the module is
182   /// built.
183   unsigned ConfigMacrosExhaustive : 1;
184 
185   /// \brief Describes the visibility of the various names within a
186   /// particular module.
187   enum NameVisibilityKind {
188     /// \brief All of the names in this module are hidden.
189     Hidden,
190     /// \brief All of the names in this module are visible.
191     AllVisible
192   };
193 
194   /// \brief The visibility of names within this particular module.
195   NameVisibilityKind NameVisibility;
196 
197   /// \brief The location of the inferred submodule.
198   SourceLocation InferredSubmoduleLoc;
199 
200   /// \brief The set of modules imported by this module, and on which this
201   /// module depends.
202   llvm::SmallSetVector<Module *, 2> Imports;
203 
204   /// \brief Describes an exported module.
205   ///
206   /// The pointer is the module being re-exported, while the bit will be true
207   /// to indicate that this is a wildcard export.
208   typedef llvm::PointerIntPair<Module *, 1, bool> ExportDecl;
209 
210   /// \brief The set of export declarations.
211   SmallVector<ExportDecl, 2> Exports;
212 
213   /// \brief Describes an exported module that has not yet been resolved
214   /// (perhaps because the module it refers to has not yet been loaded).
215   struct UnresolvedExportDecl {
216     /// \brief The location of the 'export' keyword in the module map file.
217     SourceLocation ExportLoc;
218 
219     /// \brief The name of the module.
220     ModuleId Id;
221 
222     /// \brief Whether this export declaration ends in a wildcard, indicating
223     /// that all of its submodules should be exported (rather than the named
224     /// module itself).
225     bool Wildcard;
226   };
227 
228   /// \brief The set of export declarations that have yet to be resolved.
229   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
230 
231   /// \brief The directly used modules.
232   SmallVector<Module *, 2> DirectUses;
233 
234   /// \brief The set of use declarations that have yet to be resolved.
235   SmallVector<ModuleId, 2> UnresolvedDirectUses;
236 
237   /// \brief A library or framework to link against when an entity from this
238   /// module is used.
239   struct LinkLibrary {
240     LinkLibrary() : IsFramework(false) { }
241     LinkLibrary(const std::string &Library, bool IsFramework)
242       : Library(Library), IsFramework(IsFramework) { }
243 
244     /// \brief The library to link against.
245     ///
246     /// This will typically be a library or framework name, but can also
247     /// be an absolute path to the library or framework.
248     std::string Library;
249 
250     /// \brief Whether this is a framework rather than a library.
251     bool IsFramework;
252   };
253 
254   /// \brief The set of libraries or frameworks to link against when
255   /// an entity from this module is used.
256   llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
257 
258   /// \brief The set of "configuration macros", which are macros that
259   /// (intentionally) change how this module is built.
260   std::vector<std::string> ConfigMacros;
261 
262   /// \brief An unresolved conflict with another module.
263   struct UnresolvedConflict {
264     /// \brief The (unresolved) module id.
265     ModuleId Id;
266 
267     /// \brief The message provided to the user when there is a conflict.
268     std::string Message;
269   };
270 
271   /// \brief The list of conflicts for which the module-id has not yet been
272   /// resolved.
273   std::vector<UnresolvedConflict> UnresolvedConflicts;
274 
275   /// \brief A conflict between two modules.
276   struct Conflict {
277     /// \brief The module that this module conflicts with.
278     Module *Other;
279 
280     /// \brief The message provided to the user when there is a conflict.
281     std::string Message;
282   };
283 
284   /// \brief The list of conflicts.
285   std::vector<Conflict> Conflicts;
286 
287   /// \brief Construct a new module or submodule.
288   Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
289          bool IsFramework, bool IsExplicit, unsigned VisibilityID);
290 
291   ~Module();
292 
293   /// \brief Determine whether this module is available for use within the
294   /// current translation unit.
295   bool isAvailable() const { return IsAvailable; }
296 
297   /// \brief Determine whether this module is available for use within the
298   /// current translation unit.
299   ///
300   /// \param LangOpts The language options used for the current
301   /// translation unit.
302   ///
303   /// \param Target The target options used for the current translation unit.
304   ///
305   /// \param Req If this module is unavailable, this parameter
306   /// will be set to one of the requirements that is not met for use of
307   /// this module.
308   bool isAvailable(const LangOptions &LangOpts,
309                    const TargetInfo &Target,
310                    Requirement &Req,
311                    UnresolvedHeaderDirective &MissingHeader) const;
312 
313   /// \brief Determine whether this module is a submodule.
314   bool isSubModule() const { return Parent != nullptr; }
315 
316   /// \brief Determine whether this module is a submodule of the given other
317   /// module.
318   bool isSubModuleOf(const Module *Other) const;
319 
320   /// \brief Determine whether this module is a part of a framework,
321   /// either because it is a framework module or because it is a submodule
322   /// of a framework module.
323   bool isPartOfFramework() const {
324     for (const Module *Mod = this; Mod; Mod = Mod->Parent)
325       if (Mod->IsFramework)
326         return true;
327 
328     return false;
329   }
330 
331   /// \brief Determine whether this module is a subframework of another
332   /// framework.
333   bool isSubFramework() const {
334     return IsFramework && Parent && Parent->isPartOfFramework();
335   }
336 
337   /// \brief Retrieve the full name of this module, including the path from
338   /// its top-level module.
339   std::string getFullModuleName() const;
340 
341   /// \brief Retrieve the top-level module for this (sub)module, which may
342   /// be this module.
343   Module *getTopLevelModule() {
344     return const_cast<Module *>(
345              const_cast<const Module *>(this)->getTopLevelModule());
346   }
347 
348   /// \brief Retrieve the top-level module for this (sub)module, which may
349   /// be this module.
350   const Module *getTopLevelModule() const;
351 
352   /// \brief Retrieve the name of the top-level module.
353   ///
354   StringRef getTopLevelModuleName() const {
355     return getTopLevelModule()->Name;
356   }
357 
358   /// \brief The serialized AST file for this module, if one was created.
359   const FileEntry *getASTFile() const {
360     return getTopLevelModule()->ASTFile;
361   }
362 
363   /// \brief Set the serialized AST file for the top-level module of this module.
364   void setASTFile(const FileEntry *File) {
365     assert((File == nullptr || getASTFile() == nullptr ||
366             getASTFile() == File) && "file path changed");
367     getTopLevelModule()->ASTFile = File;
368   }
369 
370   /// \brief Retrieve the directory for which this module serves as the
371   /// umbrella.
372   const DirectoryEntry *getUmbrellaDir() const;
373 
374   /// \brief Retrieve the header that serves as the umbrella header for this
375   /// module.
376   const FileEntry *getUmbrellaHeader() const {
377     return Umbrella.dyn_cast<const FileEntry *>();
378   }
379 
380   /// \brief Determine whether this module has an umbrella directory that is
381   /// not based on an umbrella header.
382   bool hasUmbrellaDir() const {
383     return Umbrella && Umbrella.is<const DirectoryEntry *>();
384   }
385 
386   /// \brief Add a top-level header associated with this module.
387   void addTopHeader(const FileEntry *File) {
388     assert(File);
389     TopHeaders.insert(File);
390   }
391 
392   /// \brief Add a top-level header filename associated with this module.
393   void addTopHeaderFilename(StringRef Filename) {
394     TopHeaderNames.push_back(Filename);
395   }
396 
397   /// \brief The top-level headers associated with this module.
398   ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
399 
400   /// \brief Determine whether this module has declared its intention to
401   /// directly use another module.
402   bool directlyUses(const Module *Requested) const;
403 
404   /// \brief Add the given feature requirement to the list of features
405   /// required by this module.
406   ///
407   /// \param Feature The feature that is required by this module (and
408   /// its submodules).
409   ///
410   /// \param RequiredState The required state of this feature: \c true
411   /// if it must be present, \c false if it must be absent.
412   ///
413   /// \param LangOpts The set of language options that will be used to
414   /// evaluate the availability of this feature.
415   ///
416   /// \param Target The target options that will be used to evaluate the
417   /// availability of this feature.
418   void addRequirement(StringRef Feature, bool RequiredState,
419                       const LangOptions &LangOpts,
420                       const TargetInfo &Target);
421 
422   /// \brief Mark this module and all of its submodules as unavailable.
423   void markUnavailable(bool MissingRequirement = false);
424 
425   /// \brief Find the submodule with the given name.
426   ///
427   /// \returns The submodule if found, or NULL otherwise.
428   Module *findSubmodule(StringRef Name) const;
429 
430   /// \brief Determine whether the specified module would be visible to
431   /// a lookup at the end of this module.
432   ///
433   /// FIXME: This may return incorrect results for (submodules of) the
434   /// module currently being built, if it's queried before we see all
435   /// of its imports.
436   bool isModuleVisible(const Module *M) const {
437     if (VisibleModulesCache.empty())
438       buildVisibleModulesCache();
439     return VisibleModulesCache.count(M);
440   }
441 
442   unsigned getVisibilityID() const { return VisibilityID; }
443 
444   typedef std::vector<Module *>::iterator submodule_iterator;
445   typedef std::vector<Module *>::const_iterator submodule_const_iterator;
446 
447   submodule_iterator submodule_begin() { return SubModules.begin(); }
448   submodule_const_iterator submodule_begin() const {return SubModules.begin();}
449   submodule_iterator submodule_end()   { return SubModules.end(); }
450   submodule_const_iterator submodule_end() const { return SubModules.end(); }
451 
452   /// \brief Appends this module's list of exported modules to \p Exported.
453   ///
454   /// This provides a subset of immediately imported modules (the ones that are
455   /// directly exported), not the complete set of exported modules.
456   void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
457 
458   static StringRef getModuleInputBufferName() {
459     return "<module-includes>";
460   }
461 
462   /// \brief Print the module map for this module to the given stream.
463   ///
464   void print(raw_ostream &OS, unsigned Indent = 0) const;
465 
466   /// \brief Dump the contents of this module to the given output stream.
467   void dump() const;
468 
469 private:
470   void buildVisibleModulesCache() const;
471 };
472 
473 /// \brief A set of visible modules.
474 class VisibleModuleSet {
475 public:
476   VisibleModuleSet() : Generation(0) {}
477   VisibleModuleSet(VisibleModuleSet &&O)
478       : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
479     O.ImportLocs.clear();
480     ++O.Generation;
481   }
482 
483   /// Move from another visible modules set. Guaranteed to leave the source
484   /// empty and bump the generation on both.
485   VisibleModuleSet &operator=(VisibleModuleSet &&O) {
486     ImportLocs = std::move(O.ImportLocs);
487     O.ImportLocs.clear();
488     ++O.Generation;
489     ++Generation;
490     return *this;
491   }
492 
493   /// \brief Get the current visibility generation. Incremented each time the
494   /// set of visible modules changes in any way.
495   unsigned getGeneration() const { return Generation; }
496 
497   /// \brief Determine whether a module is visible.
498   bool isVisible(const Module *M) const {
499     return getImportLoc(M).isValid();
500   }
501 
502   /// \brief Get the location at which the import of a module was triggered.
503   SourceLocation getImportLoc(const Module *M) const {
504     return M->getVisibilityID() < ImportLocs.size()
505                ? ImportLocs[M->getVisibilityID()]
506                : SourceLocation();
507   }
508 
509   /// \brief A callback to call when a module is made visible (directly or
510   /// indirectly) by a call to \ref setVisible.
511   typedef llvm::function_ref<void(Module *M)> VisibleCallback;
512   /// \brief A callback to call when a module conflict is found. \p Path
513   /// consists of a sequence of modules from the conflicting module to the one
514   /// made visible, where each was exported by the next.
515   typedef llvm::function_ref<void(ArrayRef<Module *> Path,
516                                   Module *Conflict, StringRef Message)>
517       ConflictCallback;
518   /// \brief Make a specific module visible.
519   void setVisible(Module *M, SourceLocation Loc,
520                   VisibleCallback Vis, ConflictCallback Cb);
521 
522 private:
523   /// Import locations for each visible module. Indexed by the module's
524   /// VisibilityID.
525   std::vector<SourceLocation> ImportLocs;
526   /// Visibility generation, bumped every time the visibility state changes.
527   unsigned Generation;
528 };
529 
530 } // end namespace clang
531 
532 
533 #endif // LLVM_CLANG_BASIC_MODULE_H
534