Author: James Y Knight
Date: 2025-08-01T22:23:30-04:00
New Revision: 4205da0f130cf86ae6b89bfc36723e7ddba9b0b7

URL: 
https://github.com/llvm/llvm-project/commit/4205da0f130cf86ae6b89bfc36723e7ddba9b0b7
DIFF: 
https://github.com/llvm/llvm-project/commit/4205da0f130cf86ae6b89bfc36723e7ddba9b0b7.diff

LOG: NFC: Clean up of IntrusiveRefCntPtr construction from raw pointers. 
(#151782)

This commit handles the following types:
- clang::ExternalASTSource
- clang::TargetInfo
- clang::ASTContext
- clang::SourceManager
- clang::FileManager

Part of cleanup #151026

Added: 
    

Modified: 
    clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
    clang/include/clang/AST/ASTContext.h
    clang/include/clang/Frontend/ASTUnit.h
    clang/include/clang/Frontend/CompilerInstance.h
    clang/include/clang/Frontend/Utils.h
    clang/include/clang/Sema/MultiplexExternalSemaSource.h
    clang/include/clang/Sema/Sema.h
    clang/lib/Frontend/ASTUnit.cpp
    clang/lib/Frontend/ChainedIncludesSource.cpp
    clang/lib/Frontend/CompilerInstance.cpp
    clang/lib/Frontend/FrontendAction.cpp
    clang/lib/Frontend/PrecompiledPreamble.cpp
    clang/lib/Interpreter/CodeCompletion.cpp
    clang/lib/Sema/MultiplexExternalSemaSource.cpp
    clang/lib/Sema/Sema.cpp
    clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
    clang/lib/Tooling/Tooling.cpp
    clang/tools/clang-installapi/ClangInstallAPI.cpp
    clang/tools/libclang/CIndexCodeCompletion.cpp
    clang/tools/libclang/CXIndexDataConsumer.cpp
    clang/tools/libclang/CXIndexDataConsumer.h
    clang/tools/libclang/Indexing.cpp
    clang/unittests/AST/ASTImporterTest.cpp
    clang/unittests/AST/ExternalASTSourceTest.cpp
    clang/unittests/Frontend/ASTUnitTest.cpp
    clang/unittests/Frontend/FrontendActionTest.cpp
    clang/unittests/Frontend/PCHPreambleTest.cpp
    clang/unittests/Frontend/ReparseWorkingDirTest.cpp
    clang/unittests/Sema/ExternalSemaSourceTest.cpp
    clang/unittests/Support/TimeProfilerTest.cpp
    clang/unittests/Tooling/Syntax/TokensTest.cpp
    clang/unittests/Tooling/Syntax/TreeTestBase.cpp
    clang/unittests/Tooling/Syntax/TreeTestBase.h
    clang/unittests/Tooling/ToolingTest.cpp
    lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp
    lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h
    lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h
    lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
    
lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp
    lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
    lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h

Removed: 
    


################################################################################
diff  --git a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp 
b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
index 7b0e4ecda8214..30bb313524cbe 100644
--- a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
+++ b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
@@ -53,7 +53,7 @@ class Action : public clang::ASTFrontendAction {
 
     Compiler->createSema(getTranslationUnitKind(), CompletionConsumer);
     SemaSource->setCompilerInstance(Compiler);
-    Compiler->getSema().addExternalSource(SemaSource.get());
+    Compiler->getSema().addExternalSource(SemaSource);
 
     clang::ParseAST(Compiler->getSema(), Compiler->getFrontendOpts().ShowStats,
                     Compiler->getFrontendOpts().SkipFunctionBodies);

diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 3b98274a80420..db86963bdf80e 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1335,6 +1335,12 @@ class ASTContext : public RefCountedBase<ASTContext> {
     return ExternalSource.get();
   }
 
+  /// Retrieve a pointer to the external AST source associated
+  /// with this AST context, if any. Returns as an IntrusiveRefCntPtr.
+  IntrusiveRefCntPtr<ExternalASTSource> getExternalSourcePtr() const {
+    return ExternalSource;
+  }
+
   /// Attach an AST mutation listener to the AST context.
   ///
   /// The AST mutation listener provides the ability to track modifications to

diff  --git a/clang/include/clang/Frontend/ASTUnit.h 
b/clang/include/clang/Frontend/ASTUnit.h
index 7dd9aeff12217..ad54016da11d2 100644
--- a/clang/include/clang/Frontend/ASTUnit.h
+++ b/clang/include/clang/Frontend/ASTUnit.h
@@ -451,6 +451,9 @@ class ASTUnit {
 
   const SourceManager &getSourceManager() const { return *SourceMgr; }
   SourceManager &getSourceManager() { return *SourceMgr; }
+  llvm::IntrusiveRefCntPtr<SourceManager> getSourceManagerPtr() {
+    return SourceMgr;
+  }
 
   const Preprocessor &getPreprocessor() const { return *PP; }
   Preprocessor &getPreprocessor() { return *PP; }
@@ -458,8 +461,11 @@ class ASTUnit {
 
   const ASTContext &getASTContext() const { return *Ctx; }
   ASTContext &getASTContext() { return *Ctx; }
+  llvm::IntrusiveRefCntPtr<ASTContext> getASTContextPtr() { return Ctx; }
 
-  void setASTContext(ASTContext *ctx) { Ctx = ctx; }
+  void setASTContext(llvm::IntrusiveRefCntPtr<ASTContext> ctx) {
+    Ctx = std::move(ctx);
+  }
   void setPreprocessor(std::shared_ptr<Preprocessor> pp);
 
   /// Enable source-range based diagnostic messages.
@@ -495,6 +501,7 @@ class ASTUnit {
 
   const FileManager &getFileManager() const { return *FileMgr; }
   FileManager &getFileManager() { return *FileMgr; }
+  IntrusiveRefCntPtr<FileManager> getFileManagerPtr() { return FileMgr; }
 
   const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
 
@@ -803,8 +810,8 @@ class ASTUnit {
       std::shared_ptr<CompilerInvocation> CI,
       std::shared_ptr<PCHContainerOperations> PCHContainerOps,
       std::shared_ptr<DiagnosticOptions> DiagOpts,
-      IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
-      bool OnlyLocalDecls = false,
+      IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+      IntrusiveRefCntPtr<FileManager> FileMgr, bool OnlyLocalDecls = false,
       CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None,
       unsigned PrecompilePreambleAfterNParses = 0,
       TranslationUnitKind TUKind = TU_Complete,
@@ -922,8 +929,9 @@ class ASTUnit {
                     CodeCompleteConsumer &Consumer,
                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
                     llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diag,
-                    LangOptions &LangOpts, SourceManager &SourceMgr,
-                    FileManager &FileMgr,
+                    LangOptions &LangOpts,
+                    llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr,
+                    llvm::IntrusiveRefCntPtr<FileManager> FileMgr,
                     SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
                     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers,
                     std::unique_ptr<SyntaxOnlyAction> Act);

diff  --git a/clang/include/clang/Frontend/CompilerInstance.h 
b/clang/include/clang/Frontend/CompilerInstance.h
index a24decd620a65..64ebb70a6a24c 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -446,7 +446,7 @@ class CompilerInstance : public ModuleLoader {
   }
 
   /// Replace the current file manager and virtual file system.
-  void setFileManager(FileManager *Value);
+  void setFileManager(IntrusiveRefCntPtr<FileManager> Value);
 
   /// @}
   /// @name Source Manager
@@ -471,7 +471,7 @@ class CompilerInstance : public ModuleLoader {
   }
 
   /// setSourceManager - Replace the current source manager.
-  void setSourceManager(SourceManager *Value);
+  void setSourceManager(llvm::IntrusiveRefCntPtr<SourceManager> Value);
 
   /// @}
   /// @name Preprocessor
@@ -516,7 +516,7 @@ class CompilerInstance : public ModuleLoader {
   }
 
   /// setASTContext - Replace the current AST context.
-  void setASTContext(ASTContext *Value);
+  void setASTContext(llvm::IntrusiveRefCntPtr<ASTContext> Value);
 
   /// Replace the current Sema; the compiler instance takes ownership
   /// of S.

diff  --git a/clang/include/clang/Frontend/Utils.h 
b/clang/include/clang/Frontend/Utils.h
index 604e42067a3f1..f86c2f5074de0 100644
--- a/clang/include/clang/Frontend/Utils.h
+++ b/clang/include/clang/Frontend/Utils.h
@@ -189,7 +189,7 @@ void AttachHeaderIncludeGen(Preprocessor &PP,
 /// memory, mainly for testing.
 IntrusiveRefCntPtr<ExternalSemaSource>
 createChainedIncludesSource(CompilerInstance &CI,
-                            IntrusiveRefCntPtr<ExternalSemaSource> &Reader);
+                            IntrusiveRefCntPtr<ASTReader> &OutReader);
 
 /// Optional inputs to createInvocation.
 struct CreateInvocationOptions {

diff  --git a/clang/include/clang/Sema/MultiplexExternalSemaSource.h 
b/clang/include/clang/Sema/MultiplexExternalSemaSource.h
index 391c2177d75ec..8bcaa121b3039 100644
--- a/clang/include/clang/Sema/MultiplexExternalSemaSource.h
+++ b/clang/include/clang/Sema/MultiplexExternalSemaSource.h
@@ -40,7 +40,7 @@ class MultiplexExternalSemaSource : public ExternalSemaSource 
{
   static char ID;
 
 private:
-  SmallVector<ExternalSemaSource *, 2> Sources;
+  SmallVector<llvm::IntrusiveRefCntPtr<ExternalSemaSource>, 2> Sources;
 
 public:
   /// Constructs a new multiplexing external sema source and appends the
@@ -49,15 +49,14 @@ class MultiplexExternalSemaSource : public 
ExternalSemaSource {
   ///\param[in] S1 - A non-null (old) ExternalSemaSource.
   ///\param[in] S2 - A non-null (new) ExternalSemaSource.
   ///
-  MultiplexExternalSemaSource(ExternalSemaSource *S1, ExternalSemaSource *S2);
-
-  ~MultiplexExternalSemaSource() override;
+  MultiplexExternalSemaSource(llvm::IntrusiveRefCntPtr<ExternalSemaSource> S1,
+                              llvm::IntrusiveRefCntPtr<ExternalSemaSource> S2);
 
   /// Appends new source to the source list.
   ///
   ///\param[in] Source - An ExternalSemaSource.
   ///
-  void AddSource(ExternalSemaSource *Source);
+  void AddSource(llvm::IntrusiveRefCntPtr<ExternalSemaSource> Source);
 
   
//===--------------------------------------------------------------------===//
   // ExternalASTSource.

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 423dcf9e2b708..0b2c027e6da67 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -927,7 +927,7 @@ class Sema final : public SemaBase {
   ///
   ///\param[in] E - A non-null external sema source.
   ///
-  void addExternalSource(ExternalSemaSource *E);
+  void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
 
   /// Print out statistics about the semantic analysis.
   void PrintStats() const;

diff  --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index 5711f454a9c9e..a4078257a889f 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -831,11 +831,10 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
   AST->CaptureDiagnostics = CaptureDiagnostics;
   AST->DiagOpts = DiagOpts;
   AST->Diagnostics = Diags;
-  AST->FileMgr = new FileManager(FileSystemOpts, VFS);
+  AST->FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOpts, VFS);
   AST->UserFilesAreVolatile = UserFilesAreVolatile;
-  AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
-                                     AST->getFileManager(),
-                                     UserFilesAreVolatile);
+  AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
+      AST->getDiagnostics(), AST->getFileManager(), UserFilesAreVolatile);
   AST->ModCache = createCrossProcessModuleCache();
   AST->HSOpts = std::make_unique<HeaderSearchOptions>(HSOpts);
   AST->HSOpts->ModuleFormat = 
std::string(PCHContainerRdr.getFormats().front());
@@ -858,20 +857,20 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
   Preprocessor &PP = *AST->PP;
 
   if (ToLoad >= LoadASTOnly)
-    AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
-                              PP.getIdentifierTable(), PP.getSelectorTable(),
-                              PP.getBuiltinInfo(),
-                              AST->getTranslationUnitKind());
+    AST->Ctx = llvm::makeIntrusiveRefCnt<ASTContext>(
+        *AST->LangOpts, AST->getSourceManager(), PP.getIdentifierTable(),
+        PP.getSelectorTable(), PP.getBuiltinInfo(),
+        AST->getTranslationUnitKind());
 
   DisableValidationForModuleKind disableValid =
       DisableValidationForModuleKind::None;
   if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
     disableValid = DisableValidationForModuleKind::All;
-  AST->Reader = new ASTReader(PP, *AST->ModCache, AST->Ctx.get(),
-                              PCHContainerRdr, *AST->CodeGenOpts, {},
-                              /*isysroot=*/"",
-                              /*DisableValidationKind=*/disableValid,
-                              AllowASTWithCompilerErrors);
+  AST->Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
+      PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr, *AST->CodeGenOpts,
+      ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
+      /*isysroot=*/"",
+      /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors);
 
   unsigned Counter = 0;
   AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
@@ -1191,9 +1190,11 @@ bool 
ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
   // changed above in AddImplicitPreamble.  If VFS is nullptr, rely on
   // createFileManager to create one.
   if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
-    Clang->setFileManager(&*FileMgr);
-  else
-    FileMgr = Clang->createFileManager(std::move(VFS));
+    Clang->setFileManager(FileMgr);
+  else {
+    Clang->createFileManager(std::move(VFS));
+    FileMgr = Clang->getFileManagerPtr();
+  }
 
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
@@ -1226,15 +1227,15 @@ bool 
ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
 
   ResetForParse();
 
-  SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
-                                UserFilesAreVolatile);
+  SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
+      getDiagnostics(), *FileMgr, +UserFilesAreVolatile);
   if (!OverrideMainBuffer) {
     checkAndRemoveNonDriverDiags(StoredDiagnostics);
     TopLevelDeclsInPreamble.clear();
   }
 
   // Create the source manager.
-  Clang->setSourceManager(&getSourceManager());
+  Clang->setSourceManager(getSourceManagerPtr());
 
   // If the main file has been overridden due to the use of a preamble,
   // make that override happen and introduce the preamble.
@@ -1499,13 +1500,13 @@ void 
ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
   TheSema = CI.takeSema();
   Consumer = CI.takeASTConsumer();
   if (CI.hasASTContext())
-    Ctx = &CI.getASTContext();
+    Ctx = CI.getASTContextPtr();
   if (CI.hasPreprocessor())
     PP = CI.getPreprocessorPtr();
   CI.setSourceManager(nullptr);
   CI.setFileManager(nullptr);
   if (CI.hasTarget())
-    Target = &CI.getTarget();
+    Target = CI.getTargetPtr();
   Reader = CI.getASTReader();
   HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
   if (Invocation != CI.getInvocationPtr()) {
@@ -1555,10 +1556,11 @@ ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
   AST->Diagnostics = Diags;
   AST->FileSystemOpts = CI->getFileSystemOpts();
   AST->Invocation = std::move(CI);
-  AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
+  AST->FileMgr =
+      llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
   AST->UserFilesAreVolatile = UserFilesAreVolatile;
-  AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
-                                     UserFilesAreVolatile);
+  AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
+      AST->getDiagnostics(), *AST->FileMgr, UserFilesAreVolatile);
   AST->ModCache = createCrossProcessModuleCache();
 
   return AST;
@@ -1646,10 +1648,10 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
   AST->Reader = nullptr;
 
   // Create a file manager object to provide access to and cache the 
filesystem.
-  Clang->setFileManager(&AST->getFileManager());
+  Clang->setFileManager(AST->getFileManagerPtr());
 
   // Create the source manager.
-  Clang->setSourceManager(&AST->getSourceManager());
+  Clang->setSourceManager(AST->getSourceManagerPtr());
 
   FrontendAction *Act = Action;
 
@@ -1743,8 +1745,9 @@ std::unique_ptr<ASTUnit> 
ASTUnit::LoadFromCompilerInvocation(
     std::shared_ptr<CompilerInvocation> CI,
     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
     std::shared_ptr<DiagnosticOptions> DiagOpts,
-    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
-    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
+    IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+    IntrusiveRefCntPtr<FileManager> FileMgr, bool OnlyLocalDecls,
+    CaptureDiagsKind CaptureDiagnostics,
     unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
     bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
     bool UserFilesAreVolatile) {
@@ -1849,7 +1852,8 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromCommandLine(
   AST->FileSystemOpts = CI->getFileSystemOpts();
   AST->CodeGenOpts = std::make_unique<CodeGenOptions>(CI->getCodeGenOpts());
   VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
-  AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
+  AST->FileMgr =
+      llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
   AST->StorePreamblesInMemory = StorePreamblesInMemory;
   AST->PreambleStoragePath = PreambleStoragePath;
   AST->ModCache = createCrossProcessModuleCache();
@@ -2210,7 +2214,8 @@ void ASTUnit::CodeComplete(
     CodeCompleteConsumer &Consumer,
     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
     llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diag, LangOptions &LangOpts,
-    SourceManager &SourceMgr, FileManager &FileMgr,
+    llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr,
+    llvm::IntrusiveRefCntPtr<FileManager> FileMgr,
     SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers,
     std::unique_ptr<SyntaxOnlyAction> Act) {
@@ -2265,7 +2270,7 @@ void ASTUnit::CodeComplete(
                                     Clang->getDiagnostics(),
                                     &StoredDiagnostics, nullptr);
   ProcessWarningOptions(*Diag, Inv.getDiagnosticOpts(),
-                        FileMgr.getVirtualFileSystem());
+                        FileMgr->getVirtualFileSystem());
 
   // Create the target instance.
   if (!Clang->createTarget()) {
@@ -2282,8 +2287,8 @@ void ASTUnit::CodeComplete(
          "IR inputs not support here!");
 
   // Use the source and file managers that we were given.
-  Clang->setFileManager(&FileMgr);
-  Clang->setSourceManager(&SourceMgr);
+  Clang->setFileManager(FileMgr);
+  Clang->setSourceManager(SourceMgr);
 
   // Remap files.
   PreprocessorOpts.clearRemappedFiles();
@@ -2301,7 +2306,7 @@ void ASTUnit::CodeComplete(
 
   auto getUniqueID =
       [&FileMgr](StringRef Filename) -> std::optional<llvm::sys::fs::UniqueID> 
{
-    if (auto Status = FileMgr.getVirtualFileSystem().status(Filename))
+    if (auto Status = FileMgr->getVirtualFileSystem().status(Filename))
       return Status->getUniqueID();
     return std::nullopt;
   };
@@ -2322,7 +2327,7 @@ void ASTUnit::CodeComplete(
   std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
   if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) {
     OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
-        PCHContainerOps, Inv, FileMgr.getVirtualFileSystemPtr(), false,
+        PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(), false,
         Line - 1);
   }
 
@@ -2333,7 +2338,7 @@ void ASTUnit::CodeComplete(
            "No preamble was built, but OverrideMainBuffer is not null");
 
     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
-        FileMgr.getVirtualFileSystemPtr();
+        FileMgr->getVirtualFileSystemPtr();
     Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
                                   OverrideMainBuffer.get());
     // FIXME: there is no way to update VFS if it was changed by

diff  --git a/clang/lib/Frontend/ChainedIncludesSource.cpp 
b/clang/lib/Frontend/ChainedIncludesSource.cpp
index 88b1076cd36ce..013814a738a36 100644
--- a/clang/lib/Frontend/ChainedIncludesSource.cpp
+++ b/clang/lib/Frontend/ChainedIncludesSource.cpp
@@ -53,17 +53,17 @@ class ChainedIncludesSource : public ExternalSemaSource {
 };
 } // end anonymous namespace
 
-static ASTReader *
+static llvm::IntrusiveRefCntPtr<ASTReader>
 createASTReader(CompilerInstance &CI, StringRef pchFile,
                 SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
                 SmallVectorImpl<std::string> &bufNames,
                 ASTDeserializationListener *deserialListener = nullptr) {
   Preprocessor &PP = CI.getPreprocessor();
-  std::unique_ptr<ASTReader> Reader;
-  Reader.reset(new ASTReader(
+  auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
       PP, CI.getModuleCache(), &CI.getASTContext(), CI.getPCHContainerReader(),
-      CI.getCodeGenOpts(), /*Extensions=*/{},
-      /*isysroot=*/"", DisableValidationForModuleKind::PCH));
+      CI.getCodeGenOpts(),
+      /*Extensions=*/ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
+      /*isysroot=*/"", DisableValidationForModuleKind::PCH);
   for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
     StringRef sr(bufNames[ti]);
     Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti]));
@@ -74,7 +74,7 @@ createASTReader(CompilerInstance &CI, StringRef pchFile,
   case ASTReader::Success:
     // Set the predefines buffer as suggested by the PCH reader.
     PP.setPredefines(Reader->getSuggestedPredefines());
-    return Reader.release();
+    return Reader;
 
   case ASTReader::Failure:
   case ASTReader::Missing:
@@ -87,8 +87,9 @@ createASTReader(CompilerInstance &CI, StringRef pchFile,
   return nullptr;
 }
 
-IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource(
-    CompilerInstance &CI, IntrusiveRefCntPtr<ExternalSemaSource> &Reader) {
+IntrusiveRefCntPtr<ExternalSemaSource>
+clang::createChainedIncludesSource(CompilerInstance &CI,
+                                   IntrusiveRefCntPtr<ASTReader> &OutReader) {
 
   std::vector<std::string> &includes = 
CI.getPreprocessorOpts().ChainedIncludes;
   assert(!includes.empty() && "No '-chain-include' in options!");
@@ -186,12 +187,12 @@ IntrusiveRefCntPtr<ExternalSemaSource> 
clang::createChainedIncludesSource(
   assert(!SerialBufs.empty());
   std::string pchName = includes.back() + ".pch-final";
   serialBufNames.push_back(pchName);
-  Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
-  if (!Reader)
+  OutReader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
+  if (!OutReader)
     return nullptr;
 
   auto ChainedSrc =
       llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(std::move(CIs));
   return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
-      ChainedSrc.get(), Reader.get());
+      std::move(ChainedSrc), OutReader);
 }

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index ed6a651d919a1..d64290f5c4673 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -166,20 +166,23 @@ CompilerInstance::getVirtualFileSystemPtr() const {
   return getFileManager().getVirtualFileSystemPtr();
 }
 
-void CompilerInstance::setFileManager(FileManager *Value) {
-  FileMgr = Value;
+void CompilerInstance::setFileManager(
+    llvm::IntrusiveRefCntPtr<FileManager> Value) {
+  FileMgr = std::move(Value);
 }
 
-void CompilerInstance::setSourceManager(SourceManager *Value) {
-  SourceMgr = Value;
+void CompilerInstance::setSourceManager(
+    llvm::IntrusiveRefCntPtr<SourceManager> Value) {
+  SourceMgr = std::move(Value);
 }
 
 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
   PP = std::move(Value);
 }
 
-void CompilerInstance::setASTContext(ASTContext *Value) {
-  Context = Value;
+void CompilerInstance::setASTContext(
+    llvm::IntrusiveRefCntPtr<ASTContext> Value) {
+  Context = std::move(Value);
 
   if (Context && Consumer)
     getASTConsumer().Initialize(getASTContext());
@@ -387,14 +390,16 @@ FileManager *CompilerInstance::createFileManager(
   if (getFrontendOpts().ShowStats)
     VFS =
         
llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
-  FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
+  FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(),
+                                                   std::move(VFS));
   return FileMgr.get();
 }
 
 // Source Manager
 
 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
-  SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
+  SourceMgr =
+      llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(), FileMgr);
 }
 
 // Initialize the remapping of files to alternative contents, e.g.,
@@ -554,11 +559,11 @@ std::string 
CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
 
 void CompilerInstance::createASTContext() {
   Preprocessor &PP = getPreprocessor();
-  auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
-                                 PP.getIdentifierTable(), 
PP.getSelectorTable(),
-                                 PP.getBuiltinInfo(), PP.TUKind);
+  auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
+      getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
+      PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
   Context->InitBuiltinTypes(getTarget(), getAuxTarget());
-  setASTContext(Context);
+  setASTContext(std::move(Context));
 }
 
 // ExternalASTSource
@@ -638,17 +643,17 @@ IntrusiveRefCntPtr<ASTReader> 
CompilerInstance::createPCHExternalASTSource(
   const HeaderSearchOptions &HSOpts =
       PP.getHeaderSearchInfo().getHeaderSearchOpts();
 
-  IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
+  auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
       PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
       Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
       AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
       HSOpts.ModulesValidateSystemHeaders,
       HSOpts.ModulesForceValidateUserHeaders,
-      HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex));
+      HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex);
 
   // We need the external source to be set up before we read the AST, because
   // eagerly-deserialized declarations may use it.
-  Context.setExternalSource(Reader.get());
+  Context.setExternalSource(Reader);
 
   Reader->setDeserializationListener(
       static_cast<ASTDeserializationListener *>(DeserializationListener),
@@ -755,7 +760,7 @@ void CompilerInstance::createSema(TranslationUnitKind 
TUKind,
 
   // Attach the external sema source if there is any.
   if (ExternalSemaSrc) {
-    TheSema->addExternalSource(ExternalSemaSrc.get());
+    TheSema->addExternalSource(ExternalSemaSrc);
     ExternalSemaSrc->InitializeSema(*TheSema);
   }
 
@@ -1221,7 +1226,7 @@ std::unique_ptr<CompilerInstance> 
CompilerInstance::cloneForModuleCompileImpl(
   if (ThreadSafeConfig) {
     Instance.createFileManager(ThreadSafeConfig->getVFS());
   } else if (FrontendOpts.ModulesShareFileManager) {
-    Instance.setFileManager(&getFileManager());
+    Instance.setFileManager(getFileManagerPtr());
   } else {
     Instance.createFileManager(getVirtualFileSystemPtr());
   }
@@ -1750,17 +1755,18 @@ void CompilerInstance::createASTReader() {
   if (timerGroup)
     ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
                                               "Reading modules", *timerGroup);
-  TheASTReader = new ASTReader(
+  TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
       getPreprocessor(), getModuleCache(), &getASTContext(),
       getPCHContainerReader(), getCodeGenOpts(),
       getFrontendOpts().ModuleFileExtensions,
       Sysroot.empty() ? "" : Sysroot.c_str(),
       PPOpts.DisablePCHOrModuleValidation,
       /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
-      /*AllowConfigurationMismatch=*/false, 
HSOpts.ModulesValidateSystemHeaders,
-      HSOpts.ModulesForceValidateUserHeaders,
-      HSOpts.ValidateASTInputFilesContent,
-      getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
+      /*AllowConfigurationMismatch=*/false,
+      +HSOpts.ModulesValidateSystemHeaders,
+      +HSOpts.ModulesForceValidateUserHeaders,
+      +HSOpts.ValidateASTInputFilesContent,
+      +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
   if (hasASTConsumer()) {
     TheASTReader->setDeserializationListener(
         getASTConsumer().GetASTDeserializationListener());

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 87cc2fc0cdd17..2d69f8cc21f96 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -845,7 +845,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
 
     // Set the shared objects, these are reset when we finish processing the
     // file, otherwise the CompilerInstance will happily destroy them.
-    CI.setFileManager(&AST->getFileManager());
+    CI.setFileManager(AST->getFileManagerPtr());
     CI.createSourceManager(CI.getFileManager());
     CI.getSourceManager().initializeForReplay(AST->getSourceManager());
 
@@ -912,13 +912,13 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
 
     // Set the shared objects, these are reset when we finish processing the
     // file, otherwise the CompilerInstance will happily destroy them.
-    CI.setFileManager(&AST->getFileManager());
-    CI.setSourceManager(&AST->getSourceManager());
+    CI.setFileManager(AST->getFileManagerPtr());
+    CI.setSourceManager(AST->getSourceManagerPtr());
     CI.setPreprocessor(AST->getPreprocessorPtr());
     Preprocessor &PP = CI.getPreprocessor();
     PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
                                            PP.getLangOpts());
-    CI.setASTContext(&AST->getASTContext());
+    CI.setASTContext(AST->getASTContextPtr());
 
     setCurrentInput(Input, std::move(AST));
 
@@ -1172,11 +1172,12 @@ bool FrontendAction::BeginSourceFile(CompilerInstance 
&CI,
 
     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
       // Convert headers to PCH and chain them.
-      IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
+      IntrusiveRefCntPtr<ExternalSemaSource> source;
+      IntrusiveRefCntPtr<ASTReader> FinalReader;
       source = createChainedIncludesSource(CI, FinalReader);
       if (!source)
         return false;
-      CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
+      CI.setASTReader(FinalReader);
       CI.getASTContext().setExternalSource(source);
     } else if (CI.getLangOpts().Modules ||
                !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
@@ -1252,23 +1253,21 @@ bool FrontendAction::BeginSourceFile(CompilerInstance 
&CI,
   // provides the layouts from that file.
   if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
       CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
-    IntrusiveRefCntPtr<ExternalASTSource>
-      Override(new LayoutOverrideSource(
-                     CI.getFrontendOpts().OverrideRecordLayoutsFile));
+    auto Override = llvm::makeIntrusiveRefCnt<LayoutOverrideSource>(
+        CI.getFrontendOpts().OverrideRecordLayoutsFile);
     CI.getASTContext().setExternalSource(Override);
   }
 
   // Setup HLSL External Sema Source
   if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
-    IntrusiveRefCntPtr<ExternalSemaSource> HLSLSema(
-        new HLSLExternalSemaSource());
-    if (auto *SemaSource = dyn_cast_if_present<ExternalSemaSource>(
-            CI.getASTContext().getExternalSource())) {
-      IntrusiveRefCntPtr<ExternalSemaSource> MultiSema(
-          new MultiplexExternalSemaSource(SemaSource, HLSLSema.get()));
-      CI.getASTContext().setExternalSource(MultiSema);
+    auto HLSLSema = llvm::makeIntrusiveRefCnt<HLSLExternalSemaSource>();
+    if (auto SemaSource = dyn_cast_if_present<ExternalSemaSource>(
+            CI.getASTContext().getExternalSourcePtr())) {
+      auto MultiSema = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
+          std::move(SemaSource), std::move(HLSLSema));
+      CI.getASTContext().setExternalSource(std::move(MultiSema));
     } else
-      CI.getASTContext().setExternalSource(HLSLSema);
+      CI.getASTContext().setExternalSource(std::move(HLSLSema));
   }
 
   FailureCleanup.release();

diff  --git a/clang/lib/Frontend/PrecompiledPreamble.cpp 
b/clang/lib/Frontend/PrecompiledPreamble.cpp
index 7fc1d87355674..03f70b74dfb42 100644
--- a/clang/lib/Frontend/PrecompiledPreamble.cpp
+++ b/clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -483,11 +483,12 @@ llvm::ErrorOr<PrecompiledPreamble> 
PrecompiledPreamble::Build(
                                         VFS);
 
   // Create a file manager object to provide access to and cache the 
filesystem.
-  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
+  Clang->setFileManager(
+      llvm::makeIntrusiveRefCnt<FileManager>(Clang->getFileSystemOpts(), VFS));
 
   // Create the source manager.
-  Clang->setSourceManager(
-      new SourceManager(*Diagnostics, Clang->getFileManager()));
+  Clang->setSourceManager(llvm::makeIntrusiveRefCnt<SourceManager>(
+      *Diagnostics, Clang->getFileManager()));
 
   auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
   Clang->addDependencyCollector(PreambleDepCollector);

diff  --git a/clang/lib/Interpreter/CodeCompletion.cpp 
b/clang/lib/Interpreter/CodeCompletion.cpp
index ecdf48983a025..dc7030c55225c 100644
--- a/clang/lib/Interpreter/CodeCompletion.cpp
+++ b/clang/lib/Interpreter/CodeCompletion.cpp
@@ -238,11 +238,9 @@ class ExternalSource : public clang::ExternalASTSource {
 // compiler instance before the super `ExecuteAction` triggers parsing
 void IncrementalSyntaxOnlyAction::ExecuteAction() {
   CompilerInstance &CI = getCompilerInstance();
-  ExternalSource *myExternalSource =
-      new ExternalSource(CI.getASTContext(), CI.getFileManager(),
-                         ParentCI->getASTContext(), 
ParentCI->getFileManager());
-  llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> astContextExternalSource(
-      myExternalSource);
+  auto astContextExternalSource = llvm::makeIntrusiveRefCnt<ExternalSource>(
+      CI.getASTContext(), CI.getFileManager(), ParentCI->getASTContext(),
+      ParentCI->getFileManager());
   CI.getASTContext().setExternalSource(astContextExternalSource);
   CI.getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage(
       true);
@@ -381,8 +379,8 @@ void ReplCodeCompleter::codeComplete(CompilerInstance 
*InterpCI,
   AU->CodeComplete(CodeCompletionFileName, 1, Col, RemappedFiles, false, false,
                    false, consumer,
                    std::make_shared<clang::PCHContainerOperations>(), diag,
-                   InterpCI->getLangOpts(), AU->getSourceManager(),
-                   AU->getFileManager(), sd, tb, std::move(Act));
+                   InterpCI->getLangOpts(), AU->getSourceManagerPtr(),
+                   AU->getFileManagerPtr(), sd, tb, std::move(Act));
 }
 
 } // namespace clang

diff  --git a/clang/lib/Sema/MultiplexExternalSemaSource.cpp 
b/clang/lib/Sema/MultiplexExternalSemaSource.cpp
index fbfb242598c24..1f040c879d724 100644
--- a/clang/lib/Sema/MultiplexExternalSemaSource.cpp
+++ b/clang/lib/Sema/MultiplexExternalSemaSource.cpp
@@ -20,26 +20,19 @@ char MultiplexExternalSemaSource::ID;
 /// given element to it.
 ///
 MultiplexExternalSemaSource::MultiplexExternalSemaSource(
-    ExternalSemaSource *S1, ExternalSemaSource *S2) {
-  S1->Retain();
-  S2->Retain();
-  Sources.push_back(S1);
-  Sources.push_back(S2);
-}
-
-// pin the vtable here.
-MultiplexExternalSemaSource::~MultiplexExternalSemaSource() {
-  for (auto *S : Sources)
-    S->Release();
+    llvm::IntrusiveRefCntPtr<ExternalSemaSource> S1,
+    llvm::IntrusiveRefCntPtr<ExternalSemaSource> S2) {
+  Sources.push_back(std::move(S1));
+  Sources.push_back(std::move(S2));
 }
 
 /// Appends new source to the source list.
 ///
 ///\param[in] source - An ExternalSemaSource.
 ///
-void MultiplexExternalSemaSource::AddSource(ExternalSemaSource *Source) {
-  Source->Retain();
-  Sources.push_back(Source);
+void MultiplexExternalSemaSource::AddSource(
+    llvm::IntrusiveRefCntPtr<ExternalSemaSource> Source) {
+  Sources.push_back(std::move(Source));
 }
 
 
//===----------------------------------------------------------------------===//
@@ -92,7 +85,7 @@ CXXBaseSpecifier 
*MultiplexExternalSemaSource::GetExternalCXXBaseSpecifiers(
 
 CXXCtorInitializer **
 MultiplexExternalSemaSource::GetExternalCXXCtorInitializers(uint64_t Offset) {
-  for (auto *S : Sources)
+  for (auto &S : Sources)
     if (auto *R = S->GetExternalCXXCtorInitializers(Offset))
       return R;
   return nullptr;
@@ -371,6 +364,6 @@ bool 
MultiplexExternalSemaSource::MaybeDiagnoseMissingCompleteType(
 
 void MultiplexExternalSemaSource::AssignedLambdaNumbering(
     CXXRecordDecl *Lambda) {
-  for (auto *Source : Sources)
+  for (auto &Source : Sources)
     Source->AssignedLambdaNumbering(Lambda);
 }

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 43a7f9e6de7ff..924becf702c23 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -656,18 +656,19 @@ ASTMutationListener *Sema::getASTMutationListener() const 
{
   return getASTConsumer().GetASTMutationListener();
 }
 
-void Sema::addExternalSource(ExternalSemaSource *E) {
+void Sema::addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E) {
   assert(E && "Cannot use with NULL ptr");
 
   if (!ExternalSource) {
-    ExternalSource = E;
+    ExternalSource = std::move(E);
     return;
   }
 
-  if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
-    Ex->AddSource(E);
+  if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource.get()))
+    Ex->AddSource(std::move(E));
   else
-    ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);
+    ExternalSource = llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
+        ExternalSource, std::move(E));
 }
 
 void Sema::PrintStats() const {

diff  --git a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp 
b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
index 5d392afcb9825..7bc34f61255f4 100644
--- a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
+++ b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
@@ -43,8 +43,8 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) {
   if (Bodies.count(D->getName()) != 0)
     return;
 
-  SourceManager &SM = CI.getSourceManager();
-  FileID mainFileID = SM.getMainFileID();
+  llvm::IntrusiveRefCntPtr<SourceManager> SM = CI.getSourceManagerPtr();
+  FileID mainFileID = SM->getMainFileID();
 
   llvm::StringRef modelPath = CI.getAnalyzerOpts().ModelPath;
 
@@ -80,14 +80,14 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) {
       new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()),
       /*ShouldOwnClient=*/true);
 
-  Instance.getDiagnostics().setSourceManager(&SM);
+  Instance.getDiagnostics().setSourceManager(SM.get());
 
   // The instance wants to take ownership, however DisableFree frontend option
   // is set to true to avoid double free issues
-  Instance.setFileManager(&CI.getFileManager());
-  Instance.setSourceManager(&SM);
+  Instance.setFileManager(CI.getFileManagerPtr());
+  Instance.setSourceManager(SM);
   Instance.setPreprocessor(CI.getPreprocessorPtr());
-  Instance.setASTContext(&CI.getASTContext());
+  Instance.setASTContext(CI.getASTContextPtr());
 
   Instance.getPreprocessor().InitializeForModelFile();
 
@@ -108,5 +108,5 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) {
   // the main file id is changed to the model file during parsing and it needs
   // to be reset to the former main file id after parsing of the model file
   // is done.
-  SM.setMainFileID(mainFileID);
+  SM->setMainFileID(mainFileID);
 }

diff  --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp
index ecafe269e9542..45dfdf4360253 100644
--- a/clang/lib/Tooling/Tooling.cpp
+++ b/clang/lib/Tooling/Tooling.cpp
@@ -212,8 +212,8 @@ bool runToolOnCodeWithArgs(
   SmallString<16> FileNameStorage;
   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
 
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), VFS));
+  llvm::IntrusiveRefCntPtr<FileManager> Files =
+      llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), VFS);
   ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster();
   ToolInvocation Invocation(
       getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), 
FileNameRef),
@@ -479,7 +479,8 @@ ClangTool::ClangTool(const CompilationDatabase 
&Compilations,
       InMemoryFileSystem(
           llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>()),
       Files(Files ? Files
-                  : new FileManager(FileSystemOptions(), OverlayFileSystem)) {
+                  : llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                           OverlayFileSystem)) 
{
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
   appendArgumentsAdjuster(getClangStripOutputAdjuster());
   appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
@@ -701,8 +702,9 @@ std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs(
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  llvm::IntrusiveRefCntPtr<FileManager> Files =
+      llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                             OverlayFileSystem);
 
   ToolInvocation Invocation(
       getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName),

diff  --git a/clang/tools/clang-installapi/ClangInstallAPI.cpp 
b/clang/tools/clang-installapi/ClangInstallAPI.cpp
index 70091fc04e18e..1edb64aaa8419 100644
--- a/clang/tools/clang-installapi/ClangInstallAPI.cpp
+++ b/clang/tools/clang-installapi/ClangInstallAPI.cpp
@@ -89,8 +89,9 @@ static bool run(ArrayRef<const char *> Args, const char 
*ProgName) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  IntrusiveRefCntPtr<clang::FileManager> FM(
-      new FileManager(clang::FileSystemOptions(), OverlayFileSystem));
+  IntrusiveRefCntPtr<clang::FileManager> FM =
+      llvm::makeIntrusiveRefCnt<FileManager>(clang::FileSystemOptions(),
+                                             OverlayFileSystem);
 
   // Capture all options and diagnose any errors.
   Options Opts(*Diag, FM.get(), Args, ProgName);
@@ -113,7 +114,7 @@ static bool run(ArrayRef<const char *> Args, const char 
*ProgName) {
 
   // Set up compilation.
   std::unique_ptr<CompilerInstance> CI(new CompilerInstance());
-  CI->setFileManager(FM.get());
+  CI->setFileManager(FM);
   CI->createDiagnostics(FM->getVirtualFileSystem());
   if (!CI->hasDiagnostics())
     return EXIT_FAILURE;

diff  --git a/clang/tools/libclang/CIndexCodeCompletion.cpp 
b/clang/tools/libclang/CIndexCodeCompletion.cpp
index adac7c3d2a390..81448b4d11342 100644
--- a/clang/tools/libclang/CIndexCodeCompletion.cpp
+++ b/clang/tools/libclang/CIndexCodeCompletion.cpp
@@ -360,7 +360,8 @@ 
AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
       
Diag(llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(DiagnosticIDs::create(),
                                                         DiagOpts)),
       FileMgr(std::move(FileMgr)),
-      SourceMgr(new SourceManager(*Diag, *this->FileMgr)),
+      SourceMgr(
+          llvm::makeIntrusiveRefCnt<SourceManager>(*Diag, *this->FileMgr)),
       CodeCompletionAllocator(
           std::make_shared<clang::GlobalCodeCompletionAllocator>()),
       Contexts(CXCompletionContext_Unknown),
@@ -736,8 +737,8 @@ clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char 
*complete_filename,
   }
 
   // Parse the resulting source file to find code-completion results.
-  AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
-      &AST->getFileManager());
+  AllocatedCXCodeCompleteResults *Results =
+      new AllocatedCXCodeCompleteResults(AST->getFileManagerPtr());
   Results->Results = nullptr;
   Results->NumResults = 0;
   
@@ -764,7 +765,7 @@ clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char 
*complete_filename,
                     (options & CXCodeComplete_IncludeCodePatterns),
                     IncludeBriefComments, Capture,
                     CXXIdx->getPCHContainerOperations(), Results->Diag,
-                    Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
+                    Results->LangOpts, Results->SourceMgr, Results->FileMgr,
                     Results->Diagnostics, Results->TemporaryBuffers,
                     /*SyntaxOnlyAction=*/nullptr);
 

diff  --git a/clang/tools/libclang/CXIndexDataConsumer.cpp 
b/clang/tools/libclang/CXIndexDataConsumer.cpp
index f0d92e8c40124..73d04b85d72db 100644
--- a/clang/tools/libclang/CXIndexDataConsumer.cpp
+++ b/clang/tools/libclang/CXIndexDataConsumer.cpp
@@ -415,9 +415,9 @@ const char *ScratchAlloc::copyCStr(StringRef Str) {
   return buf;
 }
 
-void CXIndexDataConsumer::setASTContext(ASTContext &ctx) {
-  Ctx = &ctx;
-  cxtu::getASTUnit(CXTU)->setASTContext(&ctx);
+void CXIndexDataConsumer::setASTContext(IntrusiveRefCntPtr<ASTContext> ctx) {
+  Ctx = ctx.get();
+  cxtu::getASTUnit(CXTU)->setASTContext(std::move(ctx));
 }
 
 void CXIndexDataConsumer::setPreprocessor(std::shared_ptr<Preprocessor> PP) {

diff  --git a/clang/tools/libclang/CXIndexDataConsumer.h 
b/clang/tools/libclang/CXIndexDataConsumer.h
index 54a3add3a9c8d..b207db7cde6d7 100644
--- a/clang/tools/libclang/CXIndexDataConsumer.h
+++ b/clang/tools/libclang/CXIndexDataConsumer.h
@@ -339,7 +339,7 @@ class CXIndexDataConsumer : public index::IndexDataConsumer 
{
   ASTContext &getASTContext() const { return *Ctx; }
   CXTranslationUnit getCXTU() const { return CXTU; }
 
-  void setASTContext(ASTContext &ctx);
+  void setASTContext(llvm::IntrusiveRefCntPtr<ASTContext> ctx);
   void setPreprocessor(std::shared_ptr<Preprocessor> PP) override;
 
   bool shouldSuppressRefs() const {

diff  --git a/clang/tools/libclang/Indexing.cpp 
b/clang/tools/libclang/Indexing.cpp
index 32a7147af3382..c142f142d5071 100644
--- a/clang/tools/libclang/Indexing.cpp
+++ b/clang/tools/libclang/Indexing.cpp
@@ -304,7 +304,8 @@ class IndexingConsumer : public ASTConsumer {
       : DataConsumer(dataConsumer) {}
 
   void Initialize(ASTContext &Context) override {
-    DataConsumer.setASTContext(Context);
+    // TODO: accept Context as IntrusiveRefCntPtr?
+    DataConsumer.setASTContext(&Context);
     DataConsumer.startedTranslationUnit();
   }
 
@@ -355,7 +356,7 @@ class IndexingFrontendAction : public ASTFrontendAction {
         DataConsumer->importedPCH(*File);
     }
 
-    DataConsumer->setASTContext(CI.getASTContext());
+    DataConsumer->setASTContext(CI.getASTContextPtr());
     Preprocessor &PP = CI.getPreprocessor();
     PP.addPPCallbacks(std::make_unique<IndexPPCallbacks>(PP, *DataConsumer));
     DataConsumer->setPreprocessor(CI.getPreprocessorPtr());
@@ -706,7 +707,7 @@ static CXErrorCode clang_indexTranslationUnit_Impl(
   else
     DataConsumer.enteredMainFile(std::nullopt);
 
-  DataConsumer.setASTContext(Unit->getASTContext());
+  DataConsumer.setASTContext(Unit->getASTContextPtr());
   DataConsumer.startedTranslationUnit();
 
   indexPreprocessingRecord(*Unit, DataConsumer);

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index c0fb642d817a0..ac38300142e34 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -6976,7 +6976,8 @@ TEST_P(LLDBLookupTest, 
ImporterShouldFindInTransparentContext) {
   // Set up DeclContextBits.HasLazyExternalLexicalLookups to true.
   ToTU->setMustBuildLookupTable();
   struct TestExternalASTSource : ExternalASTSource {};
-  ToTU->getASTContext().setExternalSource(new TestExternalASTSource());
+  ToTU->getASTContext().setExternalSource(
+      llvm::makeIntrusiveRefCnt<TestExternalASTSource>());
 
   Decl *FromTU = getTuDecl(
       R"(
@@ -8154,8 +8155,8 @@ TEST_P(ImportWithExternalSource, 
CompleteRecordBeforeImporting) {
 
   // Create and add the test ExternalASTSource.
   std::vector<clang::TagDecl *> CompletedTags;
-  IntrusiveRefCntPtr<ExternalASTSource> source =
-      new SourceWithCompletedTagList(CompletedTags);
+  auto source =
+      llvm::makeIntrusiveRefCnt<SourceWithCompletedTagList>(CompletedTags);
   clang::ASTContext &Context = FromTU->getASTContext();
   Context.setExternalSource(std::move(source));
 

diff  --git a/clang/unittests/AST/ExternalASTSourceTest.cpp 
b/clang/unittests/AST/ExternalASTSourceTest.cpp
index 11715bb8ce7cd..21d4ce4dcf212 100644
--- a/clang/unittests/AST/ExternalASTSourceTest.cpp
+++ b/clang/unittests/AST/ExternalASTSourceTest.cpp
@@ -26,7 +26,8 @@ using namespace llvm;
 
 class TestFrontendAction : public ASTFrontendAction {
 public:
-  TestFrontendAction(ExternalASTSource *Source) : Source(Source) {}
+  TestFrontendAction(IntrusiveRefCntPtr<ExternalASTSource> Source)
+      : Source(std::move(Source)) {}
 
 private:
   void ExecuteAction() override {
@@ -44,7 +45,8 @@ class TestFrontendAction : public ASTFrontendAction {
   IntrusiveRefCntPtr<ExternalASTSource> Source;
 };
 
-bool testExternalASTSource(ExternalASTSource *Source, StringRef FileContents) {
+bool testExternalASTSource(llvm::IntrusiveRefCntPtr<ExternalASTSource> Source,
+                           StringRef FileContents) {
 
   auto Invocation = std::make_shared<CompilerInvocation>();
   Invocation->getPreprocessorOpts().addRemappedFile(
@@ -80,6 +82,7 @@ TEST(ExternalASTSourceTest, FailedLookupOccursOnce) {
   };
 
   unsigned Calls = 0;
-  ASSERT_TRUE(testExternalASTSource(new TestSource(Calls), "int j, k = j;"));
+  ASSERT_TRUE(testExternalASTSource(
+      llvm::makeIntrusiveRefCnt<TestSource>(Calls), "int j, k = j;"));
   EXPECT_EQ(1u, Calls);
 }

diff  --git a/clang/unittests/Frontend/ASTUnitTest.cpp 
b/clang/unittests/Frontend/ASTUnitTest.cpp
index 7148ca03e0aed..7160453b17daa 100644
--- a/clang/unittests/Frontend/ASTUnitTest.cpp
+++ b/clang/unittests/Frontend/ASTUnitTest.cpp
@@ -55,7 +55,8 @@ class ASTUnitTest : public ::testing::Test {
     if (!CInvok)
       return nullptr;
 
-    FileManager *FileMgr = new FileManager(FileSystemOptions(), VFS);
+    auto FileMgr =
+        llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), VFS);
     PCHContainerOps = std::make_shared<PCHContainerOperations>();
 
     return ASTUnit::LoadFromCompilerInvocation(
@@ -143,7 +144,8 @@ TEST_F(ASTUnitTest, ModuleTextualHeader) {
   CInvok = createInvocation(Args, std::move(CIOpts));
   ASSERT_TRUE(CInvok);
 
-  FileManager *FileMgr = new FileManager(FileSystemOptions(), InMemoryFs);
+  auto FileMgr =
+      llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), InMemoryFs);
   PCHContainerOps = std::make_shared<PCHContainerOperations>();
 
   auto AU = ASTUnit::LoadFromCompilerInvocation(

diff  --git a/clang/unittests/Frontend/FrontendActionTest.cpp 
b/clang/unittests/Frontend/FrontendActionTest.cpp
index 4e040783c923e..48c0cfd6a185a 100644
--- a/clang/unittests/Frontend/FrontendActionTest.cpp
+++ b/clang/unittests/Frontend/FrontendActionTest.cpp
@@ -244,7 +244,8 @@ TEST(ASTFrontendAction, ExternalSemaSource) {
   auto *TDC = new TypoDiagnosticConsumer;
   Compiler.createDiagnostics(*llvm::vfs::getRealFileSystem(), TDC,
                              /*ShouldOwnClient=*/true);
-  Compiler.setExternalSemaSource(new TypoExternalSemaSource(Compiler));
+  Compiler.setExternalSemaSource(
+      llvm::makeIntrusiveRefCnt<TypoExternalSemaSource>(Compiler));
 
   SyntaxOnlyAction TestAction;
   ASSERT_TRUE(Compiler.ExecuteAction(TestAction));

diff  --git a/clang/unittests/Frontend/PCHPreambleTest.cpp 
b/clang/unittests/Frontend/PCHPreambleTest.cpp
index d27f793a52a7a..9991838d1de92 100644
--- a/clang/unittests/Frontend/PCHPreambleTest.cpp
+++ b/clang/unittests/Frontend/PCHPreambleTest.cpp
@@ -100,7 +100,7 @@ class PCHPreambleTest : public ::testing::Test {
         CompilerInstance::createDiagnostics(*VFS, *DiagOpts,
                                             new DiagnosticConsumer));
 
-    FileManager *FileMgr = new FileManager(FSOpts, VFS);
+    auto FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(FSOpts, VFS);
 
     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
         CI, PCHContainerOpts, DiagOpts, Diags, FileMgr, false,

diff  --git a/clang/unittests/Frontend/ReparseWorkingDirTest.cpp 
b/clang/unittests/Frontend/ReparseWorkingDirTest.cpp
index 38ef4686e7d91..6b34b967a731c 100644
--- a/clang/unittests/Frontend/ReparseWorkingDirTest.cpp
+++ b/clang/unittests/Frontend/ReparseWorkingDirTest.cpp
@@ -64,7 +64,8 @@ class ReparseWorkingDirTest : public ::testing::Test {
         CompilerInstance::createDiagnostics(*VFS, *DiagOpts,
                                             new DiagnosticConsumer));
 
-    FileManager *FileMgr = new FileManager(CI->getFileSystemOpts(), VFS);
+    auto FileMgr =
+        llvm::makeIntrusiveRefCnt<FileManager>(CI->getFileSystemOpts(), VFS);
 
     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
         CI, PCHContainerOpts, DiagOpts, Diags, FileMgr, false,

diff  --git a/clang/unittests/Sema/ExternalSemaSourceTest.cpp 
b/clang/unittests/Sema/ExternalSemaSourceTest.cpp
index cc9dd4175af55..2524ac3ea518b 100644
--- a/clang/unittests/Sema/ExternalSemaSourceTest.cpp
+++ b/clang/unittests/Sema/ExternalSemaSourceTest.cpp
@@ -181,7 +181,7 @@ class FunctionTypoProvider : public 
clang::ExternalSemaSource {
 // performing semantic analysis.
 class ExternalSemaSourceInstaller : public clang::ASTFrontendAction {
   std::vector<DiagnosticWatcher *> Watchers;
-  std::vector<clang::ExternalSemaSource *> Sources;
+  std::vector<llvm::IntrusiveRefCntPtr<clang::ExternalSemaSource>> Sources;
   std::unique_ptr<DiagnosticConsumer> OwnedClient;
 
 protected:
@@ -212,8 +212,8 @@ class ExternalSemaSourceInstaller : public 
clang::ASTFrontendAction {
   }
 
 public:
-  void PushSource(clang::ExternalSemaSource *Source) {
-    Sources.push_back(Source);
+  void PushSource(llvm::IntrusiveRefCntPtr<clang::ExternalSemaSource> Source) {
+    Sources.push_back(std::move(Source));
   }
 
   void PushWatcher(DiagnosticWatcher *Watcher) { Watchers.push_back(Watcher); }
@@ -238,7 +238,7 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionPrioritized) 
{
   auto Installer = std::make_unique<ExternalSemaSourceInstaller>();
   auto Provider = makeIntrusiveRefCnt<NamespaceTypoProvider>("AAB", "BBB");
   DiagnosticWatcher Watcher("AAB", "BBB");
-  Installer->PushSource(Provider.get());
+  Installer->PushSource(Provider);
   Installer->PushWatcher(&Watcher);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
@@ -255,9 +255,9 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) {
   auto Second = makeIntrusiveRefCnt<NamespaceTypoProvider>("AAB", "CCC");
   auto Third = makeIntrusiveRefCnt<NamespaceTypoProvider>("AAB", "DDD");
   DiagnosticWatcher Watcher("AAB", "CCC");
-  Installer->PushSource(First.get());
-  Installer->PushSource(Second.get());
-  Installer->PushSource(Third.get());
+  Installer->PushSource(First);
+  Installer->PushSource(Second);
+  Installer->PushSource(Third);
   Installer->PushWatcher(&Watcher);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
@@ -273,7 +273,7 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) {
 TEST(ExternalSemaSource, TryOtherTacticsBeforeDiagnosing) {
   auto Installer = std::make_unique<ExternalSemaSourceInstaller>();
   auto Diagnoser = makeIntrusiveRefCnt<CompleteTypeDiagnoser>(false);
-  Installer->PushSource(Diagnoser.get());
+  Installer->PushSource(Diagnoser);
   std::vector<std::string> Args(1, "-std=c++11");
   // This code hits the class template specialization/class member of a class
   // template specialization checks in Sema::RequireCompleteTypeImpl.
@@ -291,9 +291,9 @@ TEST(ExternalSemaSource, FirstDiagnoserTaken) {
   auto First = makeIntrusiveRefCnt<CompleteTypeDiagnoser>(false);
   auto Second = makeIntrusiveRefCnt<CompleteTypeDiagnoser>(true);
   auto Third = makeIntrusiveRefCnt<CompleteTypeDiagnoser>(true);
-  Installer->PushSource(First.get());
-  Installer->PushSource(Second.get());
-  Installer->PushSource(Third.get());
+  Installer->PushSource(First);
+  Installer->PushSource(Second);
+  Installer->PushSource(Third);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_FALSE(clang::tooling::runToolOnCodeWithArgs(
       std::move(Installer), "class Incomplete; Incomplete IncompleteInstance;",

diff  --git a/clang/unittests/Support/TimeProfilerTest.cpp 
b/clang/unittests/Support/TimeProfilerTest.cpp
index f70149daad295..871c59f650c82 100644
--- a/clang/unittests/Support/TimeProfilerTest.cpp
+++ b/clang/unittests/Support/TimeProfilerTest.cpp
@@ -52,8 +52,7 @@ bool compileFromString(StringRef Code, StringRef Standard, 
StringRef File,
     FS->addFile(Header.getKey(), 0,
                 MemoryBuffer::getMemBuffer(Header.getValue()));
   }
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), FS));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), FS);
 
   auto Invocation = std::make_shared<CompilerInvocation>();
   std::vector<const char *> Args = {Standard.data(), File.data()};
@@ -64,7 +63,7 @@ bool compileFromString(StringRef Code, StringRef Standard, 
StringRef File,
 
   CompilerInstance Compiler(std::move(Invocation));
   Compiler.createDiagnostics(Files->getVirtualFileSystem());
-  Compiler.setFileManager(Files.get());
+  Compiler.setFileManager(Files);
 
   class TestFrontendAction : public ASTFrontendAction {
   private:

diff  --git a/clang/unittests/Tooling/Syntax/TokensTest.cpp 
b/clang/unittests/Tooling/Syntax/TokensTest.cpp
index e86793ff8e05f..6094177e4817b 100644
--- a/clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ b/clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -134,8 +134,8 @@ class TokenCollectorTest : public ::testing::Test {
         FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release());
     CompilerInstance Compiler(std::move(CI));
     Compiler.setDiagnostics(Diags);
-    Compiler.setFileManager(FileMgr.get());
-    Compiler.setSourceManager(SourceMgr.get());
+    Compiler.setFileManager(FileMgr);
+    Compiler.setSourceManager(SourceMgr);
 
     this->Buffer = TokenBuffer(*SourceMgr);
     RecordTokens Recorder(this->Buffer);
@@ -255,9 +255,9 @@ class TokenCollectorTest : public ::testing::Test {
   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> FS =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   llvm::IntrusiveRefCntPtr<FileManager> FileMgr =
-      new FileManager(FileSystemOptions(), FS);
+      llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), FS);
   llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr =
-      new SourceManager(*Diags, *FileMgr);
+      llvm::makeIntrusiveRefCnt<SourceManager>(*Diags, *FileMgr);
   /// Contains last result of calling recordTokens().
   TokenBuffer Buffer = TokenBuffer(*SourceMgr);
 };

diff  --git a/clang/unittests/Tooling/Syntax/TreeTestBase.cpp 
b/clang/unittests/Tooling/Syntax/TreeTestBase.cpp
index 4a25863b03245..400a0d5a1801b 100644
--- a/clang/unittests/Tooling/Syntax/TreeTestBase.cpp
+++ b/clang/unittests/Tooling/Syntax/TreeTestBase.cpp
@@ -153,8 +153,8 @@ SyntaxTreeTest::buildTree(StringRef Code, const 
TestClangConfig &ClangConfig) {
       FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release());
   CompilerInstance Compiler(Invocation);
   Compiler.setDiagnostics(Diags);
-  Compiler.setFileManager(FileMgr.get());
-  Compiler.setSourceManager(SourceMgr.get());
+  Compiler.setFileManager(FileMgr);
+  Compiler.setSourceManager(SourceMgr);
 
   syntax::TranslationUnit *Root = nullptr;
   BuildSyntaxTreeAction Recorder(Root, this->TM, this->TB, this->Arena);

diff  --git a/clang/unittests/Tooling/Syntax/TreeTestBase.h 
b/clang/unittests/Tooling/Syntax/TreeTestBase.h
index fce89e263efd6..e85d76c9efed7 100644
--- a/clang/unittests/Tooling/Syntax/TreeTestBase.h
+++ b/clang/unittests/Tooling/Syntax/TreeTestBase.h
@@ -47,9 +47,9 @@ class SyntaxTreeTest : public ::testing::Test,
   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> FS =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   IntrusiveRefCntPtr<FileManager> FileMgr =
-      new FileManager(FileSystemOptions(), FS);
+      llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(), FS);
   IntrusiveRefCntPtr<SourceManager> SourceMgr =
-      new SourceManager(*Diags, *FileMgr);
+      llvm::makeIntrusiveRefCnt<SourceManager>(*Diags, *FileMgr);
   std::shared_ptr<CompilerInvocation> Invocation;
   // Set after calling buildTree().
   std::unique_ptr<syntax::TokenBuffer> TB;

diff  --git a/clang/unittests/Tooling/ToolingTest.cpp 
b/clang/unittests/Tooling/ToolingTest.cpp
index c72676f83e6ba..25e1d67eb2294 100644
--- a/clang/unittests/Tooling/ToolingTest.cpp
+++ b/clang/unittests/Tooling/ToolingTest.cpp
@@ -194,8 +194,8 @@ TEST(ToolInvocation, TestMapVirtualFile) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
   Args.push_back("-Idef");
@@ -221,8 +221,8 @@ TEST(ToolInvocation, TestVirtualModulesCompilation) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
   Args.push_back("-Idef");
@@ -248,8 +248,8 @@ TEST(ToolInvocation, 
DiagnosticsEngineProperlyInitializedForCC1Construction) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
 
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
@@ -278,8 +278,8 @@ TEST(ToolInvocation, 
CustomDiagnosticOptionsOverwriteParsedOnes) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
 
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
@@ -325,8 +325,8 @@ TEST(ToolInvocation, DiagConsumerExpectingSourceManager) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
   // Note: intentional error; user probably meant -ferror-limit=0.
@@ -352,8 +352,8 @@ TEST(ToolInvocation, CC1Args) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
   Args.push_back("-cc1");
@@ -373,8 +373,8 @@ TEST(ToolInvocation, CC1ArgsInvalid) {
   auto InMemoryFileSystem =
       llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
   OverlayFileSystem->pushOverlay(InMemoryFileSystem);
-  llvm::IntrusiveRefCntPtr<FileManager> Files(
-      new FileManager(FileSystemOptions(), OverlayFileSystem));
+  auto Files = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOptions(),
+                                                      OverlayFileSystem);
   std::vector<std::string> Args;
   Args.push_back("tool-executable");
   Args.push_back("-cc1");

diff  --git a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp 
b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp
index 5d67a51b26905..a95fce1c5aa96 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp
@@ -18,10 +18,7 @@ lldb_private::ASTConsumerForwarder::~ASTConsumerForwarder() 
= default;
 
 void lldb_private::ASTConsumerForwarder::PrintStats() { m_c->PrintStats(); }
 
-lldb_private::SemaSourceWithPriorities::~SemaSourceWithPriorities() {
-  for (auto *Source : Sources)
-    Source->Release();
-}
+lldb_private::SemaSourceWithPriorities::~SemaSourceWithPriorities() = default;
 
 void lldb_private::SemaSourceWithPriorities::PrintStats() {
   for (size_t i = 0; i < Sources.size(); ++i)

diff  --git a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h 
b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h
index a1f02dc3d1b09..61ca63c81d2d8 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h
@@ -33,8 +33,9 @@ class ExternalASTSourceWrapper : public 
clang::ExternalSemaSource {
   llvm::IntrusiveRefCntPtr<ExternalASTSource> m_Source;
 
 public:
-  explicit ExternalASTSourceWrapper(ExternalASTSource *Source)
-      : m_Source(Source) {
+  explicit ExternalASTSourceWrapper(
+      llvm::IntrusiveRefCntPtr<ExternalASTSource> Source)
+      : m_Source(std::move(Source)) {
     assert(m_Source && "Can't wrap nullptr ExternalASTSource");
   }
 
@@ -284,7 +285,8 @@ class SemaSourceWithPriorities : public 
clang::ExternalSemaSource {
 
 private:
   /// The sources ordered in decreasing priority.
-  llvm::SmallVector<clang::ExternalSemaSource *, 2> Sources;
+  llvm::SmallVector<llvm::IntrusiveRefCntPtr<clang::ExternalSemaSource>, 2>
+      Sources;
 
 public:
   /// Construct a SemaSourceWithPriorities with a 'high quality' source that
@@ -292,16 +294,14 @@ class SemaSourceWithPriorities : public 
clang::ExternalSemaSource {
   /// as a fallback.
   ///
   /// This class assumes shared ownership of the sources provided to it.
-  SemaSourceWithPriorities(clang::ExternalSemaSource *high_quality_source,
-                           clang::ExternalSemaSource *low_quality_source) {
+  SemaSourceWithPriorities(
+      llvm::IntrusiveRefCntPtr<clang::ExternalSemaSource> high_quality_source,
+      llvm::IntrusiveRefCntPtr<clang::ExternalSemaSource> low_quality_source) {
     assert(high_quality_source);
     assert(low_quality_source);
 
-    high_quality_source->Retain();
-    low_quality_source->Retain();
-
-    Sources.push_back(high_quality_source);
-    Sources.push_back(low_quality_source);
+    Sources.push_back(std::move(high_quality_source));
+    Sources.push_back(std::move(low_quality_source));
   }
 
   ~SemaSourceWithPriorities() override;
@@ -374,7 +374,7 @@ class SemaSourceWithPriorities : public 
clang::ExternalSemaSource {
 
   clang::CXXCtorInitializer **
   GetExternalCXXCtorInitializers(uint64_t Offset) override {
-    for (auto *S : Sources)
+    for (const auto &S : Sources)
       if (auto *R = S->GetExternalCXXCtorInitializers(Offset))
         return R;
     return nullptr;
@@ -422,7 +422,7 @@ class SemaSourceWithPriorities : public 
clang::ExternalSemaSource {
   }
 
   void CompleteType(clang::TagDecl *Tag) override {
-    for (clang::ExternalSemaSource *S : Sources) {
+    for (const auto &S : Sources) {
       S->CompleteType(Tag);
       // Stop after the first source completed the type.
       if (Tag->isCompleteDefinition())

diff  --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h 
b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h
index dd89bae96f629..2450635555eb6 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h
@@ -253,8 +253,8 @@ class ClangASTSource : public clang::ExternalASTSource,
     ClangASTSource &m_original;
   };
 
-  clang::ExternalASTSource *CreateProxy() {
-    return new ClangASTSourceProxy(*this);
+  llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> CreateProxy() {
+    return llvm::makeIntrusiveRefCnt<ClangASTSourceProxy>(*this);
   }
 
 protected:

diff  --git 
a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp 
b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
index e5a1d2db604c8..c32e6377c24ff 100644
--- a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
+++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -1315,16 +1315,18 @@ ClangExpressionParser::ParseInternal(DiagnosticManager 
&diagnostic_manager,
     decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
     decl_map->InstallDiagnosticManager(diagnostic_manager);
 
-    clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
+    llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source =
+        decl_map->CreateProxy();
 
-    auto *ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
+    auto ast_source_wrapper =
+        llvm::makeIntrusiveRefCnt<ExternalASTSourceWrapper>(ast_source);
 
     if (ast_context.getExternalSource()) {
-      auto *module_wrapper =
-          new ExternalASTSourceWrapper(ast_context.getExternalSource());
+      auto module_wrapper = 
llvm::makeIntrusiveRefCnt<ExternalASTSourceWrapper>(
+          ast_context.getExternalSourcePtr());
 
-      auto *multiplexer =
-          new SemaSourceWithPriorities(module_wrapper, ast_source_wrapper);
+      auto multiplexer = llvm::makeIntrusiveRefCnt<SemaSourceWithPriorities>(
+          module_wrapper, ast_source_wrapper);
 
       ast_context.setExternalSource(multiplexer);
     } else {

diff  --git 
a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp
 
b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp
index e4b20b30a069f..d6d2df27c5e74 100644
--- 
a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp
+++ 
b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp
@@ -136,9 +136,9 @@ 
AppleObjCDeclVendor::AppleObjCDeclVendor(ObjCLanguageRuntime &runtime)
   m_ast_ctx = std::make_shared<TypeSystemClang>(
       "AppleObjCDeclVendor AST",
       runtime.GetProcess()->GetTarget().GetArchitecture().GetTriple());
-  m_external_source = new AppleObjCExternalASTSource(*this);
-  llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> 
external_source_owning_ptr(
-      m_external_source);
+  auto external_source_owning_ptr =
+      llvm::makeIntrusiveRefCnt<AppleObjCExternalASTSource>(*this);
+  m_external_source = external_source_owning_ptr.get();
   m_ast_ctx->getASTContext().setExternalSource(external_source_owning_ptr);
 }
 

diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
index 9301f92b710ec..8dd6aa08ba2aa 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -616,10 +616,10 @@ void TypeSystemClang::SetTargetTriple(llvm::StringRef 
target_triple) {
 }
 
 void TypeSystemClang::SetExternalSource(
-    llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
+    llvm::IntrusiveRefCntPtr<ExternalASTSource> ast_source_sp) {
   ASTContext &ast = getASTContext();
   ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
-  ast.setExternalSource(ast_source_up);
+  ast.setExternalSource(std::move(ast_source_sp));
 }
 
 ASTContext &TypeSystemClang::getASTContext() const {
@@ -702,9 +702,9 @@ void TypeSystemClang::CreateASTContext() {
 
   GetASTMap().Insert(m_ast_up.get(), this);
 
-  llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
-      new ClangExternalASTSourceCallbacks(*this));
-  SetExternalSource(ast_source_up);
+  auto ast_source_sp =
+      llvm::makeIntrusiveRefCnt<ClangExternalASTSourceCallbacks>(*this);
+  SetExternalSource(ast_source_sp);
 }
 
 TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) {
@@ -9620,8 +9620,8 @@ class SpecializedScratchAST : public TypeSystemClang {
         m_scratch_ast_source_up(std::move(ast_source)) {
     // Setup the ClangASTSource to complete this AST.
     m_scratch_ast_source_up->InstallASTContext(*this);
-    llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
-        m_scratch_ast_source_up->CreateProxy());
+    llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source =
+        m_scratch_ast_source_up->CreateProxy();
     SetExternalSource(proxy_ast_source);
   }
 
@@ -9641,8 +9641,8 @@ ScratchTypeSystemClang::ScratchTypeSystemClang(Target 
&target,
           new ClangPersistentVariables(target.shared_from_this())) {
   m_scratch_ast_source_up = CreateASTSource();
   m_scratch_ast_source_up->InstallASTContext(*this);
-  llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
-      m_scratch_ast_source_up->CreateProxy());
+  llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source =
+      m_scratch_ast_source_up->CreateProxy();
   SetExternalSource(proxy_ast_source);
 }
 

diff  --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h 
b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
index 5431d12473763..70d613d47f93a 100644
--- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -178,7 +178,7 @@ class TypeSystemClang : public TypeSystem {
   const char *GetTargetTriple();
 
   void SetExternalSource(
-      llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> &ast_source_up);
+      llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_sp);
 
   bool GetCompleteDecl(clang::Decl *decl) {
     return TypeSystemClang::GetCompleteDecl(&getASTContext(), decl);


        
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to