1 //===- ModuleMap.h - Describe the layout of modules -------------*- 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 // This file defines the ModuleMap interface, which describes the layout of a 11 // module as it relates to headers. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_LEX_MODULEMAP_H 16 #define LLVM_CLANG_LEX_MODULEMAP_H 17 18 #include "clang/Basic/LangOptions.h" 19 #include "clang/Basic/Module.h" 20 #include "clang/Basic/SourceLocation.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringMap.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/TinyPtrVector.h" 29 #include "llvm/ADT/Twine.h" 30 #include <ctime> 31 #include <memory> 32 #include <string> 33 #include <utility> 34 35 namespace clang { 36 37 class DiagnosticsEngine; 38 class DirectoryEntry; 39 class FileEntry; 40 class FileManager; 41 class HeaderSearch; 42 class SourceManager; 43 44 /// \brief A mechanism to observe the actions of the module map parser as it 45 /// reads module map files. 46 class ModuleMapCallbacks { 47 public: 48 virtual ~ModuleMapCallbacks() = default; 49 50 /// \brief Called when a module map file has been read. 51 /// 52 /// \param FileStart A SourceLocation referring to the start of the file's 53 /// contents. 54 /// \param File The file itself. 55 /// \param IsSystem Whether this is a module map from a system include path. 56 virtual void moduleMapFileRead(SourceLocation FileStart, 57 const FileEntry &File, bool IsSystem) {} 58 59 /// \brief Called when a header is added during module map parsing. 60 /// 61 /// \param Filename The header file itself. 62 virtual void moduleMapAddHeader(StringRef Filename) {} 63 64 /// \brief Called when an umbrella header is added during module map parsing. 65 /// 66 /// \param FileMgr FileManager instance 67 /// \param Header The umbrella header to collect. 68 virtual void moduleMapAddUmbrellaHeader(FileManager *FileMgr, 69 const FileEntry *Header) {} 70 }; 71 72 class ModuleMap { 73 SourceManager &SourceMgr; 74 DiagnosticsEngine &Diags; 75 const LangOptions &LangOpts; 76 const TargetInfo *Target; 77 HeaderSearch &HeaderInfo; 78 79 llvm::SmallVector<std::unique_ptr<ModuleMapCallbacks>, 1> Callbacks; 80 81 /// \brief The directory used for Clang-supplied, builtin include headers, 82 /// such as "stdint.h". 83 const DirectoryEntry *BuiltinIncludeDir = nullptr; 84 85 /// \brief Language options used to parse the module map itself. 86 /// 87 /// These are always simple C language options. 88 LangOptions MMapLangOpts; 89 90 /// The module that the main source file is associated with (the module 91 /// named LangOpts::CurrentModule, if we've loaded it). 92 Module *SourceModule = nullptr; 93 94 /// The global module for the current TU, if we still own it. (Ownership is 95 /// transferred if/when we create an enclosing module. 96 std::unique_ptr<Module> PendingGlobalModule; 97 98 /// \brief The top-level modules that are known. 99 llvm::StringMap<Module *> Modules; 100 101 /// \brief The number of modules we have created in total. 102 unsigned NumCreatedModules = 0; 103 104 public: 105 /// \brief Flags describing the role of a module header. 106 enum ModuleHeaderRole { 107 /// \brief This header is normally included in the module. 108 NormalHeader = 0x0, 109 110 /// \brief This header is included but private. 111 PrivateHeader = 0x1, 112 113 /// \brief This header is part of the module (for layering purposes) but 114 /// should be textually included. 115 TextualHeader = 0x2, 116 117 // Caution: Adding an enumerator needs other changes. 118 // Adjust the number of bits for KnownHeader::Storage. 119 // Adjust the bitfield HeaderFileInfo::HeaderRole size. 120 // Adjust the HeaderFileInfoTrait::ReadData streaming. 121 // Adjust the HeaderFileInfoTrait::EmitData streaming. 122 // Adjust ModuleMap::addHeader. 123 }; 124 125 /// Convert a header kind to a role. Requires Kind to not be HK_Excluded. 126 static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind); 127 128 /// Convert a header role to a kind. 129 static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role); 130 131 /// \brief A header that is known to reside within a given module, 132 /// whether it was included or excluded. 133 class KnownHeader { 134 llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage; 135 136 public: 137 KnownHeader() : Storage(nullptr, NormalHeader) {} 138 KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {} 139 140 friend bool operator==(const KnownHeader &A, const KnownHeader &B) { 141 return A.Storage == B.Storage; 142 } 143 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) { 144 return A.Storage != B.Storage; 145 } 146 147 /// \brief Retrieve the module the header is stored in. 148 Module *getModule() const { return Storage.getPointer(); } 149 150 /// \brief The role of this header within the module. 151 ModuleHeaderRole getRole() const { return Storage.getInt(); } 152 153 /// \brief Whether this header is available in the module. 154 bool isAvailable() const { 155 return getModule()->isAvailable(); 156 } 157 158 /// \brief Whether this header is accessible from the specified module. 159 bool isAccessibleFrom(Module *M) const { 160 return !(getRole() & PrivateHeader) || 161 (M && M->getTopLevelModule() == getModule()->getTopLevelModule()); 162 } 163 164 // \brief Whether this known header is valid (i.e., it has an 165 // associated module). 166 explicit operator bool() const { 167 return Storage.getPointer() != nullptr; 168 } 169 }; 170 171 using AdditionalModMapsSet = llvm::SmallPtrSet<const FileEntry *, 1>; 172 173 private: 174 friend class ModuleMapParser; 175 176 using HeadersMap = 177 llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1>>; 178 179 /// \brief Mapping from each header to the module that owns the contents of 180 /// that header. 181 HeadersMap Headers; 182 183 /// Map from file sizes to modules with lazy header directives of that size. 184 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize; 185 186 /// Map from mtimes to modules with lazy header directives with those mtimes. 187 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>> 188 LazyHeadersByModTime; 189 190 /// \brief Mapping from directories with umbrella headers to the module 191 /// that is generated from the umbrella header. 192 /// 193 /// This mapping is used to map headers that haven't explicitly been named 194 /// in the module map over to the module that includes them via its umbrella 195 /// header. 196 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs; 197 198 /// \brief The set of attributes that can be attached to a module. 199 struct Attributes { 200 /// \brief Whether this is a system module. 201 unsigned IsSystem : 1; 202 203 /// \brief Whether this is an extern "C" module. 204 unsigned IsExternC : 1; 205 206 /// \brief Whether this is an exhaustive set of configuration macros. 207 unsigned IsExhaustive : 1; 208 209 /// \brief Whether files in this module can only include non-modular headers 210 /// and headers from used modules. 211 unsigned NoUndeclaredIncludes : 1; 212 213 Attributes() 214 : IsSystem(false), IsExternC(false), IsExhaustive(false), 215 NoUndeclaredIncludes(false) {} 216 }; 217 218 /// \brief A directory for which framework modules can be inferred. 219 struct InferredDirectory { 220 /// \brief Whether to infer modules from this directory. 221 unsigned InferModules : 1; 222 223 /// \brief The attributes to use for inferred modules. 224 Attributes Attrs; 225 226 /// \brief If \c InferModules is non-zero, the module map file that allowed 227 /// inferred modules. Otherwise, nullptr. 228 const FileEntry *ModuleMapFile; 229 230 /// \brief The names of modules that cannot be inferred within this 231 /// directory. 232 SmallVector<std::string, 2> ExcludedModules; 233 234 InferredDirectory() : InferModules(false) {} 235 }; 236 237 /// \brief A mapping from directories to information about inferring 238 /// framework modules from within those directories. 239 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories; 240 241 /// A mapping from an inferred module to the module map that allowed the 242 /// inference. 243 llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy; 244 245 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps; 246 247 /// \brief Describes whether we haved parsed a particular file as a module 248 /// map. 249 llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap; 250 251 /// \brief Resolve the given export declaration into an actual export 252 /// declaration. 253 /// 254 /// \param Mod The module in which we're resolving the export declaration. 255 /// 256 /// \param Unresolved The export declaration to resolve. 257 /// 258 /// \param Complain Whether this routine should complain about unresolvable 259 /// exports. 260 /// 261 /// \returns The resolved export declaration, which will have a NULL pointer 262 /// if the export could not be resolved. 263 Module::ExportDecl 264 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved, 265 bool Complain) const; 266 267 /// \brief Resolve the given module id to an actual module. 268 /// 269 /// \param Id The module-id to resolve. 270 /// 271 /// \param Mod The module in which we're resolving the module-id. 272 /// 273 /// \param Complain Whether this routine should complain about unresolvable 274 /// module-ids. 275 /// 276 /// \returns The resolved module, or null if the module-id could not be 277 /// resolved. 278 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const; 279 280 /// Add an unresolved header to a module. 281 void addUnresolvedHeader(Module *Mod, 282 Module::UnresolvedHeaderDirective Header); 283 284 /// Look up the given header directive to find an actual header file. 285 /// 286 /// \param M The module in which we're resolving the header directive. 287 /// \param Header The header directive to resolve. 288 /// \param RelativePathName Filled in with the relative path name from the 289 /// module to the resolved header. 290 /// \return The resolved file, if any. 291 const FileEntry *findHeader(Module *M, 292 const Module::UnresolvedHeaderDirective &Header, 293 SmallVectorImpl<char> &RelativePathName); 294 295 /// Resolve the given header directive. 296 void resolveHeader(Module *M, 297 const Module::UnresolvedHeaderDirective &Header); 298 299 /// Attempt to resolve the specified header directive as naming a builtin 300 /// header. 301 /// \return \c true if a corresponding builtin header was found. 302 bool resolveAsBuiltinHeader(Module *M, 303 const Module::UnresolvedHeaderDirective &Header); 304 305 /// \brief Looks up the modules that \p File corresponds to. 306 /// 307 /// If \p File represents a builtin header within Clang's builtin include 308 /// directory, this also loads all of the module maps to see if it will get 309 /// associated with a specific module (e.g. in /usr/include). 310 HeadersMap::iterator findKnownHeader(const FileEntry *File); 311 312 /// \brief Searches for a module whose umbrella directory contains \p File. 313 /// 314 /// \param File The header to search for. 315 /// 316 /// \param IntermediateDirs On success, contains the set of directories 317 /// searched before finding \p File. 318 KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File, 319 SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs); 320 321 /// \brief Given that \p File is not in the Headers map, look it up within 322 /// umbrella directories and find or create a module for it. 323 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File); 324 325 /// \brief A convenience method to determine if \p File is (possibly nested) 326 /// in an umbrella directory. 327 bool isHeaderInUmbrellaDirs(const FileEntry *File) { 328 SmallVector<const DirectoryEntry *, 2> IntermediateDirs; 329 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs)); 330 } 331 332 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir, 333 Attributes Attrs, Module *Parent); 334 335 public: 336 /// \brief Construct a new module map. 337 /// 338 /// \param SourceMgr The source manager used to find module files and headers. 339 /// This source manager should be shared with the header-search mechanism, 340 /// since they will refer to the same headers. 341 /// 342 /// \param Diags A diagnostic engine used for diagnostics. 343 /// 344 /// \param LangOpts Language options for this translation unit. 345 /// 346 /// \param Target The target for this translation unit. 347 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, 348 const LangOptions &LangOpts, const TargetInfo *Target, 349 HeaderSearch &HeaderInfo); 350 351 /// \brief Destroy the module map. 352 ~ModuleMap(); 353 354 /// \brief Set the target information. 355 void setTarget(const TargetInfo &Target); 356 357 /// \brief Set the directory that contains Clang-supplied include 358 /// files, such as our stdarg.h or tgmath.h. 359 void setBuiltinIncludeDir(const DirectoryEntry *Dir) { 360 BuiltinIncludeDir = Dir; 361 } 362 363 /// \brief Get the directory that contains Clang-supplied include files. 364 const DirectoryEntry *getBuiltinDir() const { 365 return BuiltinIncludeDir; 366 } 367 368 /// \brief Is this a compiler builtin header? 369 static bool isBuiltinHeader(StringRef FileName); 370 371 /// \brief Add a module map callback. 372 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) { 373 Callbacks.push_back(std::move(Callback)); 374 } 375 376 /// \brief Retrieve the module that owns the given header file, if any. 377 /// 378 /// \param File The header file that is likely to be included. 379 /// 380 /// \param AllowTextual If \c true and \p File is a textual header, return 381 /// its owning module. Otherwise, no KnownHeader will be returned if the 382 /// file is only known as a textual header. 383 /// 384 /// \returns The module KnownHeader, which provides the module that owns the 385 /// given header file. The KnownHeader is default constructed to indicate 386 /// that no module owns this header file. 387 KnownHeader findModuleForHeader(const FileEntry *File, 388 bool AllowTextual = false); 389 390 /// \brief Retrieve all the modules that contain the given header file. This 391 /// may not include umbrella modules, nor information from external sources, 392 /// if they have not yet been inferred / loaded. 393 /// 394 /// Typically, \ref findModuleForHeader should be used instead, as it picks 395 /// the preferred module for the header. 396 ArrayRef<KnownHeader> findAllModulesForHeader(const FileEntry *File) const; 397 398 /// Resolve all lazy header directives for the specified file. 399 /// 400 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This 401 /// is effectively internal, but is exposed so HeaderSearch can call it. 402 void resolveHeaderDirectives(const FileEntry *File) const; 403 404 /// Resolve all lazy header directives for the specified module. 405 void resolveHeaderDirectives(Module *Mod) const; 406 407 /// \brief Reports errors if a module must not include a specific file. 408 /// 409 /// \param RequestingModule The module including a file. 410 /// 411 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in 412 /// the interface of RequestingModule, \c false if it's in the 413 /// implementation of RequestingModule. Value is ignored and 414 /// meaningless if RequestingModule is nullptr. 415 /// 416 /// \param FilenameLoc The location of the inclusion's filename. 417 /// 418 /// \param Filename The included filename as written. 419 /// 420 /// \param File The included file. 421 void diagnoseHeaderInclusion(Module *RequestingModule, 422 bool RequestingModuleIsModuleInterface, 423 SourceLocation FilenameLoc, StringRef Filename, 424 const FileEntry *File); 425 426 /// \brief Determine whether the given header is part of a module 427 /// marked 'unavailable'. 428 bool isHeaderInUnavailableModule(const FileEntry *Header) const; 429 430 /// \brief Determine whether the given header is unavailable as part 431 /// of the specified module. 432 bool isHeaderUnavailableInModule(const FileEntry *Header, 433 const Module *RequestingModule) const; 434 435 /// \brief Retrieve a module with the given name. 436 /// 437 /// \param Name The name of the module to look up. 438 /// 439 /// \returns The named module, if known; otherwise, returns null. 440 Module *findModule(StringRef Name) const; 441 442 /// \brief Retrieve a module with the given name using lexical name lookup, 443 /// starting at the given context. 444 /// 445 /// \param Name The name of the module to look up. 446 /// 447 /// \param Context The module context, from which we will perform lexical 448 /// name lookup. 449 /// 450 /// \returns The named module, if known; otherwise, returns null. 451 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const; 452 453 /// \brief Retrieve a module with the given name within the given context, 454 /// using direct (qualified) name lookup. 455 /// 456 /// \param Name The name of the module to look up. 457 /// 458 /// \param Context The module for which we will look for a submodule. If 459 /// null, we will look for a top-level module. 460 /// 461 /// \returns The named submodule, if known; otherwose, returns null. 462 Module *lookupModuleQualified(StringRef Name, Module *Context) const; 463 464 /// \brief Find a new module or submodule, or create it if it does not already 465 /// exist. 466 /// 467 /// \param Name The name of the module to find or create. 468 /// 469 /// \param Parent The module that will act as the parent of this submodule, 470 /// or nullptr to indicate that this is a top-level module. 471 /// 472 /// \param IsFramework Whether this is a framework module. 473 /// 474 /// \param IsExplicit Whether this is an explicit submodule. 475 /// 476 /// \returns The found or newly-created module, along with a boolean value 477 /// that will be true if the module is newly-created. 478 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent, 479 bool IsFramework, 480 bool IsExplicit); 481 482 /// \brief Create a 'global module' for a C++ Modules TS module interface 483 /// unit. 484 /// 485 /// We model the global module as a submodule of the module interface unit. 486 /// Unfortunately, we can't create the module interface unit's Module until 487 /// later, because we don't know what it will be called. 488 Module *createGlobalModuleForInterfaceUnit(SourceLocation Loc); 489 490 /// \brief Create a new module for a C++ Modules TS module interface unit. 491 /// The module must not already exist, and will be configured for the current 492 /// compilation. 493 /// 494 /// Note that this also sets the current module to the newly-created module. 495 /// 496 /// \returns The newly-created module. 497 Module *createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name, 498 Module *GlobalModule); 499 500 /// \brief Infer the contents of a framework module map from the given 501 /// framework directory. 502 Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir, 503 bool IsSystem, Module *Parent); 504 505 /// \brief Retrieve the module map file containing the definition of the given 506 /// module. 507 /// 508 /// \param Module The module whose module map file will be returned, if known. 509 /// 510 /// \returns The file entry for the module map file containing the given 511 /// module, or nullptr if the module definition was inferred. 512 const FileEntry *getContainingModuleMapFile(const Module *Module) const; 513 514 /// \brief Get the module map file that (along with the module name) uniquely 515 /// identifies this module. 516 /// 517 /// The particular module that \c Name refers to may depend on how the module 518 /// was found in header search. However, the combination of \c Name and 519 /// this module map will be globally unique for top-level modules. In the case 520 /// of inferred modules, returns the module map that allowed the inference 521 /// (e.g. contained 'module *'). Otherwise, returns 522 /// getContainingModuleMapFile(). 523 const FileEntry *getModuleMapFileForUniquing(const Module *M) const; 524 525 void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap); 526 527 /// \brief Get any module map files other than getModuleMapFileForUniquing(M) 528 /// that define submodules of a top-level module \p M. This is cheaper than 529 /// getting the module map file for each submodule individually, since the 530 /// expected number of results is very small. 531 AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) { 532 auto I = AdditionalModMaps.find(M); 533 if (I == AdditionalModMaps.end()) 534 return nullptr; 535 return &I->second; 536 } 537 538 void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) { 539 AdditionalModMaps[M].insert(ModuleMap); 540 } 541 542 /// \brief Resolve all of the unresolved exports in the given module. 543 /// 544 /// \param Mod The module whose exports should be resolved. 545 /// 546 /// \param Complain Whether to emit diagnostics for failures. 547 /// 548 /// \returns true if any errors were encountered while resolving exports, 549 /// false otherwise. 550 bool resolveExports(Module *Mod, bool Complain); 551 552 /// \brief Resolve all of the unresolved uses in the given module. 553 /// 554 /// \param Mod The module whose uses should be resolved. 555 /// 556 /// \param Complain Whether to emit diagnostics for failures. 557 /// 558 /// \returns true if any errors were encountered while resolving uses, 559 /// false otherwise. 560 bool resolveUses(Module *Mod, bool Complain); 561 562 /// \brief Resolve all of the unresolved conflicts in the given module. 563 /// 564 /// \param Mod The module whose conflicts should be resolved. 565 /// 566 /// \param Complain Whether to emit diagnostics for failures. 567 /// 568 /// \returns true if any errors were encountered while resolving conflicts, 569 /// false otherwise. 570 bool resolveConflicts(Module *Mod, bool Complain); 571 572 /// \brief Sets the umbrella header of the given module to the given 573 /// header. 574 void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader, 575 Twine NameAsWritten); 576 577 /// \brief Sets the umbrella directory of the given module to the given 578 /// directory. 579 void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir, 580 Twine NameAsWritten); 581 582 /// \brief Adds this header to the given module. 583 /// \param Role The role of the header wrt the module. 584 void addHeader(Module *Mod, Module::Header Header, 585 ModuleHeaderRole Role, bool Imported = false); 586 587 /// \brief Marks this header as being excluded from the given module. 588 void excludeHeader(Module *Mod, Module::Header Header); 589 590 /// \brief Parse the given module map file, and record any modules we 591 /// encounter. 592 /// 593 /// \param File The file to be parsed. 594 /// 595 /// \param IsSystem Whether this module map file is in a system header 596 /// directory, and therefore should be considered a system module. 597 /// 598 /// \param HomeDir The directory in which relative paths within this module 599 /// map file will be resolved. 600 /// 601 /// \param ID The FileID of the file to process, if we've already entered it. 602 /// 603 /// \param Offset [inout] On input the offset at which to start parsing. On 604 /// output, the offset at which the module map terminated. 605 /// 606 /// \param ExternModuleLoc The location of the "extern module" declaration 607 /// that caused us to load this module map file, if any. 608 /// 609 /// \returns true if an error occurred, false otherwise. 610 bool parseModuleMapFile(const FileEntry *File, bool IsSystem, 611 const DirectoryEntry *HomeDir, FileID ID = FileID(), 612 unsigned *Offset = nullptr, 613 SourceLocation ExternModuleLoc = SourceLocation()); 614 615 /// \brief Dump the contents of the module map, for debugging purposes. 616 void dump(); 617 618 using module_iterator = llvm::StringMap<Module *>::const_iterator; 619 620 module_iterator module_begin() const { return Modules.begin(); } 621 module_iterator module_end() const { return Modules.end(); } 622 }; 623 624 } // namespace clang 625 626 #endif // LLVM_CLANG_LEX_MODULEMAP_H 627