diff options
Diffstat (limited to 'clang/lib/Frontend')
-rw-r--r-- | clang/lib/Frontend/ASTMerge.cpp | 4 | ||||
-rw-r--r-- | clang/lib/Frontend/ASTUnit.cpp | 95 | ||||
-rw-r--r-- | clang/lib/Frontend/ChainedIncludesSource.cpp | 30 | ||||
-rw-r--r-- | clang/lib/Frontend/CompilerInstance.cpp | 69 | ||||
-rw-r--r-- | clang/lib/Frontend/CompilerInvocation.cpp | 4 | ||||
-rw-r--r-- | clang/lib/Frontend/FrontendAction.cpp | 129 | ||||
-rw-r--r-- | clang/lib/Frontend/PrecompiledPreamble.cpp | 25 | ||||
-rw-r--r-- | clang/lib/Frontend/SerializedDiagnosticPrinter.cpp | 5 |
8 files changed, 217 insertions, 144 deletions
diff --git a/clang/lib/Frontend/ASTMerge.cpp b/clang/lib/Frontend/ASTMerge.cpp index a4ce883..10c1045 100644 --- a/clang/lib/Frontend/ASTMerge.cpp +++ b/clang/lib/Frontend/ASTMerge.cpp @@ -41,10 +41,10 @@ void ASTMergeAction::ExecuteAction() { auto SharedState = std::make_shared<ASTImporterSharedState>( *CI.getASTContext().getTranslationUnitDecl()); for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) { - IntrusiveRefCntPtr<DiagnosticsEngine> Diags(new DiagnosticsEngine( + auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>( DiagIDs, CI.getDiagnosticOpts(), new ForwardingDiagnosticConsumer(*CI.getDiagnostics().getClient()), - /*ShouldOwnClient=*/true)); + /*ShouldOwnClient=*/true); std::unique_ptr<ASTUnit> Unit = ASTUnit::LoadFromASTFile( ASTFiles[I], CI.getPCHContainerReader(), ASTUnit::LoadEverything, nullptr, Diags, CI.getFileSystemOpts(), CI.getHeaderSearchOpts()); diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index 67ed17b..a407825 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> @@ -1204,7 +1205,7 @@ bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, // Set up diagnostics, capturing any diagnostics that would // otherwise be dropped. - Clang->setDiagnostics(&getDiagnostics()); + Clang->setDiagnostics(getDiagnosticsPtr()); // Create the target instance. if (!Clang->createTarget()) @@ -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. @@ -1424,7 +1425,7 @@ ASTUnit::getMainBufferWithPrecompiledPreamble( PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true; llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build( - PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS, + PreambleInvocationIn, MainFileBuffer.get(), Bounds, Diagnostics, VFS, PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath, Callbacks); @@ -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; @@ -1624,7 +1626,7 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( // Set up diagnostics, capturing any diagnostics that would // otherwise be dropped. - Clang->setDiagnostics(&AST->getDiagnostics()); + Clang->setDiagnostics(AST->getDiagnosticsPtr()); // Create the target instance. if (!Clang->createTarget()) @@ -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) { @@ -1773,7 +1776,7 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation( if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), PrecompilePreambleAfterNParses, - &AST->FileMgr->getVirtualFileSystem())) + AST->FileMgr->getVirtualFileSystemPtr())) return nullptr; return AST; } @@ -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(); @@ -1895,7 +1899,7 @@ bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, if (!VFS) { assert(FileMgr && "FileMgr is null on Reparse call"); - VFS = &FileMgr->getVirtualFileSystem(); + VFS = FileMgr->getVirtualFileSystemPtr(); } clearFileLevelDecls(); @@ -2209,8 +2213,10 @@ void ASTUnit::CodeComplete( bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr<PCHContainerOperations> PCHContainerOps, - DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, - FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, + llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diag, LangOptions &LangOpts, + llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr, + llvm::IntrusiveRefCntPtr<FileManager> FileMgr, + SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers, std::unique_ptr<SyntaxOnlyAction> Act) { if (!Invocation) @@ -2259,12 +2265,12 @@ void ASTUnit::CodeComplete( std::string(Clang->getFrontendOpts().Inputs[0].getFile()); // Set up diagnostics, capturing any diagnostics produced. - Clang->setDiagnostics(&Diag); + Clang->setDiagnostics(Diag); CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All, Clang->getDiagnostics(), &StoredDiagnostics, nullptr); - ProcessWarningOptions(Diag, Inv.getDiagnosticOpts(), - FileMgr.getVirtualFileSystem()); + ProcessWarningOptions(*Diag, Inv.getDiagnosticOpts(), + FileMgr->getVirtualFileSystem()); // Create the target instance. if (!Clang->createTarget()) { @@ -2281,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(); @@ -2300,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; }; @@ -2321,7 +2327,8 @@ void ASTUnit::CodeComplete( std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) { OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( - PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1); + PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(), false, + Line - 1); } // If the main file has been overridden due to the use of a preamble, @@ -2331,7 +2338,7 @@ void ASTUnit::CodeComplete( "No preamble was built, but OverrideMainBuffer is not null"); IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = - &FileMgr.getVirtualFileSystem(); + 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 ba7c767..013814a 100644 --- a/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -53,17 +53,17 @@ private: }; } // 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!"); @@ -118,13 +119,12 @@ IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource( TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), CI.getDiagnosticOpts()); - IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr<DiagnosticsEngine> Diags( - new DiagnosticsEngine(DiagID, CI.getDiagnosticOpts(), DiagClient)); + auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>( + DiagnosticIDs::create(), CI.getDiagnosticOpts(), DiagClient); auto Clang = std::make_unique<CompilerInstance>( std::move(CInvok), CI.getPCHContainerOperations()); - Clang->setDiagnostics(Diags.get()); + Clang->setDiagnostics(Diags); Clang->setTarget(TargetInfo::CreateTargetInfo( Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts())); Clang->createFileManager(); @@ -187,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 c7b82db..d64290f 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -87,8 +87,9 @@ bool CompilerInstance::shouldBuildGlobalModuleIndex() const { !DisableGeneratingGlobalModuleIndex; } -void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { - Diagnostics = Value; +void CompilerInstance::setDiagnostics( + llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Value) { + Diagnostics = std::move(Value); } void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) { @@ -160,20 +161,28 @@ llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const { return getFileManager().getVirtualFileSystem(); } -void CompilerInstance::setFileManager(FileManager *Value) { - FileMgr = Value; +llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> +CompilerInstance::getVirtualFileSystemPtr() const { + return getFileManager().getVirtualFileSystemPtr(); } -void CompilerInstance::setSourceManager(SourceManager *Value) { - SourceMgr = Value; +void CompilerInstance::setFileManager( + llvm::IntrusiveRefCntPtr<FileManager> Value) { + FileMgr = std::move(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()); @@ -340,9 +349,8 @@ IntrusiveRefCntPtr<DiagnosticsEngine> CompilerInstance::createDiagnostics( llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts, DiagnosticConsumer *Client, bool ShouldOwnClient, const CodeGenOptions *CodeGenOpts) { - IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr<DiagnosticsEngine> Diags( - new DiagnosticsEngine(DiagID, Opts)); + auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>( + DiagnosticIDs::create(), Opts); // Create the diagnostic client for reporting errors or for // implementing -verify. @@ -375,21 +383,23 @@ IntrusiveRefCntPtr<DiagnosticsEngine> CompilerInstance::createDiagnostics( FileManager *CompilerInstance::createFileManager( IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { if (!VFS) - VFS = FileMgr ? &FileMgr->getVirtualFileSystem() + VFS = FileMgr ? FileMgr->getVirtualFileSystemPtr() : createVFSFromCompilerInvocation(getInvocation(), getDiagnostics()); assert(VFS && "FileManager has no VFS?"); 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., @@ -549,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 @@ -633,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), @@ -750,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); } @@ -1216,9 +1226,9 @@ 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(&getVirtualFileSystem()); + Instance.createFileManager(getVirtualFileSystemPtr()); } if (ThreadSafeConfig) { @@ -1745,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/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index ab4384a..9f77e62 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -826,7 +826,7 @@ static bool RoundTrip(ParseFn Parse, GenerateFn Generate, // Setup a dummy DiagnosticsEngine. DiagnosticOptions DummyDiagOpts; - DiagnosticsEngine DummyDiags(new DiagnosticIDs(), DummyDiagOpts); + DiagnosticsEngine DummyDiags(DiagnosticIDs::create(), DummyDiagOpts); DummyDiags.setClient(new TextDiagnosticBuffer()); // Run the first parse on the original arguments with the dummy invocation and @@ -2685,7 +2685,7 @@ bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, std::optional<DiagnosticsEngine> IgnoringDiags; if (!Diags) { IgnoringDiagOpts.emplace(); - IgnoringDiags.emplace(new DiagnosticIDs(), *IgnoringDiagOpts, + IgnoringDiags.emplace(DiagnosticIDs::create(), *IgnoringDiagOpts, new IgnoringDiagConsumer()); Diags = &*IgnoringDiags; } diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index 1d82fc7..2d69f8c 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -9,6 +9,7 @@ #include "clang/Frontend/FrontendAction.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/DiagnosticOptions.h" @@ -39,6 +40,7 @@ #include "clang/Serialization/ASTReader.h" #include "clang/Serialization/GlobalModuleIndex.h" #include "llvm/ADT/ScopeExit.h" +#include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/BuryPointer.h" #include "llvm/Support/ErrorHandling.h" @@ -87,12 +89,25 @@ public: // reducing the granularity and making the output less useful. return; } - if (auto *DC = D->getDeclContext(); !DC || !DC->isFileContext()) { + auto *DC = D->getLexicalDeclContext(); + if (!DC || !DC->isFileContext()) { // We choose to work at namespace level to reduce complexity and the // number of cases we care about. return; } + PendingDecls.push_back(D); + if (auto *NS = dyn_cast<NamespaceDecl>(DC)) { + // Add any namespaces we have not seen before. + // Note that we filter out namespaces from DeclRead as it includes too + // all redeclarations and we only want the ones that had other used + // declarations. + while (NS && ProcessedNamespaces.insert(NS).second) { + PendingDecls.push_back(NS); + + NS = dyn_cast<NamespaceDecl>(NS->getLexicalParent()); + } + } } struct Position { @@ -141,23 +156,25 @@ public: OptionalFileEntryRef Ref; }; llvm::DenseMap<const FileEntry *, FileData> FileToRanges; + for (const Decl *D : PendingDecls) { - CharSourceRange R = SM.getExpansionRange(D->getSourceRange()); - if (!R.isValid()) - continue; + for (CharSourceRange R : getRangesToMark(D)) { + if (!R.isValid()) + continue; - auto *F = SM.getFileEntryForID(SM.getFileID(R.getBegin())); - if (F != SM.getFileEntryForID(SM.getFileID(R.getEnd()))) { - // Such cases are rare and difficult to handle. - continue; - } + auto *F = SM.getFileEntryForID(SM.getFileID(R.getBegin())); + if (F != SM.getFileEntryForID(SM.getFileID(R.getEnd()))) { + // Such cases are rare and difficult to handle. + continue; + } - auto &Data = FileToRanges[F]; - if (!Data.Ref) - Data.Ref = SM.getFileEntryRefForID(SM.getFileID(R.getBegin())); - Data.FromTo.push_back( - {Position::GetBeginSpelling(SM, R), - Position::GetEndSpelling(SM, R, D->getLangOpts())}); + auto &Data = FileToRanges[F]; + if (!Data.Ref) + Data.Ref = SM.getFileEntryRefForID(SM.getFileID(R.getBegin())); + Data.FromTo.push_back( + {Position::GetBeginSpelling(SM, R), + Position::GetEndSpelling(SM, R, D->getLangOpts())}); + } } // To simplify output, merge consecutive and intersecting ranges. @@ -188,10 +205,49 @@ public: private: std::vector<const Decl *> PendingDecls; + llvm::SmallPtrSet<const NamespaceDecl *, 0> ProcessedNamespaces; bool IsCollectingDecls = true; const SourceManager &SM; std::unique_ptr<llvm::raw_ostream> OS; + llvm::SmallVector<CharSourceRange, 2> getRangesToMark(const Decl *D) { + auto *NS = dyn_cast<NamespaceDecl>(D); + if (!NS) + return {SM.getExpansionRange(D->getSourceRange())}; + + SourceLocation LBraceLoc; + if (NS->isAnonymousNamespace()) { + LBraceLoc = NS->getLocation(); + } else { + // Start with the location of the identifier. + SourceLocation TokenBeforeLBrace = NS->getLocation(); + if (NS->hasAttrs()) { + for (auto *A : NS->getAttrs()) { + // But attributes may go after it. + if (SM.isBeforeInTranslationUnit(TokenBeforeLBrace, + A->getRange().getEnd())) { + // Give up, the attributes are often coming from macros and we + // cannot skip them reliably. + return {}; + } + } + } + auto &LangOpts = D->getLangOpts(); + // Now skip one token, the next should be the lbrace. + Token Tok; + if (Lexer::getRawToken(TokenBeforeLBrace, Tok, SM, LangOpts, true) || + Lexer::getRawToken(Tok.getEndLoc(), Tok, SM, LangOpts, true) || + Tok.getKind() != tok::l_brace) { + // On error or if we did not find the token we expected, avoid marking + // everything inside the namespace as used. + return {}; + } + LBraceLoc = Tok.getLocation(); + } + return {SM.getExpansionRange(SourceRange(NS->getBeginLoc(), LBraceLoc)), + SM.getExpansionRange(NS->getRBraceLoc())}; + } + void printJson(llvm::ArrayRef<RequiredRanges> Result) { *OS << "{\n"; *OS << R"( "required_ranges": [)" << "\n"; @@ -226,6 +282,8 @@ private: } *OS << " ]\n"; *OS << "}\n"; + + OS->flush(); } }; @@ -763,11 +821,11 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // If we're replaying the build of an AST file, import it and set up // the initial state from its build. if (ReplayASTFile) { - IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()); + IntrusiveRefCntPtr<DiagnosticsEngine> Diags = CI.getDiagnosticsPtr(); // The AST unit populates its own diagnostics engine rather than ours. - IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(new DiagnosticsEngine( - Diags->getDiagnosticIDs(), Diags->getDiagnosticOptions())); + auto ASTDiags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>( + Diags->getDiagnosticIDs(), Diags->getDiagnosticOptions()); ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false); // FIXME: What if the input is a memory buffer? @@ -787,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()); @@ -835,7 +893,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, assert(hasASTFileSupport() && "This action does not have AST file support!"); - IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()); + IntrusiveRefCntPtr<DiagnosticsEngine> Diags = CI.getDiagnosticsPtr(); // FIXME: What if the input is a memory buffer? StringRef InputFile = Input.getFile(); @@ -854,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)); @@ -1114,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()) { @@ -1194,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 146cf90..03f70b7 100644 --- a/clang/lib/Frontend/PrecompiledPreamble.cpp +++ b/clang/lib/Frontend/PrecompiledPreamble.cpp @@ -57,11 +57,9 @@ createVFSOverlayForPreamblePCH(StringRef PCHFilename, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { // We want only the PCH file from the real filesystem to be available, // so we create an in-memory VFS with just that and overlay it on top. - IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS( - new llvm::vfs::InMemoryFileSystem()); + auto PCHFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>(); PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer)); - IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay( - new llvm::vfs::OverlayFileSystem(VFS)); + auto Overlay = llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(VFS); Overlay->pushOverlay(PCHFS); return Overlay; } @@ -414,7 +412,7 @@ PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default; llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build( const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - DiagnosticsEngine &Diagnostics, + IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics, IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory, StringRef StoragePath, PreambleCallbacks &Callbacks) { @@ -463,7 +461,7 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build( llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup( Clang.get()); - Clang->setDiagnostics(&Diagnostics); + Clang->setDiagnostics(Diagnostics); // Create the target instance. if (!Clang->createTarget()) @@ -478,18 +476,19 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build( } // Clear out old caches and data. - Diagnostics.Reset(); - ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts(), *VFS); + Diagnostics->Reset(); + ProcessWarningOptions(*Diagnostics, Clang->getDiagnosticOpts(), *VFS); - VFS = - createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS); + VFS = createVFSFromCompilerInvocation(Clang->getInvocation(), *Diagnostics, + 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/Frontend/SerializedDiagnosticPrinter.cpp b/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp index 23a1f90..1f5bb47 100644 --- a/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ b/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -753,10 +753,9 @@ DiagnosticsEngine *SDiagsWriter::getMetaDiags() { // to be distinct from the engine the writer was being added to and would // normally not be used. if (!State->MetaDiagnostics) { - IntrusiveRefCntPtr<DiagnosticIDs> IDs(new DiagnosticIDs()); auto Client = new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts); - State->MetaDiagnostics = - std::make_unique<DiagnosticsEngine>(IDs, State->DiagOpts, Client); + State->MetaDiagnostics = std::make_unique<DiagnosticsEngine>( + DiagnosticIDs::create(), State->DiagOpts, Client); } return State->MetaDiagnostics.get(); } |