[clang] [clang] Be const-correct with all uses of `Module *`. (PR #93493)

David Stone via cfe-commits cfe-commits at lists.llvm.org
Mon May 27 14:50:41 PDT 2024


https://github.com/davidstone created https://github.com/llvm/llvm-project/pull/93493

None

>From b1538fc7660f7ccf67625b10d390301eaf4fdd35 Mon Sep 17 00:00:00 2001
From: David Stone <davidfromonline at gmail.com>
Date: Mon, 27 May 2024 15:45:59 -0600
Subject: [PATCH] [clang] Be const-correct with all uses of `Module *`.

---
 .../include/clang/APINotes/APINotesManager.h  |  2 +-
 clang/include/clang/AST/ASTContext.h          |  8 +-
 clang/include/clang/AST/ASTMutationListener.h |  2 +-
 clang/include/clang/AST/DeclBase.h            |  6 +-
 clang/include/clang/Basic/Module.h            | 44 +++++------
 clang/include/clang/Frontend/FrontendAction.h |  2 +-
 .../clang/Frontend/MultiplexConsumer.h        |  2 +-
 .../clang/Lex/ExternalPreprocessorSource.h    |  2 +-
 clang/include/clang/Lex/HeaderSearch.h        | 10 +--
 clang/include/clang/Lex/MacroInfo.h           | 12 +--
 clang/include/clang/Lex/ModuleMap.h           | 34 +++++----
 clang/include/clang/Lex/PPCallbacks.h         | 12 +--
 clang/include/clang/Lex/Preprocessor.h        | 27 +++----
 clang/include/clang/Sema/Sema.h               | 46 +++++++-----
 .../ASTDeserializationListener.h              |  2 +-
 clang/include/clang/Serialization/ASTReader.h |  4 +-
 clang/include/clang/Serialization/ASTWriter.h | 14 ++--
 clang/lib/APINotes/APINotesManager.cpp        |  2 +-
 clang/lib/AST/ASTContext.cpp                  |  8 +-
 clang/lib/AST/Decl.cpp                        |  6 +-
 clang/lib/AST/DeclBase.cpp                    |  2 +-
 clang/lib/AST/ItaniumMangle.cpp               |  2 +-
 clang/lib/AST/ODRDiagsEmitter.cpp             |  2 +-
 clang/lib/AST/TextNodeDumper.cpp              |  4 +-
 clang/lib/Basic/Module.cpp                    | 37 +++++-----
 clang/lib/CodeGen/CGDebugInfo.cpp             |  4 +-
 clang/lib/CodeGen/CGDeclCXX.cpp               | 14 ++--
 clang/lib/CodeGen/CodeGenModule.cpp           | 31 ++++----
 clang/lib/CodeGen/CodeGenModule.h             |  8 +-
 clang/lib/Frontend/CompilerInstance.cpp       | 25 ++++---
 clang/lib/Frontend/FrontendAction.cpp         |  4 +-
 clang/lib/Frontend/FrontendActions.cpp        |  6 +-
 clang/lib/Frontend/MultiplexConsumer.cpp      |  6 +-
 .../lib/Frontend/PrintPreprocessedOutput.cpp  |  7 +-
 .../Frontend/Rewrite/InclusionRewriter.cpp    |  3 +-
 clang/lib/Lex/HeaderSearch.cpp                | 15 ++--
 clang/lib/Lex/MacroInfo.cpp                   |  2 +-
 clang/lib/Lex/ModuleMap.cpp                   | 73 ++++++++++---------
 clang/lib/Lex/PPDirectives.cpp                |  8 +-
 clang/lib/Lex/PPLexerChange.cpp               |  2 +-
 clang/lib/Lex/PPMacroExpansion.cpp            |  4 +-
 clang/lib/Lex/Pragma.cpp                      |  6 +-
 clang/lib/Lex/Preprocessor.cpp                |  7 +-
 clang/lib/Sema/Sema.cpp                       |  4 +-
 clang/lib/Sema/SemaCodeComplete.cpp           |  4 +-
 clang/lib/Sema/SemaDecl.cpp                   | 10 +--
 clang/lib/Sema/SemaDeclCXX.cpp                |  4 +-
 clang/lib/Sema/SemaLookup.cpp                 | 53 +++++++-------
 clang/lib/Sema/SemaModule.cpp                 | 39 +++++-----
 clang/lib/Sema/SemaOverload.cpp               |  4 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp    |  2 +-
 clang/lib/Serialization/ASTReader.cpp         | 31 ++++----
 clang/lib/Serialization/ASTReaderDecl.cpp     |  2 +-
 clang/lib/Serialization/ASTWriter.cpp         | 20 ++---
 clang/lib/Serialization/ASTWriterDecl.cpp     |  2 +-
 .../DependencyScanning/ModuleDepCollector.cpp |  2 +-
 clang/tools/libclang/CIndex.cpp               | 12 +--
 clang/tools/libclang/CXIndexDataConsumer.cpp  |  2 +-
 clang/unittests/Sema/SemaNoloadLookupTest.cpp |  2 +-
 59 files changed, 361 insertions(+), 349 deletions(-)

diff --git a/clang/include/clang/APINotes/APINotesManager.h b/clang/include/clang/APINotes/APINotesManager.h
index 18375c9e51a17..b559c24b322f2 100644
--- a/clang/include/clang/APINotes/APINotesManager.h
+++ b/clang/include/clang/APINotes/APINotesManager.h
@@ -145,7 +145,7 @@ class APINotesManager {
   ///
   /// \returns a vector of FileEntry where APINotes files are.
   llvm::SmallVector<FileEntryRef, 2>
-  getCurrentModuleAPINotes(Module *M, bool LookInModule,
+  getCurrentModuleAPINotes(const Module *M, bool LookInModule,
                            ArrayRef<std::string> SearchPaths);
 
   /// Load Compiled API notes for current module.
diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index a1d1d1c51cd41..70d131c12e073 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -462,7 +462,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
 
     void resolve(ASTContext &Ctx);
   };
-  llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
+  llvm::DenseMap<const Module *, PerModuleInitializers *> ModuleInitializers;
 
   /// This is the top-level (C++20) Named module we are building.
   Module *CurrentCXXNamedModule = nullptr;
@@ -1060,12 +1060,12 @@ class ASTContext : public RefCountedBase<ASTContext> {
   /// for a module. This will typically be a global variable (with internal
   /// linkage) that runs module initializers, such as the iostream initializer,
   /// or an ImportDecl nominating another module that has initializers.
-  void addModuleInitializer(Module *M, Decl *Init);
+  void addModuleInitializer(const Module *M, Decl *Init);
 
-  void addLazyModuleInitializers(Module *M, ArrayRef<GlobalDeclID> IDs);
+  void addLazyModuleInitializers(const Module *M, ArrayRef<GlobalDeclID> IDs);
 
   /// Get the initializations to perform when importing a module, if any.
-  ArrayRef<Decl*> getModuleInitializers(Module *M);
+  ArrayRef<Decl *> getModuleInitializers(const Module *M);
 
   /// Set the (C++20) module we are building.
   void setCurrentNamedModule(Module *M);
diff --git a/clang/include/clang/AST/ASTMutationListener.h b/clang/include/clang/AST/ASTMutationListener.h
index 2c4ec2ce67f36..fc476f531815c 100644
--- a/clang/include/clang/AST/ASTMutationListener.h
+++ b/clang/include/clang/AST/ASTMutationListener.h
@@ -139,7 +139,7 @@ class ASTMutationListener {
   /// \param D The definition that was previously not visible.
   /// \param M The containing module in which the definition was made visible,
   ///        if any.
-  virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {}
+  virtual void RedefinedHiddenDefinition(const NamedDecl *D, const Module *M) {}
 
   /// An attribute was added to a RecordDecl
   ///
diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index e43e812cd9455..e7dac0c67ff3d 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -817,11 +817,11 @@ class alignas(8) Decl {
            "owned local decl but no local module storage");
     return reinterpret_cast<Module *const *>(this)[-1];
   }
-  void setLocalOwningModule(Module *M) {
+  void setLocalOwningModule(const Module *M) {
     assert(!isFromASTFile() && hasOwningModule() &&
            hasLocalOwningModuleStorage() &&
            "should not have a cached owning module");
-    reinterpret_cast<Module **>(this)[-1] = M;
+    reinterpret_cast<const Module **>(this)[-1] = M;
   }
 
   /// Is this declaration owned by some module?
@@ -839,7 +839,7 @@ class alignas(8) Decl {
   ///
   /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
   /// all declarations in a global module fragment are unowned.
-  Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
+  const Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
 
   /// Determine whether this declaration is definitely visible to name lookup,
   /// independent of whether the owning module is visible.
diff --git a/clang/include/clang/Basic/Module.h b/clang/include/clang/Basic/Module.h
index 2d62d05cd9190..d85e59bd5e9bb 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -296,7 +296,7 @@ class alignas(8) Module {
   SmallVector<Requirement, 2> Requirements;
 
   /// A module with the same name that shadows this module.
-  Module *ShadowingModule = nullptr;
+  const Module *ShadowingModule = nullptr;
 
   /// Whether this module has declared itself unimportable, either because
   /// it's missing a requirement from \p Requirements or because it's been
@@ -403,7 +403,7 @@ class alignas(8) Module {
 
   /// The set of top-level modules that affected the compilation of this module,
   /// but were not imported.
-  llvm::SmallSetVector<Module *, 2> AffectingClangModules;
+  llvm::SmallSetVector<const Module *, 2> AffectingClangModules;
 
   /// Describes an exported module.
   ///
@@ -433,7 +433,7 @@ class alignas(8) Module {
   SmallVector<UnresolvedExportDecl, 2> UnresolvedExports;
 
   /// The directly used modules.
-  SmallVector<Module *, 2> DirectUses;
+  SmallVector<const Module *, 2> DirectUses;
 
   /// The set of use declarations that have yet to be resolved.
   SmallVector<ModuleId, 2> UnresolvedDirectUses;
@@ -487,7 +487,7 @@ class alignas(8) Module {
   /// A conflict between two modules.
   struct Conflict {
     /// The module that this module conflicts with.
-    Module *Other;
+    const Module *Other;
 
     /// The message provided to the user when there is a conflict.
     std::string Message;
@@ -519,7 +519,7 @@ class alignas(8) Module {
   /// \param ShadowingModule If this module is unimportable because it is
   /// shadowed, this parameter will be set to the shadowing module.
   bool isUnimportable(const LangOptions &LangOpts, const TargetInfo &Target,
-                      Requirement &Req, Module *&ShadowingModule) const;
+                      Requirement &Req, const Module *&ShadowingModule) const;
 
   /// Determine whether this module can be built in this compilation.
   bool isForBuilding(const LangOptions &LangOpts) const;
@@ -545,11 +545,9 @@ class alignas(8) Module {
   ///
   /// \param ShadowingModule If this module is unavailable because it is
   /// shadowed, this parameter will be set to the shadowing module.
-  bool isAvailable(const LangOptions &LangOpts,
-                   const TargetInfo &Target,
-                   Requirement &Req,
-                   UnresolvedHeaderDirective &MissingHeader,
-                   Module *&ShadowingModule) const;
+  bool isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
+                   Requirement &Req, UnresolvedHeaderDirective &MissingHeader,
+                   const Module *&ShadowingModule) const;
 
   /// Determine whether this module is a submodule.
   bool isSubModule() const { return Parent != nullptr; }
@@ -755,13 +753,13 @@ class alignas(8) Module {
   /// one.
   ///
   /// \returns The GMF sub-module if found, or NULL otherwise.
-  Module *getGlobalModuleFragment() const;
+  const Module *getGlobalModuleFragment() const;
 
   /// Get the Private Module Fragment (sub-module) for this module, it there is
   /// one.
   ///
   /// \returns The PMF sub-module if found, or NULL otherwise.
-  Module *getPrivateModuleFragment() const;
+  const Module *getPrivateModuleFragment() const;
 
   /// Determine whether the specified module would be visible to
   /// a lookup at the end of this module.
@@ -845,20 +843,22 @@ class VisibleModuleSet {
 
   /// A callback to call when a module is made visible (directly or
   /// indirectly) by a call to \ref setVisible.
-  using VisibleCallback = llvm::function_ref<void(Module *M)>;
+  using VisibleCallback = llvm::function_ref<void(const Module *M)>;
 
   /// A callback to call when a module conflict is found. \p Path
   /// consists of a sequence of modules from the conflicting module to the one
   /// made visible, where each was exported by the next.
   using ConflictCallback =
-      llvm::function_ref<void(ArrayRef<Module *> Path, Module *Conflict,
-                         StringRef Message)>;
+      llvm::function_ref<void(ArrayRef<const Module *> Path,
+                              const Module *Conflict, StringRef Message)>;
 
   /// Make a specific module visible.
-  void setVisible(Module *M, SourceLocation Loc,
-                  VisibleCallback Vis = [](Module *) {},
-                  ConflictCallback Cb = [](ArrayRef<Module *>, Module *,
-                                           StringRef) {});
+  void setVisible(
+      const Module *M, SourceLocation Loc,
+      VisibleCallback Vis = [](const Module *) {},
+      ConflictCallback Cb = [](ArrayRef<const Module *>, const Module *,
+                               StringRef) {});
+
 private:
   /// Import locations for each visible module. Indexed by the module's
   /// VisibilityID.
@@ -876,7 +876,7 @@ class ASTSourceDescriptor {
   StringRef Path;
   StringRef ASTFile;
   ASTFileSignature Signature;
-  Module *ClangModule = nullptr;
+  const Module *ClangModule = nullptr;
 
 public:
   ASTSourceDescriptor() = default;
@@ -884,13 +884,13 @@ class ASTSourceDescriptor {
                       ASTFileSignature Signature)
       : PCHModuleName(std::move(Name)), Path(std::move(Path)),
         ASTFile(std::move(ASTFile)), Signature(Signature) {}
-  ASTSourceDescriptor(Module &M);
+  ASTSourceDescriptor(const Module &M);
 
   std::string getModuleName() const;
   StringRef getPath() const { return Path; }
   StringRef getASTFile() const { return ASTFile; }
   ASTFileSignature getSignature() const { return Signature; }
-  Module *getModuleOrNull() const { return ClangModule; }
+  const Module *getModuleOrNull() const { return ClangModule; }
 };
 
 
diff --git a/clang/include/clang/Frontend/FrontendAction.h b/clang/include/clang/Frontend/FrontendAction.h
index 039f6f247b6d8..6407728e39c6d 100644
--- a/clang/include/clang/Frontend/FrontendAction.h
+++ b/clang/include/clang/Frontend/FrontendAction.h
@@ -158,7 +158,7 @@ class FrontendAction {
     return *CurrentASTUnit;
   }
 
-  Module *getCurrentModule() const;
+  const Module *getCurrentModule() const;
 
   std::unique_ptr<ASTUnit> takeCurrentASTUnit() {
     return std::move(CurrentASTUnit);
diff --git a/clang/include/clang/Frontend/MultiplexConsumer.h b/clang/include/clang/Frontend/MultiplexConsumer.h
index 4ed0d86d3cdfb..bf8b50320e4e1 100644
--- a/clang/include/clang/Frontend/MultiplexConsumer.h
+++ b/clang/include/clang/Frontend/MultiplexConsumer.h
@@ -39,7 +39,7 @@ class MultiplexASTDeserializationListener : public ASTDeserializationListener {
   void SelectorRead(serialization::SelectorID iD, Selector Sel) override;
   void MacroDefinitionRead(serialization::PreprocessedEntityID,
                            MacroDefinitionRecord *MD) override;
-  void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
+  void ModuleRead(serialization::SubmoduleID ID, const Module *Mod) override;
   void ModuleImportRead(serialization::SubmoduleID ID,
                         SourceLocation ImportLoc) override;
 
diff --git a/clang/include/clang/Lex/ExternalPreprocessorSource.h b/clang/include/clang/Lex/ExternalPreprocessorSource.h
index 6775841860373..51f93bc1b1242 100644
--- a/clang/include/clang/Lex/ExternalPreprocessorSource.h
+++ b/clang/include/clang/Lex/ExternalPreprocessorSource.h
@@ -39,7 +39,7 @@ class ExternalPreprocessorSource {
   virtual IdentifierInfo *GetIdentifier(unsigned ID) = 0;
 
   /// Map a module ID to a module.
-  virtual Module *getModule(unsigned ModuleID) = 0;
+  virtual const Module *getModule(unsigned ModuleID) = 0;
 };
 
 }
diff --git a/clang/include/clang/Lex/HeaderSearch.h b/clang/include/clang/Lex/HeaderSearch.h
index 5ac63dddd4d4e..2e81f4f902c75 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -547,8 +547,8 @@ class HeaderSearch {
   /// \param M The module to which `File` belongs (this should usually be the
   /// SuggestedModule returned by LookupFile/LookupSubframeworkHeader)
   bool ShouldEnterIncludeFile(Preprocessor &PP, FileEntryRef File,
-                              bool isImport, bool ModulesEnabled, Module *M,
-                              bool &IsFirstIncludeOfFile);
+                              bool isImport, bool ModulesEnabled,
+                              const Module *M, bool &IsFirstIncludeOfFile);
 
   /// Return whether the specified file is a normal header,
   /// a system header, or a C++ friendly system header.
@@ -622,7 +622,7 @@ class HeaderSearch {
   ///
   /// \returns The name of the module file that corresponds to this module,
   /// or an empty string if this module does not correspond to any module file.
-  std::string getCachedModuleFileName(Module *Module);
+  std::string getCachedModuleFileName(const Module *Module);
 
   /// Retrieve the name of the prebuilt module file that should be used
   /// to load a module with the given name.
@@ -644,7 +644,7 @@ class HeaderSearch {
   ///
   /// \returns The name of the module file that corresponds to this module,
   /// or an empty string if this module does not correspond to any module file.
-  std::string getPrebuiltImplicitModuleFileName(Module *Module);
+  std::string getPrebuiltImplicitModuleFileName(const Module *Module);
 
   /// Retrieve the name of the (to-be-)cached module file that should
   /// be used to load a module with the given name.
@@ -736,7 +736,7 @@ class HeaderSearch {
   /// Collect the set of all known, top-level modules.
   ///
   /// \param Modules Will be filled with the set of known, top-level modules.
-  void collectAllModules(SmallVectorImpl<Module *> &Modules);
+  void collectAllModules(SmallVectorImpl<const Module *> &Modules);
 
   /// Load all known, top-level system modules.
   void loadTopLevelSystemModules();
diff --git a/clang/include/clang/Lex/MacroInfo.h b/clang/include/clang/Lex/MacroInfo.h
index 19a706216d509..162bf9777d227 100644
--- a/clang/include/clang/Lex/MacroInfo.h
+++ b/clang/include/clang/Lex/MacroInfo.h
@@ -521,7 +521,7 @@ class ModuleMacro : public llvm::FoldingSetNode {
   MacroInfo *Macro;
 
   /// The module that exports this macro.
-  Module *OwningModule;
+  const Module *OwningModule;
 
   /// The number of module macros that override this one.
   unsigned NumOverriddenBy = 0;
@@ -529,8 +529,8 @@ class ModuleMacro : public llvm::FoldingSetNode {
   /// The number of modules whose macros are directly overridden by this one.
   unsigned NumOverrides;
 
-  ModuleMacro(Module *OwningModule, const IdentifierInfo *II, MacroInfo *Macro,
-              ArrayRef<ModuleMacro *> Overrides)
+  ModuleMacro(const Module *OwningModule, const IdentifierInfo *II,
+              MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides)
       : II(II), Macro(Macro), OwningModule(OwningModule),
         NumOverrides(Overrides.size()) {
     std::copy(Overrides.begin(), Overrides.end(),
@@ -538,7 +538,7 @@ class ModuleMacro : public llvm::FoldingSetNode {
   }
 
 public:
-  static ModuleMacro *create(Preprocessor &PP, Module *OwningModule,
+  static ModuleMacro *create(Preprocessor &PP, const Module *OwningModule,
                              const IdentifierInfo *II, MacroInfo *Macro,
                              ArrayRef<ModuleMacro *> Overrides);
 
@@ -546,7 +546,7 @@ class ModuleMacro : public llvm::FoldingSetNode {
     return Profile(ID, OwningModule, II);
   }
 
-  static void Profile(llvm::FoldingSetNodeID &ID, Module *OwningModule,
+  static void Profile(llvm::FoldingSetNodeID &ID, const Module *OwningModule,
                       const IdentifierInfo *II) {
     ID.AddPointer(OwningModule);
     ID.AddPointer(II);
@@ -556,7 +556,7 @@ class ModuleMacro : public llvm::FoldingSetNode {
   const IdentifierInfo *getName() const { return II; }
 
   /// Get the ID of the module that exports this macro.
-  Module *getOwningModule() const { return OwningModule; }
+  const Module *getOwningModule() const { return OwningModule; }
 
   /// Get definition for this exported #define, or nullptr if this
   /// represents a #undef.
diff --git a/clang/include/clang/Lex/ModuleMap.h b/clang/include/clang/Lex/ModuleMap.h
index 2e28ff6823cb2..4c5741412d600 100644
--- a/clang/include/clang/Lex/ModuleMap.h
+++ b/clang/include/clang/Lex/ModuleMap.h
@@ -105,7 +105,7 @@ class ModuleMap {
   llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
 
   /// Shadow modules created while building this module map.
-  llvm::SmallVector<Module*, 2> ShadowModules;
+  llvm::SmallVector<const Module *, 2> ShadowModules;
 
   /// The number of modules we have created in total.
   unsigned NumCreatedModules = 0;
@@ -182,7 +182,7 @@ class ModuleMap {
     }
 
     /// Whether this header is accessible from the specified module.
-    bool isAccessibleFrom(Module *M) const {
+    bool isAccessibleFrom(const Module *M) const {
       return !(getRole() & PrivateHeader) ||
              (M && M->getTopLevelModule() == getModule()->getTopLevelModule());
     }
@@ -227,7 +227,7 @@ class ModuleMap {
   /// Modules from the same scope may not have the same name.
   unsigned CurrentModuleScopeID = 0;
 
-  llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
+  llvm::DenseMap<const Module *, unsigned> ModuleScopeIDs;
 
   /// The set of attributes that can be attached to a module.
   struct Attributes {
@@ -300,7 +300,8 @@ class ModuleMap {
   /// \returns The resolved export declaration, which will have a NULL pointer
   /// if the export could not be resolved.
   Module::ExportDecl
-  resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
+  resolveExport(const Module *Mod,
+                const Module::UnresolvedExportDecl &Unresolved,
                 bool Complain) const;
 
   /// Resolve the given module id to an actual module.
@@ -314,7 +315,8 @@ class ModuleMap {
   ///
   /// \returns The resolved module, or null if the module-id could not be
   /// resolved.
-  Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
+  Module *resolveModuleId(const ModuleId &Id, const Module *Mod,
+                          bool Complain) const;
 
   /// Add an unresolved header to a module.
   ///
@@ -337,7 +339,7 @@ class ModuleMap {
   ///        be found in case M was, set it to true. False otherwise.
   /// \return The resolved file, if any.
   OptionalFileEntryRef
-  findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
+  findHeader(const Module *M, const Module::UnresolvedHeaderDirective &Header,
              SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
 
   /// Resolve the given header directive.
@@ -382,8 +384,8 @@ class ModuleMap {
     return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
   }
 
-  Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, Attributes Attrs,
-                               Module *Parent);
+  const Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir,
+                                     Attributes Attrs, Module *Parent);
 
 public:
   /// Construct a new module map.
@@ -418,7 +420,7 @@ class ModuleMap {
   bool isBuiltinHeader(FileEntryRef File);
 
   bool shouldImportRelativeToBuiltinIncludeDir(StringRef FileName,
-                                               Module *Module) const;
+                                               const Module *Module) const;
 
   /// Add a module map callback.
   void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
@@ -511,7 +513,7 @@ class ModuleMap {
   /// name lookup.
   ///
   /// \returns The named module, if known; otherwise, returns null.
-  Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
+  Module *lookupModuleUnqualified(StringRef Name, const Module *Context) const;
 
   /// Retrieve a module with the given name within the given context,
   /// using direct (qualified) name lookup.
@@ -522,7 +524,7 @@ class ModuleMap {
   /// null, we will look for a top-level module.
   ///
   /// \returns The named submodule, if known; otherwose, returns null.
-  Module *lookupModuleQualified(StringRef Name, Module *Context) const;
+  Module *lookupModuleQualified(StringRef Name, const Module *Context) const;
 
   /// Find a new module or submodule, or create it if it does not already
   /// exist.
@@ -585,13 +587,13 @@ class ModuleMap {
 
   /// Infer the contents of a framework module map from the given
   /// framework directory.
-  Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, bool IsSystem,
-                               Module *Parent);
+  const Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir,
+                                     bool IsSystem, Module *Parent);
 
   /// Create a new top-level module that is shadowed by
   /// \p ShadowingModule.
   Module *createShadowedModule(StringRef Name, bool IsFramework,
-                               Module *ShadowingModule);
+                               const Module *ShadowingModule);
 
   /// Creates a new declaration scope for module names, allowing
   /// previously defined modules to shadow definitions from the new scope.
@@ -600,7 +602,7 @@ class ModuleMap {
   /// scope, which is the opposite of how shadowing works for variables.
   void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
 
-  bool mayShadowNewModule(Module *ExistingModule) {
+  bool mayShadowNewModule(const Module *ExistingModule) {
     assert(!ExistingModule->Parent && "expected top-level module");
     assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
     return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
@@ -634,7 +636,7 @@ class ModuleMap {
   FileID getModuleMapFileIDForUniquing(const Module *M) const;
   OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const;
 
-  void setInferredModuleAllowedBy(Module *M, FileID ModMapFID);
+  void setInferredModuleAllowedBy(const Module *M, FileID ModMapFID);
 
   /// Canonicalize \p Path in a manner suitable for a module map file. In
   /// particular, this canonicalizes the parent directory separately from the
diff --git a/clang/include/clang/Lex/PPCallbacks.h b/clang/include/clang/Lex/PPCallbacks.h
index dfc74b52686f1..5f4ad21aa8834 100644
--- a/clang/include/clang/Lex/PPCallbacks.h
+++ b/clang/include/clang/Lex/PPCallbacks.h
@@ -153,8 +153,8 @@ class PPCallbacks {
   ///
   /// \param ForPragma If entering from pragma directive.
   ///
-  virtual void EnteredSubmodule(Module *M, SourceLocation ImportLoc,
-                                bool ForPragma) { }
+  virtual void EnteredSubmodule(const Module *M, SourceLocation ImportLoc,
+                                bool ForPragma) {}
 
   /// Callback invoked whenever a submodule was left.
   ///
@@ -164,8 +164,8 @@ class PPCallbacks {
   ///
   /// \param ForPragma If entering from pragma directive.
   ///
-  virtual void LeftSubmodule(Module *M, SourceLocation ImportLoc,
-                             bool ForPragma) { }
+  virtual void LeftSubmodule(const Module *M, SourceLocation ImportLoc,
+                             bool ForPragma) {}
 
   /// Callback invoked whenever there was an explicit module-import
   /// syntax.
@@ -487,13 +487,13 @@ class PPChainedCallbacks : public PPCallbacks {
                                SuggestedModule, ModuleImported, FileType);
   }
 
-  void EnteredSubmodule(Module *M, SourceLocation ImportLoc,
+  void EnteredSubmodule(const Module *M, SourceLocation ImportLoc,
                         bool ForPragma) override {
     First->EnteredSubmodule(M, ImportLoc, ForPragma);
     Second->EnteredSubmodule(M, ImportLoc, ForPragma);
   }
 
-  void LeftSubmodule(Module *M, SourceLocation ImportLoc,
+  void LeftSubmodule(const Module *M, SourceLocation ImportLoc,
                      bool ForPragma) override {
     First->LeftSubmodule(M, ImportLoc, ForPragma);
     Second->LeftSubmodule(M, ImportLoc, ForPragma);
diff --git a/clang/include/clang/Lex/Preprocessor.h b/clang/include/clang/Lex/Preprocessor.h
index c0850a8fa9f7f..553166cd07af0 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -766,14 +766,14 @@ class Preprocessor {
 
   /// If the current lexer is for a submodule that is being built, this
   /// is that submodule.
-  Module *CurLexerSubmodule = nullptr;
+  const Module *CurLexerSubmodule = nullptr;
 
   /// Keeps track of the stack of files currently
   /// \#included, and macros currently being expanded from, not counting
   /// CurLexer/CurTokenLexer.
   struct IncludeStackInfo {
     LexerCallback               CurLexerCallback;
-    Module                     *TheSubmodule;
+    const Module *TheSubmodule;
     std::unique_ptr<Lexer>      TheLexer;
     PreprocessorLexer          *ThePPLexer;
     std::unique_ptr<TokenLexer> TheTokenLexer;
@@ -781,7 +781,7 @@ class Preprocessor {
 
     // The following constructors are completely useless copies of the default
     // versions, only needed to pacify MSVC.
-    IncludeStackInfo(LexerCallback CurLexerCallback, Module *TheSubmodule,
+    IncludeStackInfo(LexerCallback CurLexerCallback, const Module *TheSubmodule,
                      std::unique_ptr<Lexer> &&TheLexer,
                      PreprocessorLexer *ThePPLexer,
                      std::unique_ptr<TokenLexer> &&TheTokenLexer,
@@ -990,7 +990,7 @@ class Preprocessor {
     // FIXME: CounterValue?
     // FIXME: PragmaPushMacroInfo?
   };
-  std::map<Module *, SubmoduleState> Submodules;
+  std::map<const Module *, SubmoduleState> Submodules;
 
   /// The preprocessor state for preprocessing outside of any submodule.
   SubmoduleState NullSubmoduleState;
@@ -1004,7 +1004,7 @@ class Preprocessor {
 
   /// The set of top-level modules that affected preprocessing, but were not
   /// imported.
-  llvm::SmallSetVector<Module *, 2> AffectingClangModules;
+  llvm::SmallSetVector<const Module *, 2> AffectingClangModules;
 
   /// The set of known macros exported from modules.
   llvm::FoldingSet<ModuleMacro> ModuleMacros;
@@ -1289,7 +1289,7 @@ class Preprocessor {
 
   /// Return the submodule owning the file being lexed. This may not be
   /// the current module if we have changed modules since entering the file.
-  Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; }
+  const Module *getCurrentLexerSubmodule() const { return CurLexerSubmodule; }
 
   /// Returns the FileID for the preprocessor predefines.
   FileID getPredefinesFileID() const { return PredefinesFileID; }
@@ -1341,7 +1341,7 @@ class Preprocessor {
   /// Determine whether II is defined as a macro within the module M,
   /// if that is a module that we've already preprocessed. Does not check for
   /// macros imported into M.
-  bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M) {
+  bool isMacroDefinedInLocalModule(const IdentifierInfo *II, const Module *M) {
     if (!II->hasMacroDefinition())
       return false;
     auto I = Submodules.find(M);
@@ -1432,10 +1432,10 @@ class Preprocessor {
                                MacroDirective *MD);
 
   /// Register an exported macro for a module and identifier.
-  ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II,
+  ModuleMacro *addModuleMacro(const Module *Mod, IdentifierInfo *II,
                               MacroInfo *Macro,
                               ArrayRef<ModuleMacro *> Overrides, bool &IsNew);
-  ModuleMacro *getModuleMacro(Module *Mod, const IdentifierInfo *II);
+  ModuleMacro *getModuleMacro(const Module *Mod, const IdentifierInfo *II);
 
   /// Get the list of leaf (non-overridden) module macros for a name.
   ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const {
@@ -1471,7 +1471,7 @@ class Preprocessor {
   /// \}
 
   /// Mark the given clang module as affecting the current clang module or translation unit.
-  void markClangModuleAsAffecting(Module *M) {
+  void markClangModuleAsAffecting(const Module *M) {
     assert(M->isModuleMapModule());
     if (!BuildingSubmoduleStack.empty()) {
       if (M != BuildingSubmoduleStack.back().M)
@@ -1483,7 +1483,8 @@ class Preprocessor {
 
   /// Get the set of top-level clang modules that affected preprocessing, but were not
   /// imported.
-  const llvm::SmallSetVector<Module *, 2> &getAffectingClangModules() const {
+  const llvm::SmallSetVector<const Module *, 2> &
+  getAffectingClangModules() const {
     return AffectingClangModules;
   }
 
@@ -1739,7 +1740,7 @@ class Preprocessor {
 
   void makeModuleVisible(Module *M, SourceLocation Loc);
 
-  SourceLocation getModuleImportLoc(Module *M) const {
+  SourceLocation getModuleImportLoc(const Module *M) const {
     return CurSubmoduleState->VisibleModules.getImportLoc(M);
   }
 
@@ -2360,7 +2361,7 @@ class Preprocessor {
   Module *getCurrentModule();
 
   /// Retrieves the module whose implementation we're current compiling, if any.
-  Module *getCurrentModuleImplementation();
+  const Module *getCurrentModuleImplementation();
 
   /// If we are preprocessing a named module.
   bool isInNamedModule() const { return ModuleDeclState.isNamedModule(); }
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index ec083f7cc09b7..f10602260355f 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -7461,7 +7461,7 @@ class Sema final : public SemaBase {
   /// Get the set of additional modules that should be checked during
   /// name lookup. A module and its imports become visible when instanting a
   /// template defined within it.
-  llvm::DenseSet<Module *> &getLookupModules();
+  llvm::DenseSet<const Module *> &getLookupModules();
 
   bool hasVisibleMergedDefinition(const NamedDecl *Def);
   bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
@@ -7482,41 +7482,47 @@ class Sema final : public SemaBase {
   /// specialization declaration for a specialization of a template. (For a
   /// member specialization, use hasVisibleMemberSpecialization.)
   bool hasVisibleExplicitSpecialization(
-      const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr);
   /// Determine if there is a reachable declaration of \p D that is an explicit
   /// specialization declaration for a specialization of a template. (For a
   /// member specialization, use hasReachableMemberSpecialization.)
   bool hasReachableExplicitSpecialization(
-      const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr);
 
   /// Determine if there is a visible declaration of \p D that is a member
   /// specialization declaration (as opposed to an instantiated declaration).
   bool hasVisibleMemberSpecialization(
-      const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr);
   /// Determine if there is a reachable declaration of \p D that is a member
   /// specialization declaration (as opposed to an instantiated declaration).
   bool hasReachableMemberSpecialization(
-      const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr);
 
   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
 
   /// Determine whether any declaration of an entity is visible.
-  bool
-  hasVisibleDeclaration(const NamedDecl *D,
-                        llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
+  bool hasVisibleDeclaration(
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr) {
     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
   }
 
-  bool hasVisibleDeclarationSlow(const NamedDecl *D,
-                                 llvm::SmallVectorImpl<Module *> *Modules);
-  /// Determine whether any declaration of an entity is reachable.
   bool
-  hasReachableDeclaration(const NamedDecl *D,
-                          llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
+  hasVisibleDeclarationSlow(const NamedDecl *D,
+                            llvm::SmallVectorImpl<const Module *> *Modules);
+  /// Determine whether any declaration of an entity is reachable.
+  bool hasReachableDeclaration(
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr) {
     return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
   }
   bool hasReachableDeclarationSlow(
-      const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
+      const NamedDecl *D,
+      llvm::SmallVectorImpl<const Module *> *Modules = nullptr);
 
   void diagnoseTypo(const TypoCorrection &Correction,
                     const PartialDiagnostic &TypoDiag,
@@ -7702,7 +7708,7 @@ class Sema final : public SemaBase {
 
   // When loading a non-modular PCH files, this is used to restore module
   // visibility.
-  void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
+  void makeModuleVisible(const Module *Mod, SourceLocation ImportLoc) {
     VisibleModules.setVisible(Mod, ImportLoc);
   }
 
@@ -7802,7 +7808,7 @@ class Sema final : public SemaBase {
   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
 
   /// For an interface unit, this is the implicitly imported interface unit.
-  clang::Module *ThePrimaryInterface = nullptr;
+  const clang::Module *ThePrimaryInterface = nullptr;
 
   /// The explicit global module fragment of the current translation unit.
   /// The explicit Global Module Fragment, as specified in C++
@@ -7827,12 +7833,12 @@ class Sema final : public SemaBase {
   bool isCurrentModulePurview() const;
 
   /// Enter the scope of the explicit global module fragment.
-  Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
+  const Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
   /// Leave the scope of the explicit global module fragment.
   void PopGlobalModuleFragment();
 
   /// Enter the scope of an implicit global module fragment.
-  Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
+  const Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
   /// Leave the scope of an implicit global module fragment.
   void PopImplicitGlobalModuleFragment();
 
@@ -10174,12 +10180,12 @@ class Sema final : public SemaBase {
 
   /// Extra modules inspected when performing a lookup during a template
   /// instantiation. Computed lazily.
-  SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
+  SmallVector<const Module *, 16> CodeSynthesisContextLookupModules;
 
   /// Cache of additional modules that should be used for name lookup
   /// within the current template instantiation. Computed lazily; use
   /// getLookupModules() to get a complete set.
-  llvm::DenseSet<Module *> LookupModulesCache;
+  llvm::DenseSet<const Module *> LookupModulesCache;
 
   /// Map from the most recent declaration of a namespace to the most
   /// recent visible declaration of that namespace.
diff --git a/clang/include/clang/Serialization/ASTDeserializationListener.h b/clang/include/clang/Serialization/ASTDeserializationListener.h
index 1d81a9ae3fe2e..8aa69c2b3a3d3 100644
--- a/clang/include/clang/Serialization/ASTDeserializationListener.h
+++ b/clang/include/clang/Serialization/ASTDeserializationListener.h
@@ -51,7 +51,7 @@ class ASTDeserializationListener {
   virtual void MacroDefinitionRead(serialization::PreprocessedEntityID,
                                    MacroDefinitionRecord *MD) {}
   /// A module definition was read from the AST file.
-  virtual void ModuleRead(serialization::SubmoduleID ID, Module *Mod) {}
+  virtual void ModuleRead(serialization::SubmoduleID ID, const Module *Mod) {}
   /// A module import was read from the AST file.
   virtual void ModuleImportRead(serialization::SubmoduleID ID,
                                 SourceLocation ImportLoc) {}
diff --git a/clang/include/clang/Serialization/ASTReader.h b/clang/include/clang/Serialization/ASTReader.h
index 4ece4593f0738..e698d3dce658b 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -714,7 +714,7 @@ class ASTReader
 
   /// A set of hidden declarations.
   using HiddenNames = SmallVector<Decl *, 2>;
-  using HiddenNamesMapType = llvm::DenseMap<Module *, HiddenNames>;
+  using HiddenNamesMapType = llvm::DenseMap<const Module *, HiddenNames>;
 
   /// A mapping from each of the hidden submodules to the deserialized
   /// declarations in that submodule that could be made visible.
@@ -1672,7 +1672,7 @@ class ASTReader
                          SourceLocation ImportLoc);
 
   /// Make the names within this set of hidden names visible.
-  void makeNamesVisible(const HiddenNames &Names, Module *Owner);
+  void makeNamesVisible(const HiddenNames &Names, const Module *Owner);
 
   /// Note that MergedDef is a redefinition of the canonical definition
   /// Def, so Def should be visible whenever MergedDef is.
diff --git a/clang/include/clang/Serialization/ASTWriter.h b/clang/include/clang/Serialization/ASTWriter.h
index 88192e439a3f0..033b5ce39f409 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -362,7 +362,7 @@ class ASTWriter : public ASTDeserializationListener,
   ///
   /// Only meaningful for standard C++ named modules. See the comments in
   /// createSignatureForNamedModule() for details.
-  llvm::DenseSet<Module *> TouchedTopLevelModules;
+  llvm::DenseSet<const Module *> TouchedTopLevelModules;
 
   /// An update to a Decl.
   class DeclUpdate {
@@ -373,7 +373,7 @@ class ASTWriter : public ASTDeserializationListener,
       void *Type;
       SourceLocation::UIntTy Loc;
       unsigned Val;
-      Module *Mod;
+      const Module *Mod;
       const Attr *Attribute;
     };
 
@@ -385,7 +385,7 @@ class ASTWriter : public ASTDeserializationListener,
     DeclUpdate(unsigned Kind, SourceLocation Loc)
         : Kind(Kind), Loc(Loc.getRawEncoding()) {}
     DeclUpdate(unsigned Kind, unsigned Val) : Kind(Kind), Val(Val) {}
-    DeclUpdate(unsigned Kind, Module *M) : Kind(Kind), Mod(M) {}
+    DeclUpdate(unsigned Kind, const Module *M) : Kind(Kind), Mod(M) {}
     DeclUpdate(unsigned Kind, const Attr *Attribute)
           : Kind(Kind), Attribute(Attribute) {}
 
@@ -398,7 +398,7 @@ class ASTWriter : public ASTDeserializationListener,
     }
 
     unsigned getNumber() const { return Val; }
-    Module *getModule() const { return Mod; }
+    const Module *getModule() const { return Mod; }
     const Attr *getAttr() const { return Attribute; }
   };
 
@@ -526,7 +526,7 @@ class ASTWriter : public ASTDeserializationListener,
   SourceLocation::UIntTy getAdjustment(SourceLocation::UIntTy Offset) const;
 
   /// Retrieve or create a submodule ID for this module.
-  unsigned getSubmoduleID(Module *Mod);
+  unsigned getSubmoduleID(const Module *Mod);
 
   /// Write the given subexpression to the bitstream.
   void WriteSubStmt(Stmt *S);
@@ -859,7 +859,7 @@ class ASTWriter : public ASTDeserializationListener,
   void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
   void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
                            MacroDefinitionRecord *MD) override;
-  void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
+  void ModuleRead(serialization::SubmoduleID ID, const Module *Mod) override;
 
   // ASTMutationListener implementation.
   void CompletedTagDefinition(const TagDecl *D) override;
@@ -891,7 +891,7 @@ class ASTWriter : public ASTDeserializationListener,
   void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
                                             const Attr *Attr) override;
   void DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) override;
-  void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
+  void RedefinedHiddenDefinition(const NamedDecl *D, const Module *M) override;
   void AddedAttributeToRecord(const Attr *Attr,
                               const RecordDecl *Record) override;
   void EnteringModulePurview() override;
diff --git a/clang/lib/APINotes/APINotesManager.cpp b/clang/lib/APINotes/APINotesManager.cpp
index 789bb97d81de0..592f6ef6d02c5 100644
--- a/clang/lib/APINotes/APINotesManager.cpp
+++ b/clang/lib/APINotes/APINotesManager.cpp
@@ -217,7 +217,7 @@ static bool hasPrivateSubmodules(const Module *M) {
 }
 
 llvm::SmallVector<FileEntryRef, 2>
-APINotesManager::getCurrentModuleAPINotes(Module *M, bool LookInModule,
+APINotesManager::getCurrentModuleAPINotes(const Module *M, bool LookInModule,
                                           ArrayRef<std::string> SearchPaths) {
   FileManager &FM = SM.getFileManager();
   auto ModuleName = M->getTopLevelModuleName();
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index a2398fef623ea..20b21f2cf2956 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -1024,7 +1024,7 @@ void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
     return;
 
   auto &Merged = It->second;
-  llvm::DenseSet<Module*> Found;
+  llvm::DenseSet<const Module *> Found;
   for (Module *&M : Merged)
     if (!Found.insert(M).second)
       M = nullptr;
@@ -1057,7 +1057,7 @@ void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
          "GetExternalDecl for lazy module initializer added more inits");
 }
 
-void ASTContext::addModuleInitializer(Module *M, Decl *D) {
+void ASTContext::addModuleInitializer(const Module *M, Decl *D) {
   // One special case: if we add a module initializer that imports another
   // module, and that module's only initializer is an ImportDecl, simplify.
   if (const auto *ID = dyn_cast<ImportDecl>(D)) {
@@ -1083,7 +1083,7 @@ void ASTContext::addModuleInitializer(Module *M, Decl *D) {
   Inits->Initializers.push_back(D);
 }
 
-void ASTContext::addLazyModuleInitializers(Module *M,
+void ASTContext::addLazyModuleInitializers(const Module *M,
                                            ArrayRef<GlobalDeclID> IDs) {
   auto *&Inits = ModuleInitializers[M];
   if (!Inits)
@@ -1092,7 +1092,7 @@ void ASTContext::addLazyModuleInitializers(Module *M,
                                  IDs.begin(), IDs.end());
 }
 
-ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
+ArrayRef<Decl *> ASTContext::getModuleInitializers(const Module *M) {
   auto It = ModuleInitializers.find(M);
   if (It == ModuleInitializers.end())
     return std::nullopt;
diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 41fbfe281ef65..8c47b48854b4c 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -1621,13 +1621,13 @@ LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
                              : CK);
 }
 
-Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
+const Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
   if (isa<NamespaceDecl>(this))
     // Namespaces never have module linkage.  It is the entities within them
     // that [may] do.
     return nullptr;
 
-  Module *M = getOwningModule();
+  const Module *M = getOwningModule();
   if (!M)
     return nullptr;
 
@@ -5675,7 +5675,7 @@ HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C,
 
 /// Retrieve the number of module identifiers needed to name the given
 /// module.
-static unsigned getNumModuleIdentifiers(Module *Mod) {
+static unsigned getNumModuleIdentifiers(const Module *Mod) {
   unsigned Result = 1;
   while (Mod->Parent) {
     Mod = Mod->Parent;
diff --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 65d5eeb6354eb..27bcb4484322c 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -106,7 +106,7 @@ void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
     Buffer += ExtraAlign;
     auto *ParentModule =
         Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
-    return new (Buffer) Module*(ParentModule) + 1;
+    return new (Buffer) const Module *(ParentModule) + 1;
   }
   return ::operator new(Size + Extra, Ctx);
 }
diff --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index ed9e6eeb36c75..56d89321cec97 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -1109,7 +1109,7 @@ void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
 
 void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
   if (ND->isExternallyVisible())
-    if (Module *M = ND->getOwningModuleForLinkage())
+    if (const Module *M = ND->getOwningModuleForLinkage())
       mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
 }
 
diff --git a/clang/lib/AST/ODRDiagsEmitter.cpp b/clang/lib/AST/ODRDiagsEmitter.cpp
index 37f0f68c92355..c185c592c8961 100644
--- a/clang/lib/AST/ODRDiagsEmitter.cpp
+++ b/clang/lib/AST/ODRDiagsEmitter.cpp
@@ -42,7 +42,7 @@ static unsigned computeODRHash(const TemplateArgument &TA) {
 
 std::string ODRDiagsEmitter::getOwningModuleNameForDiagnostic(const Decl *D) {
   // If we know the owning module, use it.
-  if (Module *M = D->getImportedOwningModule())
+  if (const Module *M = D->getImportedOwningModule())
     return M->getFullModuleName();
 
   // Not from a module.
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index 4a1e94ffe283b..52c1a13f6b4a4 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -282,10 +282,10 @@ void TextNodeDumper::Visit(const Decl *D) {
   dumpLocation(D->getLocation());
   if (D->isFromASTFile())
     OS << " imported";
-  if (Module *M = D->getOwningModule())
+  if (const Module *M = D->getOwningModule())
     OS << " in " << M->getFullModuleName();
   if (auto *ND = dyn_cast<NamedDecl>(D))
-    for (Module *M : D->getASTContext().getModulesWithMergedDefinition(
+    for (const Module *M : D->getASTContext().getModulesWithMergedDefinition(
              const_cast<NamedDecl *>(ND)))
       AddChild([=] { OS << "also in " << M->getFullModuleName(); });
   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
diff --git a/clang/lib/Basic/Module.cpp b/clang/lib/Basic/Module.cpp
index 045ef580f9c33..a8cb90e389dd5 100644
--- a/clang/lib/Basic/Module.cpp
+++ b/clang/lib/Basic/Module.cpp
@@ -130,7 +130,7 @@ static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
 
 bool Module::isUnimportable(const LangOptions &LangOpts,
                             const TargetInfo &Target, Requirement &Req,
-                            Module *&ShadowingModule) const {
+                            const Module *&ShadowingModule) const {
   if (!IsUnimportable)
     return false;
 
@@ -176,7 +176,7 @@ bool Module::isForBuilding(const LangOptions &LangOpts) const {
 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
                          Requirement &Req,
                          UnresolvedHeaderDirective &MissingHeader,
-                         Module *&ShadowingModule) const {
+                         const Module *&ShadowingModule) const {
   if (IsAvailable)
     return true;
 
@@ -329,7 +329,7 @@ void Module::addRequirement(StringRef Feature, bool RequiredState,
 }
 
 void Module::markUnavailable(bool Unimportable) {
-  auto needUpdate = [Unimportable](Module *M) {
+  auto needUpdate = [Unimportable](const Module *M) {
     return M->IsAvailable || (!M->IsUnimportable && Unimportable);
   };
 
@@ -377,7 +377,7 @@ Module *Module::findOrInferSubmodule(StringRef Name) {
   return Result;
 }
 
-Module *Module::getGlobalModuleFragment() const {
+const Module *Module::getGlobalModuleFragment() const {
   assert(isNamedModuleUnit() && "We should only query the global module "
                                 "fragment from the C++20 Named modules");
 
@@ -388,7 +388,7 @@ Module *Module::getGlobalModuleFragment() const {
   return nullptr;
 }
 
-Module *Module::getPrivateModuleFragment() const {
+const Module *Module::getPrivateModuleFragment() const {
   assert(isNamedModuleUnit() && "We should only query the private module "
                                 "fragment from the C++20 Named modules");
 
@@ -401,10 +401,7 @@ Module *Module::getPrivateModuleFragment() const {
 
 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
   // All non-explicit submodules are exported.
-  for (std::vector<Module *>::const_iterator I = SubModules.begin(),
-                                             E = SubModules.end();
-       I != E; ++I) {
-    Module *Mod = *I;
+  for (Module *Mod : SubModules) {
     if (!Mod->IsExplicit)
       Exported.push_back(Mod);
   }
@@ -412,7 +409,7 @@ void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
   // Find re-exported modules by filtering the list of imported modules.
   bool AnyWildcard = false;
   bool UnrestrictedWildcard = false;
-  SmallVector<Module *, 4> WildcardRestrictions;
+  SmallVector<const Module *, 4> WildcardRestrictions;
   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
     Module *Mod = Exports[I].getPointer();
     if (!Exports[I].getInt()) {
@@ -428,7 +425,7 @@ void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
     if (UnrestrictedWildcard)
       continue;
 
-    if (Module *Restriction = Exports[I].getPointer())
+    if (const Module *Restriction = Exports[I].getPointer())
       WildcardRestrictions.push_back(Restriction);
     else {
       WildcardRestrictions.clear();
@@ -447,7 +444,7 @@ void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
     if (!Acceptable) {
       // Check whether this module meets one of the restrictions.
       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
-        Module *Restriction = WildcardRestrictions[R];
+        const Module *Restriction = WildcardRestrictions[R];
         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
           Acceptable = true;
           break;
@@ -471,7 +468,7 @@ void Module::buildVisibleModulesCache() const {
   // Every imported module is visible.
   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
   while (!Stack.empty()) {
-    Module *CurrModule = Stack.pop_back_val();
+    const Module *CurrModule = Stack.pop_back_val();
 
     // Every module transitively exported by an imported module is visible.
     if (VisibleModulesCache.insert(CurrModule).second)
@@ -589,7 +586,7 @@ void Module::print(raw_ostream &OS, unsigned Indent, bool Dump) const {
   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
     OS.indent(Indent + 2);
     OS << "export ";
-    if (Module *Restriction = Exports[I].getPointer()) {
+    if (const Module *Restriction = Exports[I].getPointer()) {
       OS << Restriction->getFullModuleName(true);
       if (Exports[I].getInt())
         OS << ".*";
@@ -609,7 +606,7 @@ void Module::print(raw_ostream &OS, unsigned Indent, bool Dump) const {
   }
 
   if (Dump) {
-    for (Module *M : Imports) {
+    for (const Module *M : Imports) {
       OS.indent(Indent + 2);
       llvm::errs() << "import " << M->getFullModuleName() << "\n";
     }
@@ -678,7 +675,7 @@ LLVM_DUMP_METHOD void Module::dump() const {
   print(llvm::errs(), 0, true);
 }
 
-void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
+void VisibleModuleSet::setVisible(const Module *M, SourceLocation Loc,
                                   VisibleCallback Vis, ConflictCallback Cb) {
   // We can't import a global module fragment so the location can be invalid.
   assert((M->isGlobalModule() || Loc.isValid()) &&
@@ -689,7 +686,7 @@ void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
   ++Generation;
 
   struct Visiting {
-    Module *M;
+    const Module *M;
     Visiting *ExportedBy;
   };
 
@@ -707,7 +704,7 @@ void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
     // Make any exported modules visible.
     SmallVector<Module *, 16> Exports;
     V.M->getExportedModules(Exports);
-    for (Module *E : Exports) {
+    for (const Module *E : Exports) {
       // Don't import non-importable modules.
       if (!E->isUnimportable())
         VisitModule({E, &V});
@@ -715,7 +712,7 @@ void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
 
     for (auto &C : V.M->Conflicts) {
       if (isVisible(C.Other)) {
-        llvm::SmallVector<Module*, 8> Path;
+        llvm::SmallVector<const Module *, 8> Path;
         for (Visiting *I = &V; I; I = I->ExportedBy)
           Path.push_back(I->M);
         Cb(Path, C.Other, C.Message);
@@ -725,7 +722,7 @@ void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
   VisitModule({M, nullptr});
 }
 
-ASTSourceDescriptor::ASTSourceDescriptor(Module &M)
+ASTSourceDescriptor::ASTSourceDescriptor(const Module &M)
     : Signature(M.Signature), ClangModule(&M) {
   if (M.Directory)
     Path = M.Directory->getName();
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp
index fac278f0e20a4..f8e30856db837 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3663,7 +3663,7 @@ llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
     // file where the type's definition is located, so it might be
     // best to make this behavior a command line or debugger tuning
     // option.
-    if (Module *M = D->getOwningModule()) {
+    if (const Module *M = D->getOwningModule()) {
       // This is a (sub-)module.
       auto Info = ASTSourceDescriptor(*M);
       return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
@@ -5864,7 +5864,7 @@ void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
   if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
     return;
-  if (Module *M = ID.getImportedModule()) {
+  if (const Module *M = ID.getImportedModule()) {
     auto Info = ASTSourceDescriptor(*M);
     auto Loc = ID.getLocation();
     DBuilder.createImportedDeclaration(
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index b047279912f6b..df279d2713e4f 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -658,7 +658,7 @@ void CodeGenModule::EmitCXXThreadLocalInitFunc() {
    We then call initializers for the Private Module Fragment (if present)
 */
 
-void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
+void CodeGenModule::EmitCXXModuleInitFunc(const Module *Primary) {
   assert(Primary->isInterfaceOrPartition() &&
          "The function should only be called for C++20 named module interface"
          " or partition.");
@@ -670,28 +670,28 @@ void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
   // Module initializers for imported modules are emitted first.
 
   // Collect all the modules that we import
-  llvm::SmallSetVector<Module *, 8> AllImports;
+  llvm::SmallSetVector<const Module *, 8> AllImports;
   // Ones that we export
   for (auto I : Primary->Exports)
     AllImports.insert(I.getPointer());
   // Ones that we only import.
-  for (Module *M : Primary->Imports)
+  for (const Module *M : Primary->Imports)
     AllImports.insert(M);
   // Ones that we import in the global module fragment or the private module
   // fragment.
-  for (Module *SubM : Primary->submodules()) {
+  for (const Module *SubM : Primary->submodules()) {
     assert((SubM->isGlobalModule() || SubM->isPrivateModule()) &&
            "The sub modules of C++20 module unit should only be global module "
            "fragments or private module framents.");
     assert(SubM->Exports.empty() &&
            "The global mdoule fragments and the private module fragments are "
            "not allowed to export import modules.");
-    for (Module *M : SubM->Imports)
+    for (const Module *M : SubM->Imports)
       AllImports.insert(M);
   }
 
   SmallVector<llvm::Function *, 8> ModuleInits;
-  for (Module *M : AllImports) {
+  for (const Module *M : AllImports) {
     // No Itanium initializer in header like modules.
     if (M->isHeaderLikeModule())
       continue; // TODO: warn of mixed use of module map modules and C++20?
@@ -831,7 +831,7 @@ CodeGenModule::EmitCXXGlobalInitFunc() {
   // When we import C++20 modules, we must run their initializers first.
   SmallVector<llvm::Function *, 8> ModuleInits;
   if (CXX20ModuleInits)
-    for (Module *M : ImportedModules) {
+    for (const Module *M : ImportedModules) {
       // No Itanium initializer in header like modules.
       if (M->isHeaderLikeModule())
         continue;
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index e4774a587707a..3e54f75631b44 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -838,7 +838,7 @@ static bool isStackProtectorOn(const LangOptions &LangOpts,
 }
 
 void CodeGenModule::Release() {
-  Module *Primary = getContext().getCurrentNamedModule();
+  const Module *Primary = getContext().getCurrentNamedModule();
   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
     EmitModuleInitializers(Primary);
   EmitDeferred();
@@ -2977,16 +2977,17 @@ void CodeGenModule::AddDependentLib(StringRef Lib) {
 
 /// Add link options implied by the given module, including modules
 /// it depends on, using a postorder walk.
-static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
-                                    SmallVectorImpl<llvm::MDNode *> &Metadata,
-                                    llvm::SmallPtrSet<Module *, 16> &Visited) {
+static void
+addLinkOptionsPostorder(CodeGenModule &CGM, const Module *Mod,
+                        SmallVectorImpl<llvm::MDNode *> &Metadata,
+                        llvm::SmallPtrSet<const Module *, 16> &Visited) {
   // Import this module's parent.
   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
   }
 
   // Import this module's dependencies.
-  for (Module *Import : llvm::reverse(Mod->Imports)) {
+  for (const Module *Import : llvm::reverse(Mod->Imports)) {
     if (Visited.insert(Import).second)
       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
   }
@@ -3028,7 +3029,7 @@ static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
   }
 }
 
-void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
+void CodeGenModule::EmitModuleInitializers(const clang::Module *Primary) {
   assert(Primary->isNamedModuleUnit() &&
          "We should only emit module initializers for named modules.");
 
@@ -3065,12 +3066,12 @@ void CodeGenModule::EmitModuleLinkOptions() {
   // Collect the set of all of the modules we want to visit to emit link
   // options, which is essentially the imported modules and all of their
   // non-explicit child modules.
-  llvm::SetVector<clang::Module *> LinkModules;
-  llvm::SmallPtrSet<clang::Module *, 16> Visited;
-  SmallVector<clang::Module *, 16> Stack;
+  llvm::SetVector<const clang::Module *> LinkModules;
+  llvm::SmallPtrSet<const clang::Module *, 16> Visited;
+  SmallVector<const clang::Module *, 16> Stack;
 
   // Seed the stack with imported modules.
-  for (Module *M : ImportedModules) {
+  for (const Module *M : ImportedModules) {
     // Do not add any link flags when an implementation TU of a module imports
     // a header of that same module.
     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
@@ -3083,7 +3084,7 @@ void CodeGenModule::EmitModuleLinkOptions() {
   // Find all of the modules to import, making a little effort to prune
   // non-leaf modules.
   while (!Stack.empty()) {
-    clang::Module *Mod = Stack.pop_back_val();
+    const clang::Module *Mod = Stack.pop_back_val();
 
     bool AnyChildren = false;
 
@@ -3112,7 +3113,7 @@ void CodeGenModule::EmitModuleLinkOptions() {
   // to linker options inserted by things like #pragma comment().
   SmallVector<llvm::MDNode *, 16> MetadataArgs;
   Visited.clear();
-  for (Module *M : LinkModules)
+  for (const Module *M : LinkModules)
     if (Visited.insert(M).second)
       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
@@ -7002,13 +7003,13 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
     // emitted here.
 
     // Find all of the submodules and emit the module initializers.
-    llvm::SmallPtrSet<clang::Module *, 16> Visited;
-    SmallVector<clang::Module *, 16> Stack;
+    llvm::SmallPtrSet<const clang::Module *, 16> Visited;
+    SmallVector<const clang::Module *, 16> Stack;
     Visited.insert(Import->getImportedModule());
     Stack.push_back(Import->getImportedModule());
 
     while (!Stack.empty()) {
-      clang::Module *Mod = Stack.pop_back_val();
+      const clang::Module *Mod = Stack.pop_back_val();
       if (!EmittedModuleInitializers.insert(Mod).second)
         continue;
 
diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h
index 0f68418130ead..f9a835eab4e60 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -520,11 +520,11 @@ class CodeGenModule : public CodeGenTypeCache {
   SmallVector<StermFinalizerData, 8> PrioritizedCXXStermFinalizers;
 
   /// The complete set of modules that has been imported.
-  llvm::SetVector<clang::Module *> ImportedModules;
+  llvm::SetVector<const clang::Module *> ImportedModules;
 
   /// The set of modules for which the module initializers
   /// have been emitted.
-  llvm::SmallPtrSet<clang::Module *, 16> EmittedModuleInitializers;
+  llvm::SmallPtrSet<const clang::Module *, 16> EmittedModuleInitializers;
 
   /// A vector of metadata strings for linker options.
   SmallVector<llvm::MDNode *, 16> LinkerOptionsMetadata;
@@ -1651,7 +1651,7 @@ class CodeGenModule : public CodeGenTypeCache {
   void EmitCXXThreadLocalInitFunc();
 
   /// Emit the function that initializes global variables for a C++ Module.
-  void EmitCXXModuleInitFunc(clang::Module *Primary);
+  void EmitCXXModuleInitFunc(const clang::Module *Primary);
 
   /// Emit the function that initializes C++ globals.
   void EmitCXXGlobalInitFunc();
@@ -1715,7 +1715,7 @@ class CodeGenModule : public CodeGenTypeCache {
   void emitLLVMUsed();
 
   /// For C++20 Itanium ABI, emit the initializers for the module.
-  void EmitModuleInitializers(clang::Module *Primary);
+  void EmitModuleInitializers(const clang::Module *Primary);
 
   /// Emit the link options introduced by imported modules.
   void EmitModuleLinkOptions();
diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp
index 6242b5a7d9fe3..8c01acc5be200 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1329,7 +1329,7 @@ static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File,
 /// using the options provided by the importing compiler instance. Returns true
 /// if the module was built without errors.
 static bool compileModule(CompilerInstance &ImportingInstance,
-                          SourceLocation ImportLoc, Module *Module,
+                          SourceLocation ImportLoc, const Module *Module,
                           StringRef ModuleFileName) {
   InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
                InputKind::ModuleMap);
@@ -1410,7 +1410,8 @@ static bool compileModule(CompilerInstance &ImportingInstance,
 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
                                       SourceLocation ImportLoc,
                                       SourceLocation ModuleNameLoc,
-                                      Module *Module, StringRef ModuleFileName,
+                                      const Module *Module,
+                                      StringRef ModuleFileName,
                                       bool *OutOfDate) {
   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
 
@@ -1445,7 +1446,7 @@ static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
                                         SourceLocation ImportLoc,
                                         SourceLocation ModuleNameLoc,
-                                        Module *Module,
+                                        const Module *Module,
                                         StringRef ModuleFileName) {
   if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
                      ModuleFileName)) {
@@ -1470,7 +1471,8 @@ static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
 /// bugs in the lock file manager.
 static bool compileModuleAndReadASTBehindLock(
     CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
-    SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
+    SourceLocation ModuleNameLoc, const Module *Module,
+    StringRef ModuleFileName) {
   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
 
   Diags.Report(ModuleNameLoc, diag::remark_module_lock)
@@ -1541,7 +1543,8 @@ static bool compileModuleAndReadASTBehindLock(
 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
                                     SourceLocation ImportLoc,
                                     SourceLocation ModuleNameLoc,
-                                    Module *Module, StringRef ModuleFileName) {
+                                    const Module *Module,
+                                    StringRef ModuleFileName) {
   return ImportingInstance.getInvocation()
                  .getFrontendOpts()
                  .BuildingImplicitModuleUsesLock
@@ -1556,7 +1559,7 @@ static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
 /// Diagnose differences between the current definition of the given
 /// configuration macro and the definition provided on the command line.
 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
-                             Module *Mod, SourceLocation ImportLoc) {
+                             const Module *Mod, SourceLocation ImportLoc) {
   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
   SourceManager &SourceMgr = PP.getSourceManager();
 
@@ -1611,9 +1614,9 @@ static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
   }
 }
 
-static void checkConfigMacros(Preprocessor &PP, Module *M,
+static void checkConfigMacros(Preprocessor &PP, const Module *M,
                               SourceLocation ImportLoc) {
-  clang::Module *TopModule = M->getTopLevelModule();
+  const clang::Module *TopModule = M->getTopLevelModule();
   for (const StringRef ConMacro : TopModule->ConfigMacros) {
     checkConfigMacro(PP, ConMacro, M, ImportLoc);
   }
@@ -1816,7 +1819,7 @@ enum ModuleSource {
 /// Select a source for loading the named module and compute the filename to
 /// load it from.
 static ModuleSource selectModuleSource(
-    Module *M, StringRef ModuleName, std::string &ModuleFilename,
+    const Module *M, StringRef ModuleName, std::string &ModuleFilename,
     const std::map<std::string, std::string, std::less<>> &BuiltModules,
     HeaderSearch &HS) {
   assert(ModuleFilename.empty() && "Already has a module source?");
@@ -2122,7 +2125,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc,
       SmallVector<StringRef, 2> Best;
       unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
 
-      for (class Module *SubModule : Module->submodules()) {
+      for (const class Module *SubModule : Module->submodules()) {
         unsigned ED =
             Name.edit_distance(SubModule->Name,
                                /*AllowReplacements=*/true, BestEditDistance);
@@ -2303,7 +2306,7 @@ GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
     bool RecreateIndex = false;
     for (ModuleMap::module_iterator I = MMap.module_begin(),
         E = MMap.module_end(); I != E; ++I) {
-      Module *TheModule = I->second;
+      const Module *TheModule = I->second;
       OptionalFileEntryRef Entry = TheModule->getASTFile();
       if (!Entry) {
         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp
index a9c45e525c696..20ce02a9e5f73 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -154,7 +154,7 @@ void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
   CurrentASTUnit = std::move(AST);
 }
 
-Module *FrontendAction::getCurrentModule() const {
+const Module *FrontendAction::getCurrentModule() const {
   CompilerInstance &CI = getCompilerInstance();
   return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
       CI.getLangOpts().CurrentModule, SourceLocation(), /*AllowSearch*/false);
@@ -663,7 +663,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
     // Set up the input file for replay purposes.
     auto Kind = AST->getInputKind();
     if (Kind.getFormat() == InputKind::ModuleMap) {
-      Module *ASTModule =
+      const Module *ASTModule =
           AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
               AST->getLangOpts().CurrentModule, SourceLocation(),
               /*AllowSearch*/ false);
diff --git a/clang/lib/Frontend/FrontendActions.cpp b/clang/lib/Frontend/FrontendActions.cpp
index 454653a31534c..6c93744dc685b 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -879,7 +879,7 @@ void DumpModuleInfoAction::ExecuteAction() {
 
     struct SubModInfo {
       unsigned Idx;
-      Module *Mod;
+      const Module *Mod;
       Module::ModuleKind Kind;
       std::string &Name;
       bool Seen;
@@ -895,7 +895,7 @@ void DumpModuleInfoAction::ExecuteAction() {
         Out << " is at index #" << I->second.Idx << "\n";
       }
     };
-    Module *Primary = nullptr;
+    const Module *Primary = nullptr;
     for (unsigned Idx = 0; Idx <= SubModuleCount; ++Idx) {
       Module *M = R->getModule(Idx);
       if (!M)
@@ -922,7 +922,7 @@ void DumpModuleInfoAction::ExecuteAction() {
       if (!Primary->Exports.empty())
         Out << "   Exports:\n";
       for (unsigned MN = 0, N = Primary->Exports.size(); MN != N; ++MN) {
-        if (Module *M = Primary->Exports[MN].getPointer()) {
+        if (const Module *M = Primary->Exports[MN].getPointer()) {
           PrintSubMapEntry(M->Name, M->Kind);
         }
       }
diff --git a/clang/lib/Frontend/MultiplexConsumer.cpp b/clang/lib/Frontend/MultiplexConsumer.cpp
index 8fdc7f55a5003..c555f6d45a3b4 100644
--- a/clang/lib/Frontend/MultiplexConsumer.cpp
+++ b/clang/lib/Frontend/MultiplexConsumer.cpp
@@ -71,7 +71,7 @@ void MultiplexASTDeserializationListener::MacroDefinitionRead(
 }
 
 void MultiplexASTDeserializationListener::ModuleRead(
-    serialization::SubmoduleID ID, Module *Mod) {
+    serialization::SubmoduleID ID, const Module *Mod) {
   for (auto &Listener : Listeners)
     Listener->ModuleRead(ID, Mod);
 }
@@ -115,7 +115,7 @@ class MultiplexASTMutationListener : public ASTMutationListener {
   void DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) override;
   void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
                                             const Attr *Attr) override;
-  void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
+  void RedefinedHiddenDefinition(const NamedDecl *D, const Module *M) override;
   void AddedAttributeToRecord(const Attr *Attr,
                               const RecordDecl *Record) override;
   void EnteringModulePurview() override;
@@ -234,7 +234,7 @@ void MultiplexASTMutationListener::DeclarationMarkedOpenMPDeclareTarget(
     L->DeclarationMarkedOpenMPDeclareTarget(D, Attr);
 }
 void MultiplexASTMutationListener::RedefinedHiddenDefinition(const NamedDecl *D,
-                                                             Module *M) {
+                                                             const Module *M) {
   for (auto *L : Listeners)
     L->RedefinedHiddenDefinition(D, M);
 }
diff --git a/clang/lib/Frontend/PrintPreprocessedOutput.cpp b/clang/lib/Frontend/PrintPreprocessedOutput.cpp
index a26d2c3ab8582..730024de50436 100644
--- a/clang/lib/Frontend/PrintPreprocessedOutput.cpp
+++ b/clang/lib/Frontend/PrintPreprocessedOutput.cpp
@@ -859,13 +859,13 @@ static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
       // token is at the include location (outside the file) and the module_end
       // token is at the EOF location (within the file).
       Callbacks->BeginModule(
-          reinterpret_cast<Module *>(Tok.getAnnotationValue()));
+          reinterpret_cast<const Module *>(Tok.getAnnotationValue()));
       PP.Lex(Tok);
       IsStartOfLine = true;
       continue;
     } else if (Tok.is(tok::annot_module_end)) {
       Callbacks->EndModule(
-          reinterpret_cast<Module *>(Tok.getAnnotationValue()));
+          reinterpret_cast<const Module *>(Tok.getAnnotationValue()));
       PP.Lex(Tok);
       IsStartOfLine = true;
       continue;
@@ -874,7 +874,8 @@ static void PrintPreprocessedTokens(Preprocessor &PP, Token &Tok,
       // module-name.
       // FIXME: The module name could contain non-identifier module name
       // components. We don't have a good way to round-trip those.
-      Module *M = reinterpret_cast<Module *>(Tok.getAnnotationValue());
+      const Module *M =
+          reinterpret_cast<const Module *>(Tok.getAnnotationValue());
       std::string Name = M->getFullModuleName();
       Callbacks->OS->write(Name.data(), Name.size());
       Callbacks->HandleNewlinesInToken(Name.data(), Name.size());
diff --git a/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp b/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
index 1462058003b3d..9c6f4f5167116 100644
--- a/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
+++ b/clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
@@ -63,7 +63,8 @@ class InclusionRewriter : public PPCallbacks {
   void handleModuleBegin(Token &Tok) {
     assert(Tok.getKind() == tok::annot_module_begin);
     ModuleEntryIncludes.insert(
-        {Tok.getLocation(), (Module *)Tok.getAnnotationValue()});
+        {Tok.getLocation(),
+         static_cast<const Module *>(Tok.getAnnotationValue())});
   }
 private:
   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
diff --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 574723b33866a..356738dfd9673 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -190,7 +190,7 @@ void HeaderSearch::getHeaderMapFileNames(
     Names.push_back(std::string(HM.first.getName()));
 }
 
-std::string HeaderSearch::getCachedModuleFileName(Module *Module) {
+std::string HeaderSearch::getCachedModuleFileName(const Module *Module) {
   OptionalFileEntryRef ModuleMap =
       getModuleMap().getModuleMapFileForUniquing(Module);
   // The ModuleMap maybe a nullptr, when we load a cached C++ module without
@@ -231,7 +231,8 @@ std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,
   return {};
 }
 
-std::string HeaderSearch::getPrebuiltImplicitModuleFileName(Module *Module) {
+std::string
+HeaderSearch::getPrebuiltImplicitModuleFileName(const Module *Module) {
   OptionalFileEntryRef ModuleMap =
       getModuleMap().getModuleMapFileForUniquing(Module);
   StringRef ModuleName = Module->Name;
@@ -602,7 +603,7 @@ getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
   return TopFrameworkDir;
 }
 
-static bool needModuleLookup(Module *RequestingModule,
+static bool needModuleLookup(const Module *RequestingModule,
                              bool HasSuggestedModule) {
   return HasSuggestedModule ||
          (RequestingModule && RequestingModule->NoUndeclaredIncludes);
@@ -1441,9 +1442,9 @@ void HeaderSearch::MarkFileModuleHeader(FileEntryRef FE,
   HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
 }
 
-bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
-                                          FileEntryRef File, bool isImport,
-                                          bool ModulesEnabled, Module *M,
+bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, FileEntryRef File,
+                                          bool isImport, bool ModulesEnabled,
+                                          const Module *M,
                                           bool &IsFirstIncludeOfFile) {
   // An include file should be entered if either:
   // 1. This is the first include of the file.
@@ -1936,7 +1937,7 @@ HeaderSearch::loadModuleMapFile(DirectoryEntryRef Dir, bool IsSystem,
   return LMM_InvalidModuleMap;
 }
 
-void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
+void HeaderSearch::collectAllModules(SmallVectorImpl<const Module *> &Modules) {
   Modules.clear();
 
   if (HSOpts->ImplicitModuleMaps) {
diff --git a/clang/lib/Lex/MacroInfo.cpp b/clang/lib/Lex/MacroInfo.cpp
index dfdf463665f3c..293b068e036ca 100644
--- a/clang/lib/Lex/MacroInfo.cpp
+++ b/clang/lib/Lex/MacroInfo.cpp
@@ -256,7 +256,7 @@ LLVM_DUMP_METHOD void MacroDirective::dump() const {
   Out << "\n";
 }
 
-ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
+ModuleMacro *ModuleMacro::create(Preprocessor &PP, const Module *OwningModule,
                                  const IdentifierInfo *II, MacroInfo *Macro,
                                  ArrayRef<ModuleMacro *> Overrides) {
   void *Mem = PP.getPreprocessorAllocator().Allocate(
diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index eed7eca2e7356..0ee20fe8be81e 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -111,7 +111,7 @@ bool ModuleMap::isModular(ModuleHeaderRole Role) {
 }
 
 Module::ExportDecl
-ModuleMap::resolveExport(Module *Mod,
+ModuleMap::resolveExport(const Module *Mod,
                          const Module::UnresolvedExportDecl &Unresolved,
                          bool Complain) const {
   // We may have just a wildcard.
@@ -128,7 +128,7 @@ ModuleMap::resolveExport(Module *Mod,
   return Module::ExportDecl(Context, Unresolved.Wildcard);
 }
 
-Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
+Module *ModuleMap::resolveModuleId(const ModuleId &Id, const Module *Mod,
                                    bool Complain) const {
   // Find the starting module.
   Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
@@ -160,7 +160,7 @@ Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
 
 /// Append to \p Paths the set of paths needed to get to the
 /// subframework in which the given module lives.
-static void appendSubframeworkPaths(Module *Mod,
+static void appendSubframeworkPaths(const Module *Mod,
                                     SmallVectorImpl<char> &Path) {
   // Collect the framework names from the given module to the top-level module.
   SmallVector<StringRef, 2> Paths;
@@ -178,7 +178,7 @@ static void appendSubframeworkPaths(Module *Mod,
 }
 
 OptionalFileEntryRef ModuleMap::findHeader(
-    Module *M, const Module::UnresolvedHeaderDirective &Header,
+    const Module *M, const Module::UnresolvedHeaderDirective &Header,
     SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) {
   // Search for the header file within the module's home directory.
   auto Directory = M->Directory;
@@ -300,7 +300,7 @@ void ModuleMap::resolveHeader(Module *Mod,
           findHeader(Mod, Header, RelativePathName, NeedsFramework)) {
     if (Header.IsUmbrella) {
       const DirectoryEntry *UmbrellaDir = &File->getDir().getDirEntry();
-      if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir])
+      if (const Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir])
         Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
           << UmbrellaMod->getFullModuleName();
       else
@@ -417,8 +417,8 @@ bool ModuleMap::isBuiltinHeader(FileEntryRef File) {
          isBuiltinHeaderName(llvm::sys::path::filename(File.getName()));
 }
 
-bool ModuleMap::shouldImportRelativeToBuiltinIncludeDir(StringRef FileName,
-                                                        Module *Module) const {
+bool ModuleMap::shouldImportRelativeToBuiltinIncludeDir(
+    StringRef FileName, const Module *Module) const {
   return LangOpts.BuiltinHeadersInSystemModules && BuiltinIncludeDir &&
          Module->IsSystem && !Module->isPartOfFramework() &&
          isBuiltinHeaderName(FileName);
@@ -468,7 +468,7 @@ ModuleMap::KnownHeader ModuleMap::findHeaderInUmbrellaDirs(
   return {};
 }
 
-static bool violatesPrivateInclude(Module *RequestingModule,
+static bool violatesPrivateInclude(const Module *RequestingModule,
                                    const FileEntry *IncFileEnt,
                                    ModuleMap::KnownHeader Header) {
 #ifndef NDEBUG
@@ -477,10 +477,10 @@ static bool violatesPrivateInclude(Module *RequestingModule,
     // as obtained from the lookup and as obtained from the module.
     // This check is not cheap, so enable it only for debugging.
     bool IsPrivate = false;
-    SmallVectorImpl<Module::Header> *HeaderList[] = {
+    const SmallVectorImpl<Module::Header> *HeaderList[] = {
         &Header.getModule()->Headers[Module::HK_Private],
         &Header.getModule()->Headers[Module::HK_PrivateTextual]};
-    for (auto *Hs : HeaderList)
+    for (const auto *Hs : HeaderList)
       IsPrivate |= llvm::any_of(
           *Hs, [&](const Module::Header &H) { return H.Entry == IncFileEnt; });
     assert(IsPrivate && "inconsistent headers and roles");
@@ -489,7 +489,7 @@ static bool violatesPrivateInclude(Module *RequestingModule,
   return !Header.isAccessibleFrom(RequestingModule);
 }
 
-static Module *getTopLevelOrNull(Module *M) {
+static const Module *getTopLevelOrNull(const Module *M) {
   return M ? M->getTopLevelModule() : nullptr;
 }
 
@@ -508,8 +508,8 @@ void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
   }
 
   bool Excluded = false;
-  Module *Private = nullptr;
-  Module *NotUsed = nullptr;
+  const Module *Private = nullptr;
+  const Module *NotUsed = nullptr;
 
   HeadersMap::iterator Known = findKnownHeader(File);
   if (Known != Headers.end()) {
@@ -643,7 +643,7 @@ ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File) {
 
     // Search up the module stack until we find a module with an umbrella
     // directory.
-    Module *UmbrellaModule = Result;
+    const Module *UmbrellaModule = Result;
     while (!UmbrellaModule->getEffectiveUmbrellaDir() && UmbrellaModule->Parent)
       UmbrellaModule = UmbrellaModule->Parent;
 
@@ -772,13 +772,13 @@ bool ModuleMap::isHeaderUnavailableInModule(
   do {
     auto KnownDir = UmbrellaDirs.find(*Dir);
     if (KnownDir != UmbrellaDirs.end()) {
-      Module *Found = KnownDir->second;
+      const Module *Found = KnownDir->second;
       if (IsUnavailable(Found))
         return true;
 
       // Search up the module stack until we find a module with an umbrella
       // directory.
-      Module *UmbrellaModule = Found;
+      const Module *UmbrellaModule = Found;
       while (!UmbrellaModule->getEffectiveUmbrellaDir() &&
              UmbrellaModule->Parent)
         UmbrellaModule = UmbrellaModule->Parent;
@@ -832,7 +832,7 @@ Module *ModuleMap::findModule(StringRef Name) const {
 }
 
 Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
-                                           Module *Context) const {
+                                           const Module *Context) const {
   for(; Context; Context = Context->Parent) {
     if (Module *Sub = lookupModuleQualified(Name, Context))
       return Sub;
@@ -841,7 +841,8 @@ Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
   return findModule(Name);
 }
 
-Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
+Module *ModuleMap::lookupModuleQualified(StringRef Name,
+                                         const Module *Context) const {
   if (!Context)
     return findModule(Name);
 
@@ -989,15 +990,16 @@ static void inferFrameworkLink(Module *Mod) {
                                                    /*IsFramework=*/true));
 }
 
-Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
-                                        bool IsSystem, Module *Parent) {
+const Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
+                                              bool IsSystem, Module *Parent) {
   Attributes Attrs;
   Attrs.IsSystem = IsSystem;
   return inferFrameworkModule(FrameworkDir, Attrs, Parent);
 }
 
-Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
-                                        Attributes Attrs, Module *Parent) {
+const Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
+                                              Attributes Attrs,
+                                              Module *Parent) {
   // Note: as an egregious but useful hack we use the real path here, because
   // we might be looking at an embedded framework that symlinks out to a
   // top-level framework, and we need to infer as if we were naming the
@@ -1013,7 +1015,7 @@ Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
       llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
 
   // Check whether we've already found this module.
-  if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
+  if (const Module *Mod = lookupModuleQualified(ModuleName, Parent))
     return Mod;
 
   FileManager &FileMgr = SourceMgr.getFileManager();
@@ -1169,7 +1171,7 @@ Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
 }
 
 Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
-                                        Module *ShadowingModule) {
+                                        const Module *ShadowingModule) {
 
   // Create a new module with this name.
   Module *Result =
@@ -1331,7 +1333,7 @@ ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
   return SourceMgr.getFileEntryRefForID(getModuleMapFileIDForUniquing(M));
 }
 
-void ModuleMap::setInferredModuleAllowedBy(Module *M, FileID ModMapFID) {
+void ModuleMap::setInferredModuleAllowedBy(const Module *M, FileID ModMapFID) {
   assert(M->IsInferred && "module not inferred");
   InferredModuleAllowedBy[M] = ModMapFID;
 }
@@ -1376,10 +1378,8 @@ void ModuleMap::addAdditionalModuleMapFile(const Module *M,
 
 LLVM_DUMP_METHOD void ModuleMap::dump() {
   llvm::errs() << "Modules:";
-  for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
-                                        MEnd = Modules.end();
-       M != MEnd; ++M)
-    M->getValue()->print(llvm::errs(), 2);
+  for (const auto &M : Modules)
+    M.getValue()->print(llvm::errs(), 2);
 
   llvm::errs() << "Headers:";
   for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
@@ -1414,7 +1414,7 @@ bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
   auto Unresolved = std::move(Top->UnresolvedDirectUses);
   Top->UnresolvedDirectUses.clear();
   for (auto &UDU : Unresolved) {
-    Module *DirectUse = resolveModuleId(UDU, Top, Complain);
+    const Module *DirectUse = resolveModuleId(UDU, Top, Complain);
     if (DirectUse)
       Top->DirectUses.push_back(DirectUse);
     else
@@ -1427,7 +1427,7 @@ bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
   auto Unresolved = std::move(Mod->UnresolvedConflicts);
   Mod->UnresolvedConflicts.clear();
   for (auto &UC : Unresolved) {
-    if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
+    if (const Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
       Module::Conflict Conflict;
       Conflict.Other = OtherMod;
       Conflict.Message = UC.Message;
@@ -1555,7 +1555,7 @@ namespace clang {
     /// non-modular headers.  For backwards compatibility, we continue to
     /// support this idiom for just these modules, and map the headers to
     /// 'textual' to match the original intent.
-    llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
+    llvm::SmallPtrSet<const Module *, 2> UsesRequiresExcludedHack;
 
     /// Consume the current token and return its location.
     SourceLocation consumeToken();
@@ -2043,8 +2043,9 @@ void ModuleMapParser::parseModuleDecl() {
   SourceLocation LBraceLoc = consumeToken();
 
   // Determine whether this (sub)module has already been defined.
-  Module *ShadowingModule = nullptr;
-  if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
+  const Module *ShadowingModule = nullptr;
+  if (const Module *Existing =
+          Map.lookupModuleQualified(ModuleName, ActiveModule)) {
     // We might see a (re)definition of a module that we already have a
     // definition for in four cases:
     //  - If we loaded one definition from an AST file and we've just found a
@@ -2312,7 +2313,7 @@ void ModuleMapParser::parseExternModuleDecl() {
 ///
 /// 2. Removes a bogus cplusplus requirement from IOKit.avc.  This requirement
 ///    was never correct and causes issues now that we check it, so drop it.
-static bool shouldAddRequirement(Module *M, StringRef Feature,
+static bool shouldAddRequirement(const Module *M, StringRef Feature,
                                  bool &IsRequiresExcludedHack) {
   if (Feature == "excluded" &&
       (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
@@ -2591,7 +2592,7 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
     return;
   }
 
-  if (Module *OwningModule = Map.UmbrellaDirs[*Dir]) {
+  if (const Module *OwningModule = Map.UmbrellaDirs[*Dir]) {
     Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
       << OwningModule->getFullModuleName();
     HadError = true;
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 8e7386449dced..b1d3735cf7eed 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -880,7 +880,7 @@ Module *Preprocessor::getModuleForLocation(SourceLocation Loc,
 OptionalFileEntryRef
 Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
                                                SourceLocation Loc) {
-  Module *IncM = getModuleForLocation(
+  const Module *IncM = getModuleForLocation(
       IncLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
 
   // Walk up through the include stack, looking through textual headers of M
@@ -1902,7 +1902,7 @@ bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
                                           DiagnosticsEngine &Diags) {
   Module::Requirement Requirement;
   Module::UnresolvedHeaderDirective MissingHeader;
-  Module *ShadowingModule = nullptr;
+  const Module *ShadowingModule = nullptr;
   if (M.isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
                     ShadowingModule))
     return false;
@@ -2296,7 +2296,7 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
     // FIXME: Should we have a second loadModule() overload to avoid this
     // extra lookup step?
     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
-    for (Module *Mod = ModuleToImport; Mod; Mod = Mod->Parent)
+    for (const Module *Mod = ModuleToImport; Mod; Mod = Mod->Parent)
       Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
                                     FilenameTok.getLocation()));
     std::reverse(Path.begin(), Path.end());
@@ -2319,7 +2319,7 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
       Action = Import;
     } else if (Imported.isMissingExpected()) {
       markClangModuleAsAffecting(
-          static_cast<Module *>(Imported)->getTopLevelModule());
+          static_cast<const Module *>(Imported)->getTopLevelModule());
       // We failed to find a submodule that we assumed would exist (because it
       // was in the directory of an umbrella header, for instance), but no
       // actual module containing it exists (because the umbrella header is
diff --git a/clang/lib/Lex/PPLexerChange.cpp b/clang/lib/Lex/PPLexerChange.cpp
index 8221db46e06ac..eeef5288037c7 100644
--- a/clang/lib/Lex/PPLexerChange.cpp
+++ b/clang/lib/Lex/PPLexerChange.cpp
@@ -586,7 +586,7 @@ bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
   // each of the headers within the directory, including all submodules, is
   // covered by the umbrella header was actually included by the umbrella
   // header.
-  if (Module *Mod = getCurrentModule()) {
+  if (const Module *Mod = getCurrentModule()) {
     llvm::SmallVector<const Module *, 4> AllMods;
     collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
     for (auto *M : AllMods)
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp b/clang/lib/Lex/PPMacroExpansion.cpp
index 8af4a97d00cb8..9f8464e996f36 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -129,7 +129,7 @@ void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
     II->setHasMacroDefinition(false);
 }
 
-ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
+ModuleMacro *Preprocessor::addModuleMacro(const Module *Mod, IdentifierInfo *II,
                                           MacroInfo *Macro,
                                           ArrayRef<ModuleMacro *> Overrides,
                                           bool &New) {
@@ -168,7 +168,7 @@ ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
   return MM;
 }
 
-ModuleMacro *Preprocessor::getModuleMacro(Module *Mod,
+ModuleMacro *Preprocessor::getModuleMacro(const Module *Mod,
                                           const IdentifierInfo *II) {
   llvm::FoldingSetNodeID ID;
   ModuleMacro::Profile(ID, Mod, II);
diff --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp
index 10f0ab7180e62..5b7a028888927 100644
--- a/clang/lib/Lex/Pragma.cpp
+++ b/clang/lib/Lex/Pragma.cpp
@@ -1118,7 +1118,7 @@ struct PragmaDebugHandler : public PragmaHandler {
       if (LexModuleName(PP, Tok, ModuleName))
         return;
       ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
-      Module *M = nullptr;
+      const Module *M = nullptr;
       for (auto IIAndLoc : ModuleName) {
         M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
         if (!M) {
@@ -1136,7 +1136,7 @@ struct PragmaDebugHandler : public PragmaHandler {
     } else if (II->isStr("modules")) {
       struct ModuleVisitor {
         Preprocessor &PP;
-        void visit(Module *M, bool VisibleOnly) {
+        void visit(const Module *M, bool VisibleOnly) {
           SourceLocation ImportLoc = PP.getModuleImportLoc(M);
           if (!VisibleOnly || ImportLoc.isValid()) {
             llvm::errs() << M->getFullModuleName() << " ";
@@ -1146,7 +1146,7 @@ struct PragmaDebugHandler : public PragmaHandler {
             }
             llvm::errs() << "\n";
           }
-          for (Module *Sub : M->submodules()) {
+          for (const Module *Sub : M->submodules()) {
             if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
               visit(Sub, VisibleOnly);
           }
diff --git a/clang/lib/Lex/Preprocessor.cpp b/clang/lib/Lex/Preprocessor.cpp
index 0b70192743a39..0ab4e21cf86fa 100644
--- a/clang/lib/Lex/Preprocessor.cpp
+++ b/clang/lib/Lex/Preprocessor.cpp
@@ -530,7 +530,7 @@ Module *Preprocessor::getCurrentModule() {
   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
 }
 
-Module *Preprocessor::getCurrentModuleImplementation() {
+const Module *Preprocessor::getCurrentModuleImplementation() {
   if (!getLangOpts().isCompilingModuleImplementation())
     return nullptr;
 
@@ -1331,8 +1331,9 @@ bool Preprocessor::LexAfterModuleImport(Token &Result) {
 
 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
   CurSubmoduleState->VisibleModules.setVisible(
-      M, Loc, [](Module *) {},
-      [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
+      M, Loc, [](const Module *) {},
+      [&](ArrayRef<const Module *> Path, const Module *Conflict,
+          StringRef Message) {
         // FIXME: Include the path in the diagnostic.
         // FIXME: Include the import location for the conflicting module.
         Diag(ModuleImportLoc, diag::warn_module_conflict)
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index d1fb21bb1ae1d..0b635ea6f8a72 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1232,13 +1232,13 @@ void Sema::ActOnEndOfTranslationUnit() {
   // Now we can decide whether the modules we're building need an initializer.
   if (Module *CurrentModule = getCurrentModule();
       CurrentModule && CurrentModule->isInterfaceOrPartition()) {
-    auto DoesModNeedInit = [this](Module *M) {
+    auto DoesModNeedInit = [this](const Module *M) {
       if (!getASTContext().getModuleInitializers(M).empty())
         return true;
       for (auto [Exported, _] : M->Exports)
         if (Exported->isNamedModuleInterfaceHasInit())
           return true;
-      for (Module *I : M->Imports)
+      for (const Module *I : M->Imports)
         if (I->isNamedModuleInterfaceHasInit())
           return true;
 
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp b/clang/lib/Sema/SemaCodeComplete.cpp
index cd1c5f9391ccd..564ad8b1ec094 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -4382,7 +4382,7 @@ void SemaCodeCompletion::CodeCompleteModuleImport(SourceLocation ImportLoc,
   typedef CodeCompletionResult Result;
   if (Path.empty()) {
     // Enumerate all top-level modules.
-    SmallVector<Module *, 8> Modules;
+    SmallVector<const Module *, 8> Modules;
     SemaRef.PP.getHeaderSearchInfo().collectAllModules(Modules);
     for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
       Builder.AddTypedTextChunk(
@@ -4394,7 +4394,7 @@ void SemaCodeCompletion::CodeCompleteModuleImport(SourceLocation ImportLoc,
     }
   } else if (getLangOpts().Modules) {
     // Load the named module.
-    Module *Mod = SemaRef.PP.getModuleLoader().loadModule(
+    const Module *Mod = SemaRef.PP.getModuleLoader().loadModule(
         ImportLoc, Path, Module::AllVisible,
         /*IsInclusionDirective=*/false);
     // Enumerate submodules.
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 2a87b26f17a2b..b5f4a7f7540c5 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1641,8 +1641,8 @@ bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
     return false;
   }
 
-  Module *NewM = New->getOwningModule();
-  Module *OldM = Old->getOwningModule();
+  const Module *NewM = New->getOwningModule();
+  const Module *OldM = Old->getOwningModule();
 
   if (NewM && NewM->isPrivateModule())
     NewM = NewM->Parent;
@@ -1763,8 +1763,8 @@ bool Sema::IsRedefinitionInModule(const NamedDecl *New,
          const_cast<Sema *>(this)->isReachable(Old) &&
          "We shouldn't see unreachable definitions here.");
 
-  Module *NewM = New->getOwningModule();
-  Module *OldM = Old->getOwningModule();
+  const Module *NewM = New->getOwningModule();
+  const Module *OldM = Old->getOwningModule();
 
   // We only checks for named modules here. The header like modules is skipped.
   // FIXME: This is not right if we import the header like modules in the module
@@ -4775,7 +4775,7 @@ void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
   StringRef HdrFilename =
       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
 
-  auto noteFromModuleOrInclude = [&](Module *Mod,
+  auto noteFromModuleOrInclude = [&](const Module *Mod,
                                      SourceLocation IncLoc) -> bool {
     // Redefinition errors with modules are common with non modular mapped
     // headers, example: a non-modular header H in module A that also gets
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 8ab429e2a136e..37f094807e6c5 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -12141,7 +12141,7 @@ class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
 static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
                                        Sema &S) {
   auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
-  Module *M = ND->getOwningModule();
+  const Module *M = ND->getOwningModule();
   assert(M && "hidden namespace definition not in a module?");
 
   if (M->isExplicitGlobalModule())
@@ -16866,7 +16866,7 @@ Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
   /// If the declaration is already in global module fragment, we don't
   /// need to attach it again.
   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
-    Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
+    const Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
     D->setLocalOwningModule(GlobalModule);
   }
 
diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index ef0a655b631ab..cf583f5e20b60 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -1555,7 +1555,7 @@ void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
 }
 
 /// Find the module in which the given declaration was defined.
-static Module *getDefiningModule(Sema &S, Decl *Entity) {
+static const Module *getDefiningModule(Sema &S, Decl *Entity) {
   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
     // If this function was instantiated from a template, the defining module is
     // the module containing the pattern.
@@ -1580,13 +1580,14 @@ static Module *getDefiningModule(Sema &S, Decl *Entity) {
   return getDefiningModule(S, cast<Decl>(Context));
 }
 
-llvm::DenseSet<Module*> &Sema::getLookupModules() {
+llvm::DenseSet<const Module *> &Sema::getLookupModules() {
   unsigned N = CodeSynthesisContexts.size();
   for (unsigned I = CodeSynthesisContextLookupModules.size();
        I != N; ++I) {
-    Module *M = CodeSynthesisContexts[I].Entity ?
-                getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
-                nullptr;
+    const Module *M =
+        CodeSynthesisContexts[I].Entity
+            ? getDefiningModule(*this, CodeSynthesisContexts[I].Entity)
+            : nullptr;
     if (M && !LookupModulesCache.insert(M).second)
       M = nullptr;
     CodeSynthesisContextLookupModules.push_back(M);
@@ -1697,8 +1698,8 @@ bool Sema::hasReachableDefaultArgument(
 template <typename Filter>
 static bool
 hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
-                             llvm::SmallVectorImpl<Module *> *Modules, Filter F,
-                             Sema::AcceptableKind Kind) {
+                             llvm::SmallVectorImpl<const Module *> *Modules,
+                             Filter F, Sema::AcceptableKind Kind) {
   bool HasFilteredRedecls = false;
 
   for (auto *Redecl : D->redecls()) {
@@ -1722,10 +1723,9 @@ hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
   return true;
 }
 
-static bool
-hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
-                                    llvm::SmallVectorImpl<Module *> *Modules,
-                                    Sema::AcceptableKind Kind) {
+static bool hasAcceptableExplicitSpecialization(
+    Sema &S, const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules,
+    Sema::AcceptableKind Kind) {
   return hasAcceptableDeclarationImpl(
       S, D, Modules,
       [](const NamedDecl *D) {
@@ -1744,21 +1744,20 @@ hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
 }
 
 bool Sema::hasVisibleExplicitSpecialization(
-    const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
+    const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules) {
   return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
                                                Sema::AcceptableKind::Visible);
 }
 
 bool Sema::hasReachableExplicitSpecialization(
-    const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
+    const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules) {
   return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
                                                Sema::AcceptableKind::Reachable);
 }
 
-static bool
-hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
-                                  llvm::SmallVectorImpl<Module *> *Modules,
-                                  Sema::AcceptableKind Kind) {
+static bool hasAcceptableMemberSpecialization(
+    Sema &S, const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules,
+    Sema::AcceptableKind Kind) {
   assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
          "not a member specialization");
   return hasAcceptableDeclarationImpl(
@@ -1778,13 +1777,13 @@ hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
 }
 
 bool Sema::hasVisibleMemberSpecialization(
-    const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
+    const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules) {
   return hasAcceptableMemberSpecialization(*this, D, Modules,
                                            Sema::AcceptableKind::Visible);
 }
 
 bool Sema::hasReachableMemberSpecialization(
-    const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
+    const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules) {
   return hasAcceptableMemberSpecialization(*this, D, Modules,
                                            Sema::AcceptableKind::Reachable);
 }
@@ -1803,7 +1802,7 @@ bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
   assert(!D->isUnconditionallyVisible() &&
          "should not call this: not in slow case");
 
-  Module *DeclModule = SemaRef.getOwningModule(D);
+  const Module *DeclModule = SemaRef.getOwningModule(D);
   assert(DeclModule && "hidden decl has no owning module");
 
   // If the owning module is visible, the decl is acceptable.
@@ -1928,7 +1927,7 @@ bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
 bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
   assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
 
-  Module *DeclModule = SemaRef.getOwningModule(D);
+  const Module *DeclModule = SemaRef.getOwningModule(D);
   assert(DeclModule && "hidden decl has no owning module");
 
   // Entities in header like modules are reachable only if they're visible.
@@ -2050,8 +2049,8 @@ static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
   return nullptr;
 }
 
-bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
-                                     llvm::SmallVectorImpl<Module *> *Modules) {
+bool Sema::hasVisibleDeclarationSlow(
+    const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules) {
   assert(!isVisible(D) && "not in slow case");
   return hasAcceptableDeclarationImpl(
       *this, D, Modules, [](const NamedDecl *) { return true; },
@@ -2059,7 +2058,7 @@ bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
 }
 
 bool Sema::hasReachableDeclarationSlow(
-    const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
+    const NamedDecl *D, llvm::SmallVectorImpl<const Module *> *Modules) {
   assert(!isReachable(D) && "not in slow case");
   return hasAcceptableDeclarationImpl(
       *this, D, Modules, [](const NamedDecl *) { return true; },
@@ -3955,7 +3954,7 @@ void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
             continue;
 
           if (D->isInExportDeclContext()) {
-            Module *FM = D->getOwningModule();
+            const Module *FM = D->getOwningModule();
             // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
             // exports are only valid in module purview and outside of any
             // PMF (although a PMF should not even be present in a module
@@ -5778,7 +5777,7 @@ void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,
 
   // Weed out duplicates from module list.
   llvm::SmallVector<Module*, 8> UniqueModules;
-  llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
+  llvm::SmallDenseSet<const Module *, 8> UniqueModuleSet;
   for (auto *M : Modules) {
     if (M->isExplicitGlobalModule() || M->isPrivateModule())
       continue;
@@ -5816,7 +5815,7 @@ void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,
     if (M->isModuleMapModule())
       return M->getFullModuleName();
 
-    Module *CurrentModule = getCurrentModule();
+    const Module *CurrentModule = getCurrentModule();
 
     if (M->isImplicitGlobalModule())
       M = M->getTopLevelModule();
diff --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index ad118ac90e4aa..1abf52459c851 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -22,7 +22,7 @@
 using namespace clang;
 using namespace sema;
 
-static void checkModuleImportContext(Sema &S, Module *M,
+static void checkModuleImportContext(Sema &S, const Module *M,
                                      SourceLocation ImportLoc, DeclContext *DC,
                                      bool FromInclude = false) {
   SourceLocation ExternCLoc;
@@ -81,9 +81,9 @@ static std::string stringFromPath(ModuleIdPath Path) {
 /// primary module interface unit corresponding to the module \param
 /// CurrentModule. Since currently it is expensive to decide whether two module
 /// units come from the same module by comparing the module name.
-static bool
-isImportingModuleUnitFromSameModule(Module *Imported, Module *CurrentModule,
-                                    Module *&FoundPrimaryModuleInterface) {
+static bool isImportingModuleUnitFromSameModule(
+    const Module *Imported, const Module *CurrentModule,
+    const Module *&FoundPrimaryModuleInterface) {
   if (!Imported->isNamedModule())
     return false;
 
@@ -126,22 +126,22 @@ isImportingModuleUnitFromSameModule(Module *Imported, Module *CurrentModule,
 ///   translation units imported by non-exported module-import-declarations in
 ///   the module unit purview of U. These rules can in turn lead to the
 ///   importation of yet more translation units.
-static void
-makeTransitiveImportsVisible(VisibleModuleSet &VisibleModules, Module *Imported,
-                             Module *CurrentModule, SourceLocation ImportLoc,
-                             bool IsImportingPrimaryModuleInterface = false) {
+static void makeTransitiveImportsVisible(
+    VisibleModuleSet &VisibleModules, const Module *Imported,
+    const Module *CurrentModule, SourceLocation ImportLoc,
+    bool IsImportingPrimaryModuleInterface = false) {
   assert(Imported->isNamedModule() &&
          "'makeTransitiveImportsVisible()' is intended for standard C++ named "
          "modules only.");
 
-  llvm::SmallVector<Module *, 4> Worklist;
+  llvm::SmallVector<const Module *, 4> Worklist;
   Worklist.push_back(Imported);
 
-  Module *FoundPrimaryModuleInterface =
+  const Module *FoundPrimaryModuleInterface =
       IsImportingPrimaryModuleInterface ? Imported : nullptr;
 
   while (!Worklist.empty()) {
-    Module *Importing = Worklist.pop_back_val();
+    const Module *Importing = Worklist.pop_back_val();
 
     if (VisibleModules.isVisible(Importing))
       continue;
@@ -152,7 +152,7 @@ makeTransitiveImportsVisible(VisibleModuleSet &VisibleModules, Module *Imported,
 
     if (isImportingModuleUnitFromSameModule(Importing, CurrentModule,
                                             FoundPrimaryModuleInterface))
-      for (Module *TransImported : Importing->Imports)
+      for (const Module *TransImported : Importing->Imports)
         if (!VisibleModules.isVisible(TransImported))
           Worklist.push_back(TransImported);
   }
@@ -161,8 +161,7 @@ makeTransitiveImportsVisible(VisibleModuleSet &VisibleModules, Module *Imported,
 Sema::DeclGroupPtrTy
 Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
   // We start in the global module;
-  Module *GlobalModule =
-      PushGlobalModuleFragment(ModuleLoc);
+  const Module *GlobalModule = PushGlobalModuleFragment(ModuleLoc);
 
   // All declarations created from now on are owned by the global module.
   auto *TU = Context.getTranslationUnitDecl();
@@ -584,7 +583,7 @@ DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
   if (IsPartition) {
     // We already checked that we are in a module purview in the parser.
     assert(!ModuleScopes.empty() && "in a module purview, but no module?");
-    Module *NamedMod = ModuleScopes.back().Module;
+    const Module *NamedMod = ModuleScopes.back().Module;
     // If we are importing into a partition, find the owning named module,
     // otherwise, the name of the importing named module.
     ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
@@ -667,13 +666,13 @@ DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
     // If this was a header import, pad out with dummy locations.
     // FIXME: Pass in and use the location of the header-name token in this
     // case.
-    for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
+    for (const Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
       IdentifierLocs.push_back(SourceLocation());
   } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
     // A single identifier for the whole name.
     IdentifierLocs.push_back(Path[0].second);
   } else {
-    Module *ModCheck = Mod;
+    const Module *ModCheck = Mod;
     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
       // If we've run out of module parents, just drop the remaining
       // identifiers.  We need the length to be consistent.
@@ -749,7 +748,7 @@ void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
   VisibleModules.setVisible(Mod, DirectiveLoc);
 
   if (getLangOpts().isCompilingModule()) {
-    Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
+    const Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
         getLangOpts().CurrentModule, DirectiveLoc, false, false);
     (void)ThisModule;
     assert(ThisModule && "was expecting a module if building one");
@@ -1010,7 +1009,7 @@ Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
   return D;
 }
 
-Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
+const Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
   // We shouldn't create new global module fragment if there is already
   // one.
   if (!TheGlobalModuleFragment) {
@@ -1036,7 +1035,7 @@ void Sema::PopGlobalModuleFragment() {
   ModuleScopes.pop_back();
 }
 
-Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
+const Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc) {
   if (!TheImplicitGlobalModuleFragment) {
     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
     TheImplicitGlobalModuleFragment =
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 6c5e8afbcfb6e..dd1dfa735f63e 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10808,12 +10808,12 @@ void Sema::diagnoseEquivalentInternalLinkageDeclarations(
   assert(D && "Unknown declaration");
   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
 
-  Module *M = getOwningModule(D);
+  const Module *M = getOwningModule(D);
   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
       << !M << (M ? M->getFullModuleName() : "");
 
   for (auto *E : Equiv) {
-    Module *M = getOwningModule(E);
+    const Module *M = getOwningModule(E);
     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
         << !M << (M ? M->getFullModuleName() : "");
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index abb8a260faab9..748d5ad0297b9 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -861,7 +861,7 @@ void Sema::popCodeSynthesisContext() {
          "forgot to remove a lookup module for a template instantiation");
   if (CodeSynthesisContexts.size() ==
       CodeSynthesisContextLookupModules.size()) {
-    if (Module *M = CodeSynthesisContextLookupModules.back())
+    if (const Module *M = CodeSynthesisContextLookupModules.back())
       LookupModulesCache.erase(M);
     CodeSynthesisContextLookupModules.pop_back();
   }
diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp
index 4a6e1d23161be..be1cccbef6fb7 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -552,8 +552,8 @@ static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
 }
 
 /// Return the top import module if it is implicit, nullptr otherwise.
-static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
-                                          Preprocessor &PP) {
+static const Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
+                                                Preprocessor &PP) {
   // If the original import came from a file explicitly generated by the user,
   // don't check the diagnostic mappings.
   // FIXME: currently this is approximated by checking whether this is not a
@@ -570,7 +570,7 @@ static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
   StringRef ModuleName = TopImport->ModuleName;
   assert(!ModuleName.empty() && "diagnostic options read before module name");
 
-  Module *M =
+  const Module *M =
       PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
   assert(M && "missing module");
   return M;
@@ -589,11 +589,11 @@ bool PCHValidator::ReadDiagnosticOptions(
   ModuleManager &ModuleMgr = Reader.getModuleManager();
   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
 
-  Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
+  const Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
   if (!TopM)
     return false;
 
-  Module *Importer = PP.getCurrentModule();
+  const Module *Importer = PP.getCurrentModule();
 
   DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
   bool SystemHeaderWarningsInModule =
@@ -2329,14 +2329,14 @@ void ASTReader::resolvePendingMacro(IdentifierInfo *II,
     for (auto &MMR : ModuleMacros) {
       Overrides.clear();
       for (unsigned ModID : MMR.Overrides) {
-        Module *Mod = getSubmodule(ModID);
+        const Module *Mod = getSubmodule(ModID);
         auto *Macro = PP.getModuleMacro(Mod, II);
         assert(Macro && "missing definition for overridden macro");
         Overrides.push_back(Macro);
       }
 
       bool Inserted = false;
-      Module *Owner = getSubmodule(MMR.SubModID);
+      const Module *Owner = getSubmodule(MMR.SubModID);
       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
     }
   }
@@ -3153,7 +3153,7 @@ ASTReader::ReadControlBlock(ModuleFile &F,
         break;
       // If we've already loaded a module map file covering this module, we may
       // have a better path for it (relative to the current build).
-      Module *M = PP.getHeaderSearchInfo().lookupModule(
+      const Module *M = PP.getHeaderSearchInfo().lookupModule(
           F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
           /*AllowExtraModuleMapSearch*/ true);
       if (M && M->Directory) {
@@ -4139,7 +4139,7 @@ ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
       F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
     // An implicitly-loaded module file should have its module listed in some
     // module map file that we've already loaded.
-    Module *M =
+    const Module *M =
         PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
     OptionalFileEntryRef ModMap =
@@ -4258,7 +4258,8 @@ static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
   }
 }
 
-void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
+void ASTReader::makeNamesVisible(const HiddenNames &Names,
+                                 const Module *Owner) {
   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
   for (Decl *D : Names) {
     bool wasHidden = !D->isUnconditionallyVisible();
@@ -4275,7 +4276,7 @@ void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
 void ASTReader::makeModuleVisible(Module *Mod,
                                   Module::NameVisibilityKind NameVisibility,
                                   SourceLocation ImportLoc) {
-  llvm::SmallPtrSet<Module *, 4> Visited;
+  llvm::SmallPtrSet<const Module *, 4> Visited;
   SmallVector<Module *, 4> Stack;
   Stack.push_back(Mod);
   while (!Stack.empty()) {
@@ -4309,9 +4310,7 @@ void ASTReader::makeModuleVisible(Module *Mod,
     // Push any exported modules onto the stack to be marked as visible.
     SmallVector<Module *, 16> Exports;
     Mod->getExportedModules(Exports);
-    for (SmallVectorImpl<Module *>::iterator
-           I = Exports.begin(), E = Exports.end(); I != E; ++I) {
-      Module *Exported = *I;
+    for (Module *Exported : Exports) {
       if (Visited.insert(Exported).second)
         Stack.push_back(Exported);
     }
@@ -8322,7 +8321,7 @@ void ASTReader::UpdateSema() {
   for (auto &Import : PendingImportedModulesSema) {
     if (Import.ImportLoc.isInvalid())
       continue;
-    if (Module *Imported = getSubmodule(Import.ID)) {
+    if (const Module *Imported = getSubmodule(Import.ID)) {
       SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
     }
   }
@@ -9019,7 +9018,7 @@ unsigned ASTReader::getModuleFileID(ModuleFile *M) {
 }
 
 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
-  if (Module *M = getSubmodule(ID))
+  if (const Module *M = getSubmodule(ID))
     return ASTSourceDescriptor(*M);
 
   // If there is only a single PCH, return it instead.
diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp b/clang/lib/Serialization/ASTReaderDecl.cpp
index 61cc99d4df687..ec36d7c6ef054 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -661,7 +661,7 @@ void ASTDeclReader::VisitDecl(Decl *D) {
     } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
       // If local visibility is being tracked, this declaration will become
       // hidden and visible as the owning module does.
-    } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
+    } else if (const Module *Owner = Reader.getSubmodule(SubmoduleID)) {
       // Mark the declaration as visible when its owning module becomes visible.
       if (Owner->NameVisibility == Module::AllVisible)
         D->setVisibleDespiteOwningModule();
diff --git a/clang/lib/Serialization/ASTWriter.cpp b/clang/lib/Serialization/ASTWriter.cpp
index 00b0e48083217..1cb44dba3e62f 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -166,7 +166,7 @@ static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
 namespace {
 
 std::optional<std::set<const FileEntry *>>
-GetAffectingModuleMaps(const Preprocessor &PP, Module *RootModule) {
+GetAffectingModuleMaps(const Preprocessor &PP, const Module *RootModule) {
   if (!PP.getHeaderSearchInfo()
            .getHeaderSearchOpts()
            .ModulesPruneNonAffectingModuleMaps)
@@ -1223,7 +1223,7 @@ ASTFileSignature ASTWriter::createSignatureForNamedModule() const {
   // Probably we can solve this by a new hash mechanism. But the safety and
   // efficiency may a problem too. Here we just combine the hash value of the
   // used modules conservatively.
-  for (Module *M : TouchedTopLevelModules)
+  for (const Module *M : TouchedTopLevelModules)
     Hasher.update(M->Signature);
 
   return ASTFileSignature::create(Hasher.result());
@@ -1967,7 +1967,7 @@ namespace {
     using key_type_ref = const key_type &;
 
     using UnresolvedModule =
-        llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
+        llvm::PointerIntPair<const Module *, 2, ModuleMap::ModuleHeaderRole>;
 
     struct data_type {
       const HeaderFileInfo &HFI;
@@ -2046,7 +2046,7 @@ namespace {
       }
       LE.write<uint32_t>(Offset);
 
-      auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
+      auto EmitModule = [&](const Module *M, ModuleMap::ModuleHeaderRole Role) {
         if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
           uint32_t Value = (ModID << 3) | (unsigned)Role;
           assert((Value >> 3) == ModID && "overflow in header module info");
@@ -2859,7 +2859,7 @@ unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
   return SubmoduleIDs[Mod] = NextSubmoduleID++;
 }
 
-unsigned ASTWriter::getSubmoduleID(Module *Mod) {
+unsigned ASTWriter::getSubmoduleID(const Module *Mod) {
   unsigned ID = getLocalOrImportedSubmoduleID(Mod);
   // FIXME: This can easily happen, if we have a reference to a submodule that
   // did not result in us loading a module file for that submodule. For
@@ -2871,7 +2871,7 @@ unsigned ASTWriter::getSubmoduleID(Module *Mod) {
 
 /// Compute the number of modules within the given tree (including the
 /// given module).
-static unsigned getNumberOfModules(Module *Mod) {
+static unsigned getNumberOfModules(const Module *Mod) {
   unsigned ChildModules = 0;
   for (auto *Submodule : Mod->submodules())
     ChildModules += getNumberOfModules(Submodule);
@@ -5458,8 +5458,8 @@ ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
     // Write the submodules that were imported, if any.
     struct ModuleInfo {
       uint64_t ID;
-      Module *M;
-      ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
+      const Module *M;
+      ModuleInfo(uint64_t ID, const Module *M) : ID(ID), M(M) {}
     };
     llvm::SmallVector<ModuleInfo, 64> Imports;
     for (const auto *I : Context.local_imports()) {
@@ -6661,7 +6661,7 @@ void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
   MacroDefinitions[MD] = ID;
 }
 
-void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
+void ASTWriter::ModuleRead(serialization::SubmoduleID ID, const Module *Mod) {
   assert(!SubmoduleIDs.contains(Mod));
   SubmoduleIDs[Mod] = ID;
 }
@@ -6900,7 +6900,7 @@ void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
       DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
 }
 
-void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
+void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, const Module *M) {
   if (Chain && Chain->isProcessingUpdateRecords()) return;
   assert(!WritingAST && "Already writing the AST!");
   assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp b/clang/lib/Serialization/ASTWriterDecl.cpp
index bbd16dbdb8fff..a6a30ec1bf9d8 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2768,7 +2768,7 @@ void ASTWriter::WriteDeclAbbrevs() {
 /// relatively painless since they would presumably only do it for top-level
 /// decls.
 static bool isRequiredDecl(const Decl *D, ASTContext &Context,
-                           Module *WritingModule) {
+                           const Module *WritingModule) {
   // Named modules have different semantics than header modules. Every named
   // module units owns a translation unit. So the importer of named modules
   // doesn't need to deserilize everything ahead of time.
diff --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index f46324ee9989e..337dbcd456add 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -362,7 +362,7 @@ void ModuleDepCollector::applyDiscoveredDependencies(CompilerInvocation &CI) {
 
   if (llvm::any_of(CI.getFrontendOpts().Inputs, needsModules)) {
     Preprocessor &PP = ScanInstance.getPreprocessor();
-    if (Module *CurrentModule = PP.getCurrentModuleImplementation())
+    if (const Module *CurrentModule = PP.getCurrentModuleImplementation())
       if (OptionalFileEntryRef CurrentModuleMap =
               PP.getHeaderSearchInfo()
                   .getModuleMap()
diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 49ed60d990ca6..b9b53d8f1e9ed 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -5084,7 +5084,7 @@ static CXString getDeclSpelling(const Decl *D) {
         return cxstring::createDup(Property->getIdentifier()->getName());
 
     if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
-      if (Module *Mod = ImportD->getImportedModule())
+      if (const Module *Mod = ImportD->getImportedModule())
         return cxstring::createDup(Mod->getFullModuleName());
 
     return cxstring::createEmpty();
@@ -9016,35 +9016,35 @@ CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
 CXFile clang_Module_getASTFile(CXModule CXMod) {
   if (!CXMod)
     return nullptr;
-  Module *Mod = static_cast<Module *>(CXMod);
+  const Module *Mod = static_cast<const Module *>(CXMod);
   return cxfile::makeCXFile(Mod->getASTFile());
 }
 
 CXModule clang_Module_getParent(CXModule CXMod) {
   if (!CXMod)
     return nullptr;
-  Module *Mod = static_cast<Module *>(CXMod);
+  const Module *Mod = static_cast<const Module *>(CXMod);
   return Mod->Parent;
 }
 
 CXString clang_Module_getName(CXModule CXMod) {
   if (!CXMod)
     return cxstring::createEmpty();
-  Module *Mod = static_cast<Module *>(CXMod);
+  const Module *Mod = static_cast<const Module *>(CXMod);
   return cxstring::createDup(Mod->Name);
 }
 
 CXString clang_Module_getFullName(CXModule CXMod) {
   if (!CXMod)
     return cxstring::createEmpty();
-  Module *Mod = static_cast<Module *>(CXMod);
+  const Module *Mod = static_cast<const Module *>(CXMod);
   return cxstring::createDup(Mod->getFullModuleName());
 }
 
 int clang_Module_isSystem(CXModule CXMod) {
   if (!CXMod)
     return 0;
-  Module *Mod = static_cast<Module *>(CXMod);
+  const Module *Mod = static_cast<const Module *>(CXMod);
   return Mod->IsSystem;
 }
 
diff --git a/clang/tools/libclang/CXIndexDataConsumer.cpp b/clang/tools/libclang/CXIndexDataConsumer.cpp
index c1022263a5128..bc46214d795d5 100644
--- a/clang/tools/libclang/CXIndexDataConsumer.cpp
+++ b/clang/tools/libclang/CXIndexDataConsumer.cpp
@@ -493,7 +493,7 @@ void CXIndexDataConsumer::importedModule(const ImportDecl *ImportD) {
   // indexing, it doesn't correspond to an imported AST file.
   // FIXME: This assumes that AST files and top-level modules directly
   // correspond, which is unlikely to remain true forever.
-  if (Module *SrcMod = ImportD->getImportedOwningModule())
+  if (const Module *SrcMod = ImportD->getImportedOwningModule())
     if (SrcMod->getTopLevelModule() == Mod->getTopLevelModule())
       return;
 
diff --git a/clang/unittests/Sema/SemaNoloadLookupTest.cpp b/clang/unittests/Sema/SemaNoloadLookupTest.cpp
index cf89c7331e4e0..306e197540137 100644
--- a/clang/unittests/Sema/SemaNoloadLookupTest.cpp
+++ b/clang/unittests/Sema/SemaNoloadLookupTest.cpp
@@ -117,7 +117,7 @@ class NoloadLookupConsumer : public SemaConsumer {
     if (!ID)
       return true;
 
-    clang::Module *M = ID->getImportedModule();
+    const clang::Module *M = ID->getImportedModule();
     assert(M);
     if (M->Name != "R")
       return true;



More information about the cfe-commits mailing list