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