Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Basic/Module.h
Line
Count
Source (jump to first uncovered line)
1
//===- Module.h - Describe a module -----------------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
/// \file
10
/// Defines the clang::Module class, which describes a module in the
11
/// source code.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#ifndef LLVM_CLANG_BASIC_MODULE_H
16
#define LLVM_CLANG_BASIC_MODULE_H
17
18
#include "clang/Basic/DirectoryEntry.h"
19
#include "clang/Basic/FileEntry.h"
20
#include "clang/Basic/SourceLocation.h"
21
#include "llvm/ADT/ArrayRef.h"
22
#include "llvm/ADT/DenseSet.h"
23
#include "llvm/ADT/Optional.h"
24
#include "llvm/ADT/PointerIntPair.h"
25
#include "llvm/ADT/STLExtras.h"
26
#include "llvm/ADT/SetVector.h"
27
#include "llvm/ADT/SmallVector.h"
28
#include "llvm/ADT/StringMap.h"
29
#include "llvm/ADT/StringRef.h"
30
#include "llvm/ADT/iterator_range.h"
31
#include <array>
32
#include <cassert>
33
#include <cstdint>
34
#include <ctime>
35
#include <iterator>
36
#include <string>
37
#include <utility>
38
#include <vector>
39
40
namespace llvm {
41
42
class raw_ostream;
43
44
} // namespace llvm
45
46
namespace clang {
47
48
class FileManager;
49
class LangOptions;
50
class TargetInfo;
51
52
/// Describes the name of a module.
53
using ModuleId = SmallVector<std::pair<std::string, SourceLocation>, 2>;
54
55
/// The signature of a module, which is a hash of the AST content.
56
struct ASTFileSignature : std::array<uint8_t, 20> {
57
  using BaseT = std::array<uint8_t, 20>;
58
59
  static constexpr size_t size = std::tuple_size<BaseT>::value;
60
61
1.96M
  ASTFileSignature(BaseT S = {{0}}) : BaseT(std::move(S)) {}
62
63
47.6k
  explicit operator bool() const { return *this != BaseT({{0}}); }
64
65
  /// Returns the value truncated to the size of an uint64_t.
66
1.73k
  uint64_t truncatedValue() const {
67
1.73k
    uint64_t Value = 0;
68
1.73k
    static_assert(sizeof(*this) >= sizeof(uint64_t), "No need to truncate.");
69
15.6k
    for (unsigned I = 0; I < sizeof(uint64_t); 
++I13.8k
)
70
13.8k
      Value |= static_cast<uint64_t>((*this)[I]) << (I * 8);
71
1.73k
    return Value;
72
1.73k
  }
73
74
3.37k
  static ASTFileSignature create(StringRef Bytes) {
75
3.37k
    return create(Bytes.bytes_begin(), Bytes.bytes_end());
76
3.37k
  }
77
78
263
  static ASTFileSignature createDISentinel() {
79
263
    ASTFileSignature Sentinel;
80
263
    Sentinel.fill(0xFF);
81
263
    return Sentinel;
82
263
  }
83
84
  template <typename InputIt>
85
65.0k
  static ASTFileSignature create(InputIt First, InputIt Last) {
86
65.0k
    assert(std::distance(First, Last) == size &&
87
65.0k
           "Wrong amount of bytes to create an ASTFileSignature");
88
89
0
    ASTFileSignature Signature;
90
65.0k
    std::copy(First, Last, Signature.begin());
91
65.0k
    return Signature;
92
65.0k
  }
clang::ASTFileSignature clang::ASTFileSignature::create<unsigned char const*>(unsigned char const*, unsigned char const*)
Line
Count
Source
85
3.37k
  static ASTFileSignature create(InputIt First, InputIt Last) {
86
3.37k
    assert(std::distance(First, Last) == size &&
87
3.37k
           "Wrong amount of bytes to create an ASTFileSignature");
88
89
0
    ASTFileSignature Signature;
90
3.37k
    std::copy(First, Last, Signature.begin());
91
3.37k
    return Signature;
92
3.37k
  }
clang::ASTFileSignature clang::ASTFileSignature::create<unsigned long long*>(unsigned long long*, unsigned long long*)
Line
Count
Source
85
61.6k
  static ASTFileSignature create(InputIt First, InputIt Last) {
86
61.6k
    assert(std::distance(First, Last) == size &&
87
61.6k
           "Wrong amount of bytes to create an ASTFileSignature");
88
89
0
    ASTFileSignature Signature;
90
61.6k
    std::copy(First, Last, Signature.begin());
91
61.6k
    return Signature;
92
61.6k
  }
93
};
94
95
/// Describes a module or submodule.
96
class Module {
97
public:
98
  /// The name of this module.
99
  std::string Name;
100
101
  /// The location of the module definition.
102
  SourceLocation DefinitionLoc;
103
104
  enum ModuleKind {
105
    /// This is a module that was defined by a module map and built out
106
    /// of header files.
107
    ModuleMapModule,
108
109
    /// This is a C++ Modules TS module interface unit.
110
    ModuleInterfaceUnit,
111
112
    /// This is a fragment of the global module within some C++ module.
113
    GlobalModuleFragment,
114
115
    /// This is the private module fragment within some C++ module.
116
    PrivateModuleFragment,
117
  };
118
119
  /// The kind of this module.
120
  ModuleKind Kind = ModuleMapModule;
121
122
  /// The parent of this module. This will be NULL for the top-level
123
  /// module.
124
  Module *Parent;
125
126
  /// The build directory of this module. This is the directory in
127
  /// which the module is notionally built, and relative to which its headers
128
  /// are found.
129
  const DirectoryEntry *Directory = nullptr;
130
131
  /// The presumed file name for the module map defining this module.
132
  /// Only non-empty when building from preprocessed source.
133
  std::string PresumedModuleMapFile;
134
135
  /// The umbrella header or directory.
136
  llvm::PointerUnion<const FileEntry *, const DirectoryEntry *> Umbrella;
137
138
  /// The module signature.
139
  ASTFileSignature Signature;
140
141
  /// The name of the umbrella entry, as written in the module map.
142
  std::string UmbrellaAsWritten;
143
144
  // The path to the umbrella entry relative to the root module's \c Directory.
145
  std::string UmbrellaRelativeToRootModuleDirectory;
146
147
  /// The module through which entities defined in this module will
148
  /// eventually be exposed, for use in "private" modules.
149
  std::string ExportAsModule;
150
151
  /// Does this Module scope describe part of the purview of a named C++ module?
152
613k
  bool isModulePurview() const {
153
613k
    return Kind == ModuleInterfaceUnit || 
Kind == PrivateModuleFragment612k
;
154
613k
  }
155
156
  /// Does this Module scope describe a fragment of the global module within
157
  /// some C++ module.
158
50
  bool isGlobalModule() const { return Kind == GlobalModuleFragment; }
159
160
private:
161
  /// The submodules of this module, indexed by name.
162
  std::vector<Module *> SubModules;
163
164
  /// A mapping from the submodule name to the index into the
165
  /// \c SubModules vector at which that submodule resides.
166
  llvm::StringMap<unsigned> SubModuleIndex;
167
168
  /// The AST file if this is a top-level module which has a
169
  /// corresponding serialized AST file, or null otherwise.
170
  Optional<FileEntryRef> ASTFile;
171
172
  /// The top-level headers associated with this module.
173
  llvm::SmallSetVector<const FileEntry *, 2> TopHeaders;
174
175
  /// top-level header filenames that aren't resolved to FileEntries yet.
176
  std::vector<std::string> TopHeaderNames;
177
178
  /// Cache of modules visible to lookup in this module.
179
  mutable llvm::DenseSet<const Module*> VisibleModulesCache;
180
181
  /// The ID used when referencing this module within a VisibleModuleSet.
182
  unsigned VisibilityID;
183
184
public:
185
  enum HeaderKind {
186
    HK_Normal,
187
    HK_Textual,
188
    HK_Private,
189
    HK_PrivateTextual,
190
    HK_Excluded
191
  };
192
  static const int NumHeaderKinds = HK_Excluded + 1;
193
194
  /// Information about a header directive as found in the module map
195
  /// file.
196
  struct Header {
197
    std::string NameAsWritten;
198
    std::string PathRelativeToRootModuleDirectory;
199
    const FileEntry *Entry;
200
201
152k
    explicit operator bool() { return Entry; }
202
  };
203
204
  /// Information about a directory name as found in the module map
205
  /// file.
206
  struct DirectoryName {
207
    std::string NameAsWritten;
208
    std::string PathRelativeToRootModuleDirectory;
209
    const DirectoryEntry *Entry;
210
211
84.2k
    explicit operator bool() { return Entry; }
212
  };
213
214
  /// The headers that are part of this module.
215
  SmallVector<Header, 2> Headers[5];
216
217
  /// Stored information about a header directive that was found in the
218
  /// module map file but has not been resolved to a file.
219
  struct UnresolvedHeaderDirective {
220
    HeaderKind Kind = HK_Normal;
221
    SourceLocation FileNameLoc;
222
    std::string FileName;
223
    bool IsUmbrella = false;
224
    bool HasBuiltinHeader = false;
225
    Optional<off_t> Size;
226
    Optional<time_t> ModTime;
227
  };
228
229
  /// Headers that are mentioned in the module map file but that we have not
230
  /// yet attempted to resolve to a file on the file system.
231
  SmallVector<UnresolvedHeaderDirective, 1> UnresolvedHeaders;
232
233
  /// Headers that are mentioned in the module map file but could not be
234
  /// found on the file system.
235
  SmallVector<UnresolvedHeaderDirective, 1> MissingHeaders;
236
237
  /// An individual requirement: a feature name and a flag indicating
238
  /// the required state of that feature.
239
  using Requirement = std::pair<std::string, bool>;
240
241
  /// The set of language features required to use this module.
242
  ///
243
  /// If any of these requirements are not available, the \c IsAvailable bit
244
  /// will be false to indicate that this (sub)module is not available.
245
  SmallVector<Requirement, 2> Requirements;
246
247
  /// A module with the same name that shadows this module.
248
  Module *ShadowingModule = nullptr;
249
250
  /// Whether this module has declared itself unimportable, either because
251
  /// it's missing a requirement from \p Requirements or because it's been
252
  /// shadowed by another module.
253
  unsigned IsUnimportable : 1;
254
255
  /// Whether we tried and failed to load a module file for this module.
256
  unsigned HasIncompatibleModuleFile : 1;
257
258
  /// Whether this module is available in the current translation unit.
259
  ///
260
  /// If the module is missing headers or does not meet all requirements then
261
  /// this bit will be 0.
262
  unsigned IsAvailable : 1;
263
264
  /// Whether this module was loaded from a module file.
265
  unsigned IsFromModuleFile : 1;
266
267
  /// Whether this is a framework module.
268
  unsigned IsFramework : 1;
269
270
  /// Whether this is an explicit submodule.
271
  unsigned IsExplicit : 1;
272
273
  /// Whether this is a "system" module (which assumes that all
274
  /// headers in it are system headers).
275
  unsigned IsSystem : 1;
276
277
  /// Whether this is an 'extern "C"' module (which implicitly puts all
278
  /// headers in it within an 'extern "C"' block, and allows the module to be
279
  /// imported within such a block).
280
  unsigned IsExternC : 1;
281
282
  /// Whether this is an inferred submodule (module * { ... }).
283
  unsigned IsInferred : 1;
284
285
  /// Whether we should infer submodules for this module based on
286
  /// the headers.
287
  ///
288
  /// Submodules can only be inferred for modules with an umbrella header.
289
  unsigned InferSubmodules : 1;
290
291
  /// Whether, when inferring submodules, the inferred submodules
292
  /// should be explicit.
293
  unsigned InferExplicitSubmodules : 1;
294
295
  /// Whether, when inferring submodules, the inferr submodules should
296
  /// export all modules they import (e.g., the equivalent of "export *").
297
  unsigned InferExportWildcard : 1;
298
299
  /// Whether the set of configuration macros is exhaustive.
300
  ///
301
  /// When the set of configuration macros is exhaustive, meaning
302
  /// that no identifier not in this list should affect how the module is
303
  /// built.
304
  unsigned ConfigMacrosExhaustive : 1;
305
306
  /// Whether files in this module can only include non-modular headers
307
  /// and headers from used modules.
308
  unsigned NoUndeclaredIncludes : 1;
309
310
  /// Whether this module came from a "private" module map, found next
311
  /// to a regular (public) module map.
312
  unsigned ModuleMapIsPrivate : 1;
313
314
  /// Describes the visibility of the various names within a
315
  /// particular module.
316
  enum NameVisibilityKind {
317
    /// All of the names in this module are hidden.
318
    Hidden,
319
    /// All of the names in this module are visible.
320
    AllVisible
321
  };
322
323
  /// The visibility of names within this particular module.
324
  NameVisibilityKind NameVisibility;
325
326
  /// The location of the inferred submodule.
327
  SourceLocation InferredSubmoduleLoc;
328
329
  /// The set of modules imported by this module, and on which this
330
  /// module depends.
331
  llvm::SmallSetVector<Module *, 2> Imports;
332
333
  /// Describes an exported module.
334
  ///
335
  /// The pointer is the module being re-exported, while the bit will be true
336
  /// to indicate that this is a wildcard export.
337
  using ExportDecl = llvm::PointerIntPair<Module *, 1, bool>;
338
339
  /// The set of export declarations.
340
  SmallVector<ExportDecl, 2> Exports;
341
342
  /// Describes an exported module that has not yet been resolved
343
  /// (perhaps because the module it refers to has not yet been loaded).
344
  struct UnresolvedExportDecl {
345
    /// The location of the 'export' keyword in the module map file.
346
    SourceLocation ExportLoc;
347
348
    /// The name of the module.
349
    ModuleId Id;
350
351
    /// Whether this export declaration ends in a wildcard, indicating
352
    /// that all of its submodules should be exported (rather than the named
353
    /// module itself).
354
    bool Wildcard;
355
  };
356
357
  /// The set of export declarations that have yet to be resolved.
358
  SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
359
360
  /// The directly used modules.
361
  SmallVector<Module *, 2> DirectUses;
362
363
  /// The set of use declarations that have yet to be resolved.
364
  SmallVector<ModuleId, 2> UnresolvedDirectUses;
365
366
  /// A library or framework to link against when an entity from this
367
  /// module is used.
368
  struct LinkLibrary {
369
    LinkLibrary() = default;
370
    LinkLibrary(const std::string &Library, bool IsFramework)
371
18.1k
        : Library(Library), IsFramework(IsFramework) {}
372
373
    /// The library to link against.
374
    ///
375
    /// This will typically be a library or framework name, but can also
376
    /// be an absolute path to the library or framework.
377
    std::string Library;
378
379
    /// Whether this is a framework rather than a library.
380
    bool IsFramework = false;
381
  };
382
383
  /// The set of libraries or frameworks to link against when
384
  /// an entity from this module is used.
385
  llvm::SmallVector<LinkLibrary, 2> LinkLibraries;
386
387
  /// Autolinking uses the framework name for linking purposes
388
  /// when this is false and the export_as name otherwise.
389
  bool UseExportAsModuleLinkName = false;
390
391
  /// The set of "configuration macros", which are macros that
392
  /// (intentionally) change how this module is built.
393
  std::vector<std::string> ConfigMacros;
394
395
  /// An unresolved conflict with another module.
396
  struct UnresolvedConflict {
397
    /// The (unresolved) module id.
398
    ModuleId Id;
399
400
    /// The message provided to the user when there is a conflict.
401
    std::string Message;
402
  };
403
404
  /// The list of conflicts for which the module-id has not yet been
405
  /// resolved.
406
  std::vector<UnresolvedConflict> UnresolvedConflicts;
407
408
  /// A conflict between two modules.
409
  struct Conflict {
410
    /// The module that this module conflicts with.
411
    Module *Other;
412
413
    /// The message provided to the user when there is a conflict.
414
    std::string Message;
415
  };
416
417
  /// The list of conflicts.
418
  std::vector<Conflict> Conflicts;
419
420
  /// Construct a new module or submodule.
421
  Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
422
         bool IsFramework, bool IsExplicit, unsigned VisibilityID);
423
424
  ~Module();
425
426
  /// Determine whether this module has been declared unimportable.
427
7.46M
  bool isUnimportable() const { return IsUnimportable; }
428
429
  /// Determine whether this module has been declared unimportable.
430
  ///
431
  /// \param LangOpts The language options used for the current
432
  /// translation unit.
433
  ///
434
  /// \param Target The target options used for the current translation unit.
435
  ///
436
  /// \param Req If this module is unimportable because of a missing
437
  /// requirement, this parameter will be set to one of the requirements that
438
  /// is not met for use of this module.
439
  ///
440
  /// \param ShadowingModule If this module is unimportable because it is
441
  /// shadowed, this parameter will be set to the shadowing module.
442
  bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
443
                      Requirement &Req, Module *&ShadowingModule) const;
444
445
  /// Determine whether this module is available for use within the
446
  /// current translation unit.
447
1.72M
  bool isAvailable() const { return IsAvailable; }
448
449
  /// Determine whether this module is available for use within the
450
  /// current translation unit.
451
  ///
452
  /// \param LangOpts The language options used for the current
453
  /// translation unit.
454
  ///
455
  /// \param Target The target options used for the current translation unit.
456
  ///
457
  /// \param Req If this module is unavailable because of a missing requirement,
458
  /// this parameter will be set to one of the requirements that is not met for
459
  /// use of this module.
460
  ///
461
  /// \param MissingHeader If this module is unavailable because of a missing
462
  /// header, this parameter will be set to one of the missing headers.
463
  ///
464
  /// \param ShadowingModule If this module is unavailable because it is
465
  /// shadowed, this parameter will be set to the shadowing module.
466
  bool isAvailable(const LangOptions &LangOpts,
467
                   const TargetInfo &Target,
468
                   Requirement &Req,
469
                   UnresolvedHeaderDirective &MissingHeader,
470
                   Module *&ShadowingModule) const;
471
472
  /// Determine whether this module is a submodule.
473
0
  bool isSubModule() const { return Parent != nullptr; }
474
475
  /// Check if this module is a (possibly transitive) submodule of \p Other.
476
  ///
477
  /// The 'A is a submodule of B' relation is a partial order based on the
478
  /// the parent-child relationship between individual modules.
479
  ///
480
  /// Returns \c false if \p Other is \c nullptr.
481
  bool isSubModuleOf(const Module *Other) const;
482
483
  /// Determine whether this module is a part of a framework,
484
  /// either because it is a framework module or because it is a submodule
485
  /// of a framework module.
486
2.96M
  bool isPartOfFramework() const {
487
11.6M
    for (const Module *Mod = this; Mod; 
Mod = Mod->Parent8.64M
)
488
8.73M
      if (Mod->IsFramework)
489
82.0k
        return true;
490
491
2.88M
    return false;
492
2.96M
  }
493
494
  /// Determine whether this module is a subframework of another
495
  /// framework.
496
10.9k
  bool isSubFramework() const {
497
10.9k
    return IsFramework && Parent && 
Parent->isPartOfFramework()3.55k
;
498
10.9k
  }
499
500
  /// Set the parent of this module. This should only be used if the parent
501
  /// could not be set during module creation.
502
79
  void setParent(Module *M) {
503
79
    assert(!Parent);
504
0
    Parent = M;
505
79
    Parent->SubModuleIndex[Name] = Parent->SubModules.size();
506
79
    Parent->SubModules.push_back(this);
507
79
  }
508
509
  /// Retrieve the full name of this module, including the path from
510
  /// its top-level module.
511
  /// \param AllowStringLiterals If \c true, components that might not be
512
  ///        lexically valid as identifiers will be emitted as string literals.
513
  std::string getFullModuleName(bool AllowStringLiterals = false) const;
514
515
  /// Whether the full name of this module is equal to joining
516
  /// \p nameParts with "."s.
517
  ///
518
  /// This is more efficient than getFullModuleName().
519
  bool fullModuleNameIs(ArrayRef<StringRef> nameParts) const;
520
521
  /// Retrieve the top-level module for this (sub)module, which may
522
  /// be this module.
523
5.75M
  Module *getTopLevelModule() {
524
5.75M
    return const_cast<Module *>(
525
5.75M
             const_cast<const Module *>(this)->getTopLevelModule());
526
5.75M
  }
527
528
  /// Retrieve the top-level module for this (sub)module, which may
529
  /// be this module.
530
  const Module *getTopLevelModule() const;
531
532
  /// Retrieve the name of the top-level module.
533
189k
  StringRef getTopLevelModuleName() const {
534
189k
    return getTopLevelModule()->Name;
535
189k
  }
536
537
  /// The serialized AST file for this module, if one was created.
538
695k
  OptionalFileEntryRefDegradesToFileEntryPtr getASTFile() const {
539
695k
    return getTopLevelModule()->ASTFile;
540
695k
  }
541
542
  /// Set the serialized AST file for the top-level module of this module.
543
14.1k
  void setASTFile(Optional<FileEntryRef> File) {
544
14.1k
    assert((!File || !getASTFile() || getASTFile() == File) &&
545
14.1k
           "file path changed");
546
0
    getTopLevelModule()->ASTFile = File;
547
14.1k
  }
548
549
  /// Retrieve the directory for which this module serves as the
550
  /// umbrella.
551
  DirectoryName getUmbrellaDir() const;
552
553
  /// Retrieve the header that serves as the umbrella header for this
554
  /// module.
555
152k
  Header getUmbrellaHeader() const {
556
152k
    if (auto *FE = Umbrella.dyn_cast<const FileEntry *>())
557
15.6k
      return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
558
15.6k
                    FE};
559
137k
    return Header{};
560
152k
  }
561
562
  /// Determine whether this module has an umbrella directory that is
563
  /// not based on an umbrella header.
564
0
  bool hasUmbrellaDir() const {
565
0
    return Umbrella && Umbrella.is<const DirectoryEntry *>();
566
0
  }
567
568
  /// Add a top-level header associated with this module.
569
  void addTopHeader(const FileEntry *File);
570
571
  /// Add a top-level header filename associated with this module.
572
1.59M
  void addTopHeaderFilename(StringRef Filename) {
573
1.59M
    TopHeaderNames.push_back(std::string(Filename));
574
1.59M
  }
575
576
  /// The top-level headers associated with this module.
577
  ArrayRef<const FileEntry *> getTopHeaders(FileManager &FileMgr);
578
579
  /// Determine whether this module has declared its intention to
580
  /// directly use another module.
581
  bool directlyUses(const Module *Requested) const;
582
583
  /// Add the given feature requirement to the list of features
584
  /// required by this module.
585
  ///
586
  /// \param Feature The feature that is required by this module (and
587
  /// its submodules).
588
  ///
589
  /// \param RequiredState The required state of this feature: \c true
590
  /// if it must be present, \c false if it must be absent.
591
  ///
592
  /// \param LangOpts The set of language options that will be used to
593
  /// evaluate the availability of this feature.
594
  ///
595
  /// \param Target The target options that will be used to evaluate the
596
  /// availability of this feature.
597
  void addRequirement(StringRef Feature, bool RequiredState,
598
                      const LangOptions &LangOpts,
599
                      const TargetInfo &Target);
600
601
  /// Mark this module and all of its submodules as unavailable.
602
  void markUnavailable(bool Unimportable);
603
604
  /// Find the submodule with the given name.
605
  ///
606
  /// \returns The submodule if found, or NULL otherwise.
607
  Module *findSubmodule(StringRef Name) const;
608
  Module *findOrInferSubmodule(StringRef Name);
609
610
  /// Determine whether the specified module would be visible to
611
  /// a lookup at the end of this module.
612
  ///
613
  /// FIXME: This may return incorrect results for (submodules of) the
614
  /// module currently being built, if it's queried before we see all
615
  /// of its imports.
616
59.0k
  bool isModuleVisible(const Module *M) const {
617
59.0k
    if (VisibleModulesCache.empty())
618
214
      buildVisibleModulesCache();
619
59.0k
    return VisibleModulesCache.count(M);
620
59.0k
  }
621
622
6.18M
  unsigned getVisibilityID() const { return VisibilityID; }
623
624
  using submodule_iterator = std::vector<Module *>::iterator;
625
  using submodule_const_iterator = std::vector<Module *>::const_iterator;
626
627
2.28M
  submodule_iterator submodule_begin() { return SubModules.begin(); }
628
24.3k
  submodule_const_iterator submodule_begin() const {return SubModules.begin();}
629
2.28M
  submodule_iterator submodule_end()   { return SubModules.end(); }
630
24.3k
  submodule_const_iterator submodule_end() const { return SubModules.end(); }
631
632
445k
  llvm::iterator_range<submodule_iterator> submodules() {
633
445k
    return llvm::make_range(submodule_begin(), submodule_end());
634
445k
  }
635
24.0k
  llvm::iterator_range<submodule_const_iterator> submodules() const {
636
24.0k
    return llvm::make_range(submodule_begin(), submodule_end());
637
24.0k
  }
638
639
  /// Appends this module's list of exported modules to \p Exported.
640
  ///
641
  /// This provides a subset of immediately imported modules (the ones that are
642
  /// directly exported), not the complete set of exported modules.
643
  void getExportedModules(SmallVectorImpl<Module *> &Exported) const;
644
645
1.88k
  static StringRef getModuleInputBufferName() {
646
1.88k
    return "<module-includes>";
647
1.88k
  }
648
649
  /// Print the module map for this module to the given stream.
650
  void print(raw_ostream &OS, unsigned Indent = 0, bool Dump = false) const;
651
652
  /// Dump the contents of this module to the given output stream.
653
  void dump() const;
654
655
private:
656
  void buildVisibleModulesCache() const;
657
};
658
659
/// A set of visible modules.
660
class VisibleModuleSet {
661
public:
662
254k
  VisibleModuleSet() = default;
663
  VisibleModuleSet(VisibleModuleSet &&O)
664
81.1k
      : ImportLocs(std::move(O.ImportLocs)), Generation(O.Generation ? 1 : 0) {
665
81.1k
    O.ImportLocs.clear();
666
81.1k
    ++O.Generation;
667
81.1k
  }
668
669
  /// Move from another visible modules set. Guaranteed to leave the source
670
  /// empty and bump the generation on both.
671
624
  VisibleModuleSet &operator=(VisibleModuleSet &&O) {
672
624
    ImportLocs = std::move(O.ImportLocs);
673
624
    O.ImportLocs.clear();
674
624
    ++O.Generation;
675
624
    ++Generation;
676
624
    return *this;
677
624
  }
678
679
  /// Get the current visibility generation. Incremented each time the
680
  /// set of visible modules changes in any way.
681
15.7M
  unsigned getGeneration() const { return Generation; }
682
683
  /// Determine whether a module is visible.
684
640k
  bool isVisible(const Module *M) const {
685
640k
    return getImportLoc(M).isValid();
686
640k
  }
687
688
  /// Get the location at which the import of a module was triggered.
689
640k
  SourceLocation getImportLoc(const Module *M) const {
690
640k
    return M->getVisibilityID() < ImportLocs.size()
691
640k
               ? 
ImportLocs[M->getVisibilityID()]606k
692
640k
               : 
SourceLocation()33.2k
;
693
640k
  }
694
695
  /// A callback to call when a module is made visible (directly or
696
  /// indirectly) by a call to \ref setVisible.
697
  using VisibleCallback = llvm::function_ref<void(Module *M)>;
698
699
  /// A callback to call when a module conflict is found. \p Path
700
  /// consists of a sequence of modules from the conflicting module to the one
701
  /// made visible, where each was exported by the next.
702
  using ConflictCallback =
703
      llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
704
                         StringRef Message)>;
705
706
  /// Make a specific module visible.
707
  void setVisible(Module *M, SourceLocation Loc,
708
760k
                  VisibleCallback Vis = [](Module *) {},
709
                  ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
710
1
                                           StringRef) {});
711
712
private:
713
  /// Import locations for each visible module. Indexed by the module's
714
  /// VisibilityID.
715
  std::vector<SourceLocation> ImportLocs;
716
717
  /// Visibility generation, bumped every time the visibility state changes.
718
  unsigned Generation = 0;
719
};
720
721
/// Abstracts clang modules and precompiled header files and holds
722
/// everything needed to generate debug info for an imported module
723
/// or PCH.
724
class ASTSourceDescriptor {
725
  StringRef PCHModuleName;
726
  StringRef Path;
727
  StringRef ASTFile;
728
  ASTFileSignature Signature;
729
  Module *ClangModule = nullptr;
730
731
public:
732
10.4k
  ASTSourceDescriptor() = default;
733
  ASTSourceDescriptor(StringRef Name, StringRef Path, StringRef ASTFile,
734
                      ASTFileSignature Signature)
735
      : PCHModuleName(std::move(Name)), Path(std::move(Path)),
736
362
        ASTFile(std::move(ASTFile)), Signature(Signature) {}
737
  ASTSourceDescriptor(Module &M);
738
739
  std::string getModuleName() const;
740
26.2k
  StringRef getPath() const { return Path; }
741
6.07k
  StringRef getASTFile() const { return ASTFile; }
742
1.51k
  ASTFileSignature getSignature() const { return Signature; }
743
612k
  Module *getModuleOrNull() const { return ClangModule; }
744
};
745
746
747
} // namespace clang
748
749
#endif // LLVM_CLANG_BASIC_MODULE_H