65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/IntrusiveRefCntPtr.h"
68#include "llvm/ADT/STLExtras.h"
69#include "llvm/ADT/ScopeExit.h"
70#include "llvm/ADT/SmallVector.h"
71#include "llvm/ADT/StringMap.h"
72#include "llvm/ADT/StringRef.h"
73#include "llvm/ADT/StringSet.h"
74#include "llvm/ADT/Twine.h"
75#include "llvm/ADT/iterator_range.h"
76#include "llvm/Bitstream/BitstreamWriter.h"
77#include "llvm/Support/Allocator.h"
78#include "llvm/Support/CrashRecoveryContext.h"
79#include "llvm/Support/DJB.h"
80#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/ErrorOr.h"
82#include "llvm/Support/MemoryBuffer.h"
83#include "llvm/Support/SaveAndRestore.h"
84#include "llvm/Support/Timer.h"
85#include "llvm/Support/VirtualFileSystem.h"
86#include "llvm/Support/raw_ostream.h"
101using namespace clang;
103using llvm::TimeRecord;
113 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
115 Start = TimeRecord::getCurrentTime();
120 TimeRecord Elapsed = TimeRecord::getCurrentTime();
122 llvm::errs() << Output <<
':';
123 Elapsed.print(Elapsed, llvm::errs());
124 llvm::errs() <<
'\n';
128 void setOutput(
const Twine &Output) {
130 this->Output = Output.str();
137static std::unique_ptr<T>
valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
140 return std::move(*Val);
147 Output = std::move(*Val);
153static std::unique_ptr<llvm::MemoryBuffer>
155 llvm::vfs::FileSystem *VFS,
156 StringRef FilePath,
bool isVolatile) {
162 llvm::MemoryBuffer *Buffer =
nullptr;
163 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
164 auto FileStatus = VFS->status(FilePath);
166 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
169 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
170 std::string MPath(RF.first);
171 auto MPathStatus = VFS->status(MPath);
173 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
174 if (MainFileID == MID) {
176 BufferOwner =
valueOrNull(VFS->getBufferForFile(RF.second, -1,
true, isVolatile));
185 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
186 std::string MPath(RB.first);
187 auto MPathStatus = VFS->status(MPath);
189 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
190 if (MainFileID == MID) {
193 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
200 if (!Buffer && !BufferOwner) {
201 BufferOwner =
valueOrNull(VFS->getBufferForFile(FilePath, -1,
true, isVolatile));
210 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
222void ASTUnit::clearFileLevelDecls() {
237ASTUnit::ASTUnit(
bool _MainFileIsAST)
239 MainFileIsAST(_MainFileIsAST), WantTiming(getenv(
"LIBCLANG_TIMING")),
240 ShouldCacheCodeCompletionResults(
false),
241 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
242 UnsafeToFree(
false) {
243 if (getenv(
"LIBCLANG_OBJTRACKING"))
253 clearFileLevelDecls();
259 if (Invocation && OwnsRemappedFileBuffers) {
265 ClearCachedCompletionResults();
267 if (getenv(
"LIBCLANG_OBJTRACKING"))
272 this->PP = std::move(PP);
277 "Bad context for source file");
285 bool &IsNestedNameSpecifier) {
286 IsNestedNameSpecifier =
false;
288 if (isa<UsingShadowDecl>(ND))
293 uint64_t Contexts = 0;
294 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
295 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
296 isa<TypeAliasTemplateDecl>(ND)) {
298 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
307 if (LangOpts.CPlusPlus)
312 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
316 if (
const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
318 if (ID->getDefinition())
325 if (isa<EnumDecl>(ND)) {
329 if (LangOpts.CPlusPlus11)
330 IsNestedNameSpecifier =
true;
331 }
else if (
const auto *
Record = dyn_cast<RecordDecl>(ND)) {
337 if (LangOpts.CPlusPlus)
338 IsNestedNameSpecifier =
true;
339 }
else if (isa<ClassTemplateDecl>(ND))
340 IsNestedNameSpecifier =
true;
341 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
347 }
else if (isa<ObjCProtocolDecl>(ND)) {
349 }
else if (isa<ObjCCategoryDecl>(ND)) {
351 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
355 IsNestedNameSpecifier =
true;
361void ASTUnit::CacheCodeCompletionResults() {
365 SimpleTimer Timer(WantTiming);
366 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
369 ClearCachedCompletionResults();
374 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
376 TheSema->CodeCompletion().GatherGlobalCodeCompletions(
377 *CachedCompletionAllocator, CCTUInfo, Results);
380 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
383 for (
auto &R : Results) {
385 case Result::RK_Declaration: {
386 bool IsNestedNameSpecifier =
false;
387 CachedCodeCompletionResult CachedResult;
388 CachedResult.Completion = R.CreateCodeCompletionString(
389 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
390 IncludeBriefCommentsInCodeCompletion);
392 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
393 CachedResult.Priority = R.Priority;
394 CachedResult.Kind = R.CursorKind;
395 CachedResult.Availability = R.Availability;
402 CachedResult.Type = 0;
411 unsigned &TypeValue = CompletionTypes[CanUsageType];
412 if (TypeValue == 0) {
413 TypeValue = CompletionTypes.size();
418 CachedResult.Type = TypeValue;
421 CachedCompletionResults.push_back(CachedResult);
424 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
425 !R.StartsNestedNameSpecifier) {
441 if (isa<NamespaceDecl>(R.Declaration) ||
442 isa<NamespaceAliasDecl>(R.Declaration))
445 if (uint64_t RemainingContexts
446 = NNSContexts & ~CachedResult.ShowInContexts) {
450 R.StartsNestedNameSpecifier =
true;
451 CachedResult.Completion = R.CreateCodeCompletionString(
452 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
453 IncludeBriefCommentsInCodeCompletion);
454 CachedResult.ShowInContexts = RemainingContexts;
457 CachedResult.Type = 0;
458 CachedCompletionResults.push_back(CachedResult);
464 case Result::RK_Keyword:
465 case Result::RK_Pattern:
470 case Result::RK_Macro: {
471 CachedCodeCompletionResult CachedResult;
472 CachedResult.Completion = R.CreateCodeCompletionString(
473 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
474 IncludeBriefCommentsInCodeCompletion);
475 CachedResult.ShowInContexts
489 CachedResult.Priority = R.Priority;
490 CachedResult.Kind = R.CursorKind;
491 CachedResult.Availability = R.Availability;
493 CachedResult.Type = 0;
494 CachedCompletionResults.push_back(CachedResult);
501 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
504void ASTUnit::ClearCachedCompletionResults() {
505 CachedCompletionResults.clear();
506 CachedCompletionTypes.clear();
507 CachedCompletionAllocator =
nullptr;
521 std::shared_ptr<TargetOptions> &TargetOpts;
524 bool InitializedLanguage =
false;
525 bool InitializedHeaderSearchPaths =
false;
531 std::shared_ptr<TargetOptions> &TargetOpts,
533 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
534 LangOpt(LangOpt), CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts),
537 bool ReadLanguageOptions(
const LangOptions &LangOpts,
538 StringRef ModuleFilename,
bool Complain,
539 bool AllowCompatibleDifferences)
override {
540 if (InitializedLanguage)
546 auto PICLevel = LangOpt.PICLevel;
547 auto PIE = LangOpt.PIE;
551 LangOpt.PICLevel = PICLevel;
554 InitializedLanguage =
true;
561 StringRef ModuleFilename,
bool Complain,
562 bool AllowCompatibleDifferences)
override {
563 this->CodeGenOpts = CGOpts;
568 StringRef ModuleFilename,
569 StringRef SpecificModuleCachePath,
570 bool Complain)
override {
572 auto ForceCheckCXX20ModulesInputFiles =
578 this->HSOpts = HSOpts;
580 ForceCheckCXX20ModulesInputFiles;
586 bool Complain)
override {
587 if (InitializedHeaderSearchPaths)
601 InitializedHeaderSearchPaths =
true;
607 StringRef ModuleFilename,
bool ReadMacros,
609 std::string &SuggestedPredefines)
override {
610 this->PPOpts = PPOpts;
615 StringRef ModuleFilename,
bool Complain,
616 bool AllowCompatibleDifferences)
override {
621 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
630 unsigned Value)
override {
636 if (!
Target || !InitializedLanguage)
668 bool CaptureNonErrorsFromIncludes =
true;
673 FilterAndStoreDiagnosticConsumer(
676 bool CaptureNonErrorsFromIncludes)
677 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
678 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
679 assert((StoredDiags || StandaloneDiags) &&
680 "No output collections were passed to StoredDiagnosticConsumer.");
685 this->LangOpts = &LangOpts;
696class CaptureDroppedDiagnostics {
698 FilterAndStoreDiagnosticConsumer Client;
700 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
703 CaptureDroppedDiagnostics(
708 Client(StoredDiags, StandaloneDiags,
709 CaptureDiagnostics !=
711 if (CaptureDiagnostics != CaptureDiagsKind::None ||
719 ~CaptureDroppedDiagnostics() {
721 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
735 auto &M =
D.getSourceManager();
736 return M.isWrittenInMainFile(M.getExpansionLoc(
D.
getLocation()));
739void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
755 StoredDiags->emplace_back(Level, Info);
756 ResultDiag = &StoredDiags->back();
759 if (StandaloneDiags) {
760 std::optional<StoredDiagnostic> StoredDiag;
762 StoredDiag.emplace(Level, Info);
763 ResultDiag = &*StoredDiag;
765 StandaloneDiags->push_back(
777 return &WriterData->Writer;
783 return &WriterData->Writer;
787std::unique_ptr<llvm::MemoryBuffer>
790 auto Buffer = FileMgr->getBufferForFile(
Filename, UserFilesAreVolatile);
792 return std::move(*Buffer);
794 *ErrorStr = Buffer.getError().message();
802 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
804 Diags->setClient(
new FilterAndStoreDiagnosticConsumer(
805 &AST.StoredDiagnostics,
nullptr,
811 WhatToLoad ToLoad, std::shared_ptr<DiagnosticOptions> DiagOpts,
817 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
820 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
821 ASTUnitCleanup(AST.get());
823 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
824 DiagCleanup(Diags.get());
826 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
828 AST->LangOpts = LangOpts ? std::make_unique<LangOptions>(*LangOpts)
829 : std::make_unique<LangOptions>();
830 AST->OnlyLocalDecls = OnlyLocalDecls;
831 AST->CaptureDiagnostics = CaptureDiagnostics;
832 AST->DiagOpts = DiagOpts;
833 AST->Diagnostics = Diags;
834 AST->FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(FileSystemOpts, VFS);
835 AST->UserFilesAreVolatile = UserFilesAreVolatile;
836 AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
837 AST->getDiagnostics(), AST->getFileManager(), UserFilesAreVolatile);
839 AST->HSOpts = std::make_unique<HeaderSearchOptions>(HSOpts);
840 AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.
getFormats().front());
841 AST->HeaderInfo.reset(
new HeaderSearch(AST->getHeaderSearchOpts(),
842 AST->getSourceManager(),
843 AST->getDiagnostics(),
846 AST->PPOpts = std::make_shared<PreprocessorOptions>();
852 AST->PP = std::make_shared<Preprocessor>(
853 *AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
854 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
860 AST->Ctx = llvm::makeIntrusiveRefCnt<ASTContext>(
863 AST->getTranslationUnitKind());
867 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
869 AST->Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
870 PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr, *AST->CodeGenOpts,
871 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
873 disableValid, AllowASTWithCompilerErrors);
875 unsigned Counter = 0;
876 AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
877 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
878 *AST->CodeGenOpts, AST->TargetOpts, AST->Target, Counter));
886 AST->Ctx->setExternalSource(AST->Reader);
899 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
903 AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
908 if (M && AST->getLangOpts().isCompilingModule() && M->
isNamedModule())
909 AST->Ctx->setCurrentNamedModule(M);
917 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
918 AST->TheSema->Initialize();
919 AST->Reader->InitializeSema(*AST->TheSema);
923 AST->getDiagnostics().getClient()->BeginSourceFile(PP.
getLangOpts(), &PP);
937class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
941 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
943 void MacroDefined(
const Token &MacroNameTok,
963 if (
const auto *ND = dyn_cast<NamedDecl>(
D)) {
964 if (
const auto *EnumD = dyn_cast<EnumDecl>(
D)) {
967 if (!EnumD->isScoped()) {
968 for (
const auto *EI : EnumD->enumerators()) {
969 if (EI->getIdentifier())
970 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
975 if (ND->getIdentifier())
976 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
978 std::string NameStr = Name.getAsString();
979 Hash = llvm::djbHash(NameStr, Hash);
984 if (
const auto *ImportD = dyn_cast<ImportDecl>(
D)) {
985 if (
const Module *Mod = ImportD->getImportedModule()) {
986 std::string ModName = Mod->getFullModuleName();
987 Hash = llvm::djbHash(ModName, Hash);
995class TopLevelDeclTrackerConsumer :
public ASTConsumer {
1000 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
1001 : Unit(_Unit), Hash(Hash) {
1005 void handleTopLevelDecl(
Decl *
D) {
1013 if (isa<ObjCMethodDecl>(
D))
1019 handleFileLevelDecl(
D);
1022 void handleFileLevelDecl(
Decl *
D) {
1024 if (
auto *NSD = dyn_cast<NamespaceDecl>(
D)) {
1025 for (
auto *I : NSD->decls())
1026 handleFileLevelDecl(I);
1031 for (
auto *TopLevelDecl :
D)
1032 handleTopLevelDecl(TopLevelDecl);
1039 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
1040 for (
auto *TopLevelDecl :
D)
1041 handleTopLevelDecl(TopLevelDecl);
1058 StringRef InFile)
override {
1060 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1062 return std::make_unique<TopLevelDeclTrackerConsumer>(
1067 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
1069 bool hasCodeCompletionSupport()
const override {
return false; }
1078 unsigned getHash()
const {
return Hash; }
1080 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1082 std::vector<LocalDeclID> takeTopLevelDeclIDs() {
1083 return std::move(TopLevelDeclIDs);
1086 void AfterPCHEmitted(
ASTWriter &Writer)
override {
1087 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1088 for (
const auto *
D : TopLevelDecls) {
1092 TopLevelDeclIDs.push_back(Writer.
getDeclID(
D));
1097 for (
auto *
D : DG) {
1102 if (isa<ObjCMethodDecl>(
D))
1105 TopLevelDecls.push_back(
D);
1109 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1110 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1115 std::vector<Decl *> TopLevelDecls;
1116 std::vector<LocalDeclID> TopLevelDeclIDs;
1141 for (
auto &SD : StoredDiagnostics) {
1142 if (SD.getLocation().isValid()) {
1144 SD.setLocation(
Loc);
1154bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1155 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1161 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1162 "VFS passed to Parse and VFS in FileMgr are different");
1164 CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1165 if (OverrideMainBuffer) {
1167 "No preamble was built, but OverrideMainBuffer is not null");
1168 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1173 auto Clang = std::make_unique<CompilerInstance>(CCInvocation,
1174 std::move(PCHContainerOps));
1177 auto CleanOnError = llvm::make_scope_exit([&]() {
1179 SavedMainFileBuffer =
nullptr;
1183 transferASTDataFromCompilerInstance(*Clang);
1184 FailedParseDiagnostics.swap(StoredDiagnostics);
1185 StoredDiagnostics.clear();
1186 NumStoredDiagnosticsFromDriver = 0;
1192 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() ==
VFS)
1193 Clang->setFileManager(FileMgr);
1195 Clang->createFileManager(std::move(VFS));
1196 FileMgr = Clang->getFileManagerPtr();
1200 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1201 CICleanup(Clang.get());
1203 OriginalSourceFile =
1204 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1211 if (!Clang->createTarget())
1214 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1215 "Invocation must have exactly one source file!");
1216 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1218 "FIXME: AST inputs not yet supported here!");
1219 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1221 "IR inputs not support here!");
1225 std::make_unique<LangOptions>(Clang->getInvocation().getLangOpts());
1226 FileSystemOpts = Clang->getFileSystemOpts();
1230 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
1232 if (!OverrideMainBuffer) {
1234 TopLevelDeclsInPreamble.clear();
1242 if (OverrideMainBuffer) {
1251 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1254 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1255 new TopLevelDeclTrackerAction(*
this));
1258 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1259 ActCleanup(Act.get());
1261 if (!Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0]))
1264 if (SavedMainFileBuffer)
1266 PreambleDiagnostics, StoredDiagnostics);
1268 PreambleSrcLocCache.clear();
1270 if (llvm::Error Err = Act->Execute()) {
1271 consumeError(std::move(Err));
1275 transferASTDataFromCompilerInstance(*Clang);
1277 Act->EndSourceFile();
1279 FailedParseDiagnostics.clear();
1281 CleanOnError.release();
1286static std::pair<unsigned, unsigned>
1290 unsigned Offset =
SM.getFileOffset(FileRange.
getBegin());
1291 unsigned EndOffset =
SM.getFileOffset(FileRange.
getEnd());
1292 return std::make_pair(Offset, EndOffset);
1319 OutDiag.
Filename = std::string(
SM.getFilename(FileLoc));
1325 for (
const auto &FixIt : InDiag.
getFixIts())
1351std::unique_ptr<llvm::MemoryBuffer>
1352ASTUnit::getMainBufferWithPrecompiledPreamble(
1353 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1356 unsigned MaxLines) {
1359 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1361 MainFilePath, UserFilesAreVolatile);
1362 if (!MainFileBuffer)
1366 PreambleInvocationIn.
getLangOpts(), *MainFileBuffer, MaxLines);
1371 if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
1382 PreambleRebuildCountdown = 1;
1383 return MainFileBuffer;
1386 PreambleDiagnostics.clear();
1387 TopLevelDeclsInPreamble.clear();
1388 PreambleSrcLocCache.clear();
1389 PreambleRebuildCountdown = 1;
1396 if (PreambleRebuildCountdown > 1) {
1397 --PreambleRebuildCountdown;
1401 assert(!Preamble &&
"No Preamble should be stored at that point");
1411 ASTUnitPreambleCallbacks Callbacks;
1413 std::optional<CaptureDroppedDiagnostics>
Capture;
1415 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1416 &NewPreambleDiagsStandalone);
1419 SimpleTimer PreambleTimer(WantTiming);
1420 PreambleTimer.setOutput(
"Precompiling preamble");
1422 const bool PreviousSkipFunctionBodies =
1428 PreambleInvocationIn, MainFileBuffer.get(), Bounds, Diagnostics, VFS,
1429 PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath,
1433 PreviousSkipFunctionBodies;
1436 Preamble = std::move(*NewPreamble);
1437 PreambleRebuildCountdown = 1;
1442 PreambleRebuildCountdown = 1;
1452 llvm_unreachable(
"unexpected BuildPreambleError");
1456 assert(Preamble &&
"Preamble wasn't built");
1458 TopLevelDecls.clear();
1459 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1460 PreambleTopLevelHashValue = Callbacks.getHash();
1465 StoredDiagnostics = std::move(NewPreambleDiags);
1466 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1471 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1472 CompletionCacheTopLevelHashValue = 0;
1473 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1476 return MainFileBuffer;
1479void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1480 assert(Preamble &&
"Should only be called when preamble was built");
1482 std::vector<Decl *> Resolved;
1483 Resolved.reserve(TopLevelDeclsInPreamble.size());
1486 for (
const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1489 if (
Decl *
D = Reader->GetLocalDecl(MF, TopLevelDecl))
1490 Resolved.push_back(
D);
1492 TopLevelDeclsInPreamble.clear();
1493 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1519 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1524 return Input.
getBuffer().getBufferIdentifier();
1530 return FE->getName();
1541 Mod = Reader->getModuleManager().getPrimaryModule();
1545std::unique_ptr<ASTUnit>
1547 std::shared_ptr<DiagnosticOptions> DiagOpts,
1550 bool UserFilesAreVolatile) {
1551 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1552 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1555 AST->DiagOpts = DiagOpts;
1556 AST->Diagnostics = Diags;
1557 AST->FileSystemOpts = CI->getFileSystemOpts();
1558 AST->Invocation = std::move(CI);
1560 llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
1561 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1562 AST->SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(
1563 AST->getDiagnostics(), *AST->FileMgr, UserFilesAreVolatile);
1570 std::shared_ptr<CompilerInvocation> CI,
1571 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1572 std::shared_ptr<DiagnosticOptions> DiagOpts,
1574 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1576 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1577 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1578 assert(CI &&
"A CompilerInvocation is required");
1580 std::unique_ptr<ASTUnit> OwnAST;
1585 create(CI, DiagOpts, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1591 if (!ResourceFilesPath.empty()) {
1595 AST->OnlyLocalDecls = OnlyLocalDecls;
1596 AST->CaptureDiagnostics = CaptureDiagnostics;
1597 if (PrecompilePreambleAfterNParses > 0)
1598 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1600 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1601 AST->IncludeBriefCommentsInCodeCompletion =
false;
1604 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1605 ASTUnitCleanup(OwnAST.get());
1607 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1608 DiagCleanup(Diags.get());
1611 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1612 CI->getFrontendOpts().DisableFree =
false;
1617 auto Clang = std::make_unique<CompilerInstance>(std::move(CI),
1618 std::move(PCHContainerOps));
1621 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1622 CICleanup(Clang.get());
1624 AST->OriginalSourceFile =
1625 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1632 if (!Clang->createTarget())
1635 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1636 "Invocation must have exactly one source file!");
1637 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1639 "FIXME: AST inputs not yet supported here!");
1640 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1642 "IR inputs not support here!");
1645 AST->TheSema.reset();
1648 AST->Reader =
nullptr;
1658 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1660 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1661 Act = TrackerAct.get();
1665 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1666 ActCleanup(TrackerAct.get());
1668 if (!Act->
BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1669 AST->transferASTDataFromCompilerInstance(*Clang);
1670 if (OwnAST && ErrAST)
1671 ErrAST->swap(OwnAST);
1676 if (Persistent && !TrackerAct) {
1677 Clang->getPreprocessor().addPPCallbacks(
1678 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1680 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1681 if (Clang->hasASTConsumer())
1682 Consumers.push_back(Clang->takeASTConsumer());
1683 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1685 Clang->setASTConsumer(
1686 std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1688 if (llvm::Error Err = Act->
Execute()) {
1689 consumeError(std::move(Err));
1690 AST->transferASTDataFromCompilerInstance(*Clang);
1691 if (OwnAST && ErrAST)
1692 ErrAST->swap(OwnAST);
1698 AST->transferASTDataFromCompilerInstance(*Clang);
1703 return OwnAST.release();
1708bool ASTUnit::LoadFromCompilerInvocation(
1709 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1710 unsigned PrecompilePreambleAfterNParses,
1715 assert(VFS &&
"VFS is null");
1718 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1719 Invocation->getFrontendOpts().DisableFree =
false;
1724 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1725 if (PrecompilePreambleAfterNParses > 0) {
1726 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1727 OverrideMainBuffer =
1728 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1734 SimpleTimer ParsingTimer(WantTiming);
1738 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1739 MemBufferCleanup(OverrideMainBuffer.get());
1741 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1744std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1745 std::shared_ptr<CompilerInvocation> CI,
1746 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1747 std::shared_ptr<DiagnosticOptions> DiagOpts,
1752 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1753 bool UserFilesAreVolatile) {
1755 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1756 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1757 AST->DiagOpts = DiagOpts;
1758 AST->Diagnostics = Diags;
1759 AST->OnlyLocalDecls = OnlyLocalDecls;
1760 AST->CaptureDiagnostics = CaptureDiagnostics;
1761 AST->TUKind = TUKind;
1762 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1763 AST->IncludeBriefCommentsInCodeCompletion
1764 = IncludeBriefCommentsInCodeCompletion;
1765 AST->Invocation = std::move(CI);
1766 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1767 AST->FileMgr = FileMgr;
1768 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1771 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1772 ASTUnitCleanup(AST.get());
1774 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1775 DiagCleanup(Diags.get());
1777 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1778 PrecompilePreambleAfterNParses,
1779 AST->FileMgr->getVirtualFileSystemPtr()))
1785 const char **ArgBegin,
const char **ArgEnd,
1786 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1787 std::shared_ptr<DiagnosticOptions> DiagOpts,
1789 bool StorePreamblesInMemory, StringRef PreambleStoragePath,
1793 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1795 bool SingleFileParse,
bool UserFilesAreVolatile,
bool ForSerialization,
1796 bool RetainExcludedConditionalBlocks, std::optional<StringRef> ModuleFormat,
1797 std::unique_ptr<ASTUnit> *ErrAST,
1799 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1805 VFS = llvm::vfs::createPhysicalFileSystem();
1809 std::shared_ptr<CompilerInvocation> CI;
1812 CaptureDroppedDiagnostics
Capture(CaptureDiagnostics, *Diags,
1813 &StoredDiagnostics,
nullptr);
1817 CIOpts.
Diags = Diags;
1826 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1836 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1838 CI->getFrontendOpts().SkipFunctionBodies =
1842 CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat);
1845 std::unique_ptr<ASTUnit> AST;
1846 AST.reset(
new ASTUnit(
false));
1847 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1848 AST->StoredDiagnostics.swap(StoredDiagnostics);
1849 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1850 AST->DiagOpts = DiagOpts;
1851 AST->Diagnostics = Diags;
1852 AST->FileSystemOpts = CI->getFileSystemOpts();
1853 AST->CodeGenOpts = std::make_unique<CodeGenOptions>(CI->getCodeGenOpts());
1856 llvm::makeIntrusiveRefCnt<FileManager>(AST->FileSystemOpts, VFS);
1857 AST->StorePreamblesInMemory = StorePreamblesInMemory;
1858 AST->PreambleStoragePath = PreambleStoragePath;
1860 AST->OnlyLocalDecls = OnlyLocalDecls;
1861 AST->CaptureDiagnostics = CaptureDiagnostics;
1862 AST->TUKind = TUKind;
1863 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1864 AST->IncludeBriefCommentsInCodeCompletion
1865 = IncludeBriefCommentsInCodeCompletion;
1866 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1867 AST->Invocation = CI;
1868 AST->SkipFunctionBodies = SkipFunctionBodies;
1869 if (ForSerialization)
1870 AST->WriterData.reset(
new ASTWriterData(*AST->ModCache, *AST->CodeGenOpts));
1876 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1877 ASTUnitCleanup(AST.get());
1879 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1880 PrecompilePreambleAfterNParses,
1885 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1901 assert(FileMgr &&
"FileMgr is null on Reparse call");
1902 VFS = FileMgr->getVirtualFileSystemPtr();
1905 clearFileLevelDecls();
1907 SimpleTimer ParsingTimer(WantTiming);
1915 Invocation->getPreprocessorOpts().clearRemappedFiles();
1917 Invocation->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1923 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1924 if (Preamble || PreambleRebuildCountdown > 0)
1925 OverrideMainBuffer =
1926 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1933 if (OverrideMainBuffer)
1938 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1942 if (!
Result && ShouldCacheCodeCompletionResults &&
1943 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1944 CacheCodeCompletionResults();
1954 SavedMainFileBuffer.reset();
1962 TopLevelDecls.clear();
1963 clearFileLevelDecls();
1976 uint64_t NormalContexts;
2009 unsigned NumResults)
override;
2011 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
2013 unsigned NumCandidates,
2015 bool Braced)
override {
2016 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
2017 OpenParLoc, Braced);
2021 return Next.getAllocator();
2025 return Next.getCodeCompletionTUInfo();
2035 unsigned NumResults,
2037 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2038 bool OnlyTagNames =
false;
2039 switch (Context.getKind()) {
2064 OnlyTagNames =
true;
2090 for (
unsigned I = 0; I != NumResults; ++I) {
2091 if (Results[I].Kind != Result::RK_Declaration)
2095 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2097 bool Hiding =
false;
2106 Hiding = (IDNS & HiddenIDNS);
2116 HiddenNames.insert(Name.getAsString());
2120void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2123 unsigned NumResults) {
2125 bool AddedResult =
false;
2128 ? NormalContexts : (1LL << Context.getKind());
2130 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2139 if ((
C->ShowInContexts & InContexts) == 0)
2146 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2153 HiddenNames.count(
C->Completion->getTypedText()))
2159 if (!Context.getPreferredType().isNull()) {
2163 Context.getPreferredType()->isAnyPointerType());
2164 }
else if (
C->Type) {
2167 Context.getPreferredType().getUnqualifiedType());
2169 if (ExpectedSTC ==
C->TypeClass) {
2171 llvm::StringMap<unsigned> &CachedCompletionTypes
2173 llvm::StringMap<unsigned>::iterator Pos
2175 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2190 Builder.AddTypedTextChunk(
C->Completion->getTypedText());
2192 Completion = Builder.TakeString();
2195 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2202 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2206 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2213 bool IncludeCodePatterns,
bool IncludeBriefComments,
2215 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2221 std::unique_ptr<SyntaxOnlyAction> Act) {
2225 SimpleTimer CompletionTimer(WantTiming);
2226 CompletionTimer.setOutput(
"Code completion @ " +
File +
":" +
2229 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2236 CachedCompletionResults.empty();
2238 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2243 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2250 LangOpts = CCInvocation->getLangOpts();
2253 LangOpts.SpellChecking =
false;
2254 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2256 auto Clang = std::make_unique<CompilerInstance>(std::move(CCInvocation),
2260 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2261 CICleanup(Clang.get());
2263 auto &Inv = Clang->getInvocation();
2264 OriginalSourceFile =
2265 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2268 Clang->setDiagnostics(
Diag);
2270 Clang->getDiagnostics(),
2271 &StoredDiagnostics,
nullptr);
2273 FileMgr->getVirtualFileSystem());
2276 if (!Clang->createTarget()) {
2280 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2281 "Invocation must have exactly one source file!");
2282 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2284 "FIXME: AST inputs not yet supported here!");
2285 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2287 "IR inputs not support here!");
2290 Clang->setFileManager(FileMgr);
2291 Clang->setSourceManager(SourceMgr);
2303 AugmentedCodeCompleteConsumer *AugmentedConsumer
2304 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2305 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2308 [&FileMgr](StringRef
Filename) -> std::optional<llvm::sys::fs::UniqueID> {
2309 if (
auto Status = FileMgr->getVirtualFileSystem().status(
Filename))
2310 return Status->getUniqueID();
2311 return std::nullopt;
2314 auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
2317 if (
auto LHSID = getUniqueID(LHS))
2318 if (
auto RHSID = getUniqueID(RHS))
2319 return *LHSID == *RHSID;
2327 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2328 if (Preamble &&
Line > 1 && hasSameUniqueID(
File, OriginalSourceFile)) {
2329 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2330 PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(),
false,
2336 if (OverrideMainBuffer) {
2338 "No preamble was built, but OverrideMainBuffer is not null");
2341 FileMgr->getVirtualFileSystemPtr();
2342 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2343 OverrideMainBuffer.get());
2348 OwnedBuffers.push_back(OverrideMainBuffer.release());
2355 if (!Clang->getLangOpts().Modules)
2361 if (Act->BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
2362 if (llvm::Error Err = Act->Execute()) {
2363 consumeError(std::move(Err));
2365 Act->EndSourceFile();
2370 if (HadModuleLoaderFatalFailure)
2376 if (llvm::Error Err = llvm::writeToOutput(
2377 File, [
this](llvm::raw_ostream &Out) {
2378 return serialize(Out) ? llvm::make_error<llvm::StringError>(
2379 "ASTUnit serialization failed",
2380 llvm::inconvertibleErrorCode())
2381 : llvm::Error::success();
2383 consumeError(std::move(Err));
2390 Sema &S, raw_ostream &OS) {
2391 Writer.
WriteAST(&S, std::string(),
nullptr,
"");
2394 if (!Buffer.empty())
2395 OS.write(Buffer.data(), Buffer.size());
2405 llvm::BitstreamWriter Stream(Buffer);
2407 ASTWriter Writer(Stream, Buffer, *ModCache, *CodeGenOpts, {});
2411void ASTUnit::TranslateStoredDiagnostics(
2421 Result.reserve(Diags.size());
2423 for (
const auto &SD : Diags) {
2425 if (SD.Filename.empty())
2431 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2432 if (ItFileID == PreambleSrcLocCache.end()) {
2435 PreambleSrcLocCache[SD.Filename] = FileLoc;
2437 FileLoc = ItFileID->getValue();
2446 Ranges.reserve(SD.Ranges.size());
2447 for (
const auto &
Range : SD.Ranges) {
2454 FixIts.reserve(SD.FixIts.size());
2455 for (
const auto &FixIt : SD.FixIts) {
2465 SD.Message,
Loc, Ranges, FixIts));
2487 assert(
SM.isLocalSourceLocation(FileLoc));
2488 auto [FID, Offset] =
SM.getDecomposedLoc(FileLoc);
2492 std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2494 Decls = std::make_unique<LocDeclsTy>();
2496 std::pair<unsigned, Decl *> LocDecl(Offset,
D);
2498 if (Decls->empty() || Decls->back().first <= Offset) {
2499 Decls->push_back(LocDecl);
2503 LocDeclsTy::iterator I =
2504 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2506 Decls->insert(I, LocDecl);
2511 if (
File.isInvalid())
2515 assert(Ctx->getExternalSource() &&
"No external source!");
2516 return Ctx->getExternalSource()->FindFileRegionDecls(
File, Offset, Length,
2520 FileDeclsTy::iterator I = FileDecls.find(
File);
2521 if (I == FileDecls.end())
2525 if (LocDecls.empty())
2528 LocDeclsTy::iterator BeginIt =
2529 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2530 return LD.first < Offset;
2532 if (BeginIt != LocDecls.begin())
2538 while (BeginIt != LocDecls.begin() &&
2539 BeginIt->second->isTopLevelDeclInObjCContainer())
2542 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2543 LocDecls, std::make_pair(Offset + Length, (
Decl *)
nullptr),
2544 llvm::less_first());
2545 if (EndIt != LocDecls.end())
2548 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2549 Decls.push_back(DIt->second);
2553 unsigned Line,
unsigned Col)
const {
2556 return SM.getMacroArgExpandedLocation(
Loc);
2560 unsigned Offset)
const {
2578 if (SourceMgr->
isInFileID(
Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2600 Offs < Preamble->getBounds().Size) {
2652llvm::iterator_range<PreprocessingRecord::iterator>
2656 Mod = Reader->getModuleManager().getPrimaryModule();
2657 return Reader->getModulePreprocessedEntities(Mod);
2661 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2670 Mod = Reader->getModuleManager().getPrimaryModule();
2671 for (
const auto *
D : Reader->getModuleFileLevelDecls(Mod)) {
2672 if (!Fn(context,
D))
2681 TL != TLEnd; ++TL) {
2682 if (!Fn(context, *TL))
2691 return std::nullopt;
2696 case serialization::MK_ImplicitModule:
2697 case serialization::MK_ExplicitModule:
2698 case serialization::MK_PrebuiltModule:
2700 case serialization::MK_PCH:
2703 case serialization::MK_Preamble:
2705 case serialization::MK_MainFile:
2714 return std::nullopt;
2725 if (LangOpts.OpenCL)
2727 else if (LangOpts.CUDA)
2729 else if (LangOpts.CPlusPlus)
2745ASTUnit::ConcurrencyState::ConcurrencyState() {
2746 Mutex =
new std::recursive_mutex;
2749ASTUnit::ConcurrencyState::~ConcurrencyState() {
2750 delete static_cast<std::recursive_mutex *
>(Mutex);
2753void ASTUnit::ConcurrencyState::start() {
2754 bool acquired =
static_cast<std::recursive_mutex *
>(Mutex)->try_lock();
2755 assert(acquired &&
"Concurrent access to ASTUnit!");
2758void ASTUnit::ConcurrencyState::finish() {
2759 static_cast<std::recursive_mutex *
>(Mutex)->unlock();
2764ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2765ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2766void ASTUnit::ConcurrencyState::start() {}
2767void ASTUnit::ConcurrencyState::finish() {}
Defines the clang::ASTContext interface.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
static void CalculateHiddenNames(const CodeCompletionContext &Context, CodeCompletionResult *Results, unsigned NumResults, ASTContext &Ctx, llvm::StringSet< llvm::BumpPtrAllocator > &HiddenNames)
Helper function that computes which global names are hidden by the local code-completion results.
static uint64_t getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown.
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash)
Add the given declaration to the hash of all top-level entities.
static bool moveOnNoError(llvm::ErrorOr< T > Val, T &Output)
static std::unique_ptr< T > valueOrNull(llvm::ErrorOr< std::unique_ptr< T > > Val)
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, raw_ostream &OS)
static std::unique_ptr< llvm::MemoryBuffer > getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation, llvm::vfs::FileSystem *VFS, StringRef FilePath, bool isVolatile)
Get a source buffer for MainFilePath, handling all file-to-file and file-to-buffer remappings inside ...
const unsigned DefaultPreambleRebuildInterval
After failing to build a precompiled preamble (due to errors in the source that occurs in the preambl...
static void checkAndRemoveNonDriverDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiags)
static bool isInMainFile(const clang::Diagnostic &D)
static ASTUnit::StandaloneDiagnostic makeStandaloneDiagnostic(const LangOptions &LangOpts, const StoredDiagnostic &InDiag)
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, const LangOptions &LangOpts, const FixItHint &InFix)
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash)
Add the given macro to the hash of all top-level entities.
Defines the Diagnostic-related interfaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::FileManager interface and associated types.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
Defines the PPCallbacks interface.
Defines the clang::Preprocessor interface.
This file declares facilities that support code completion.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TargetOptions class.
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
comments::CommandTraits & getCommentCommandTraits() const
const LangOptions & getLangOpts() const
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Abstract base class to use for AST consumer-based frontend actions.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Abstract interface for callback invocations by the ASTReader.
@ ARR_None
The client can't handle any AST loading failures.
@ Success
The control block was read successfully.
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
@ Failure
The AST file itself appears corrupted.
@ VersionMismatch
The AST file was written by a different version of Clang.
@ HadErrors
The AST file has errors.
@ Missing
The AST file was missing.
Utility class for loading a ASTContext from an AST file.
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
void enableSourceFileDiagnostics()
Enable source-range based diagnostic messages.
void addFileLevelDecl(Decl *D)
Add a new local file-level declaration.
const FileManager & getFileManager() const
void CodeComplete(StringRef File, unsigned Line, unsigned Column, ArrayRef< RemappedFile > RemappedFiles, bool IncludeMacros, bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr< PCHContainerOperations > PCHContainerOps, 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)
Perform code completion at the given file, line, and column within this translation unit.
cached_completion_iterator cached_completion_end()
bool serialize(raw_ostream &OS)
Serialize this translation unit with the given output stream.
ASTDeserializationListener * getDeserializationListener()
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles={}, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Reparse the source files using the same command-line options that were originally used to produce thi...
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
const DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
void ResetForParse()
Free data that will be re-generated on the next parse.
llvm::IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr()
InputKind getInputKind() const
Determine the input kind this AST unit represents.
OptionalFileEntryRef getPCHFile()
Get the PCH file if one was included.
StringRef getMainFileName() const
static std::unique_ptr< ASTUnit > LoadFromASTFile(StringRef Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, const HeaderSearchOptions &HSOpts, const LangOptions *LangOpts=nullptr, bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, bool AllowASTWithCompilerErrors=false, bool UserFilesAreVolatile=false, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=llvm::vfs::getRealFileSystem())
Create a ASTUnit from an AST file.
SourceLocation mapLocationToPreamble(SourceLocation Loc) const
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
cached_completion_iterator cached_completion_begin()
const LangOptions & getLangOpts() const
bool isMainFileAST() const
std::vector< Decl * >::iterator top_level_iterator
const SourceManager & getSourceManager() const
SourceLocation getEndOfPreambleFileID() const
llvm::IntrusiveRefCntPtr< DiagnosticsEngine > getDiagnosticsPtr()
static ASTUnit * LoadFromCompilerInvocationAction(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, FrontendAction *Action=nullptr, ASTUnit *Unit=nullptr, bool Persistent=true, StringRef ResourceFilesPath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, unsigned PrecompilePreambleAfterNParses=0, bool CacheCodeCompletionResults=false, bool UserFilesAreVolatile=false, std::unique_ptr< ASTUnit > *ErrAST=nullptr)
Create an ASTUnit from a source file, via a CompilerInvocation object, by invoking the optionally pro...
@ LoadASTOnly
Load the AST, but do not restore Sema state.
@ LoadEverything
Load everything, including Sema.
top_level_iterator top_level_end()
SourceLocation getStartOfMainFileID() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
IntrusiveRefCntPtr< FileManager > getFileManagerPtr()
bool(*)(void *context, const Decl *D) DeclVisitorFn
Type for a function iterating over a number of declarations.
bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn)
Iterate over local declarations (locally parsed if this is a parsed source file or the loaded declara...
llvm::iterator_range< PreprocessingRecord::iterator > getLocalPreprocessingEntities() const
Returns an iterator range for the local preprocessing entities of the local Preprocessor,...
top_level_iterator top_level_begin()
std::vector< CachedCodeCompletionResult >::iterator cached_completion_iterator
ASTMutationListener * getASTMutationListener()
TranslationUnitKind getTranslationUnitKind() const
Determine what kind of translation unit this AST represents.
static std::unique_ptr< ASTUnit > LoadFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool StorePreamblesInMemory=false, StringRef PreambleStoragePath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, ArrayRef< RemappedFile > RemappedFiles={}, bool RemappedFilesKeepOriginalName=true, unsigned PrecompilePreambleAfterNParses=0, TranslationUnitKind TUKind=TU_Complete, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=false, bool AllowPCHWithCompilerErrors=false, SkipFunctionBodiesScope SkipFunctionBodies=SkipFunctionBodiesScope::None, bool SingleFileParse=false, bool UserFilesAreVolatile=false, bool ForSerialization=false, bool RetainExcludedConditionalBlocks=false, std::optional< StringRef > ModuleFormat=std::nullopt, std::unique_ptr< ASTUnit > *ErrAST=nullptr, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
LoadFromCommandLine - Create an ASTUnit from a vector of command line arguments, which must specify e...
void setPreprocessor(std::shared_ptr< Preprocessor > pp)
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
bool Save(StringRef File)
Save this translation unit to a file with the given name.
const HeaderSearchOptions & getHeaderSearchOpts() const
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< DiagnosticOptions > DiagOpts, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, CaptureDiagsKind CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
void addTopLevelDecl(Decl *D)
Add a new top-level declaration.
bool isInMainFileID(SourceLocation Loc) const
bool isModuleFile() const
Returns true if the ASTUnit was constructed from a serialized module file.
void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls)
Get the decls that are contained in a file in the Offset/Length range.
const ASTContext & getASTContext() const
bool isInPreambleFileID(SourceLocation Loc) const
SourceLocation mapLocationFromPreamble(SourceLocation Loc) const
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
std::pair< std::string, llvm::MemoryBuffer * > RemappedFile
A mapping from a file name to the memory buffer that stores the remapped contents of that file.
Writes an AST file containing the contents of a translation unit.
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
ASTFileSignature WriteAST(llvm::PointerUnion< Sema *, Preprocessor * > Subject, StringRef OutputFile, Module *WritingModule, StringRef isysroot, bool ShouldCacheASTInMemory=false)
Write a precompiled header or a module with the AST produced by the Sema object, or a dependency scan...
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
SourceLocation getEnd() const
SourceLocation getBegin() const
Abstract interface for a consumer of code-completion information.
bool includeFixIts() const
Whether to include completion items with small fix-its, e.g.
bool loadExternal() const
Hint whether to load data from the external AST in order to provide full results.
Options controlling the behavior of code completion.
unsigned IncludeCodePatterns
Show code patterns in code completion results.
unsigned IncludeFixIts
Include results after corrections (small fix-its), e.g.
unsigned LoadExternal
Hint whether to load data from the external AST to provide full results.
unsigned IncludeMacros
Show macros in code completion results.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
unsigned IncludeGlobals
Show top-level decls in code completion results.
An allocator used specifically for the purpose of code completion.
A builder class used to construct new code-completion strings.
The context in which code completion occurred, so that the code-completion consumer can process the r...
@ CCC_TypeQualifiers
Code completion within a type-qualifier list.
@ CCC_ObjCMessageReceiver
Code completion occurred where an Objective-C message receiver is expected.
@ CCC_PreprocessorExpression
Code completion occurred within a preprocessor expression.
@ CCC_ObjCCategoryName
Code completion where an Objective-C category name is expected.
@ CCC_ObjCIvarList
Code completion occurred within the instance variable list of an Objective-C interface,...
@ CCC_Statement
Code completion occurred where a statement (or declaration) is expected in a function,...
@ CCC_Type
Code completion occurred where a type name is expected.
@ CCC_ArrowMemberAccess
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
@ CCC_ClassStructUnion
Code completion occurred within a class, struct, or union.
@ CCC_ObjCInterface
Code completion occurred within an Objective-C interface, protocol, or category interface.
@ CCC_ObjCPropertyAccess
Code completion occurred on the right-hand side of an Objective-C property access expression.
@ CCC_Expression
Code completion occurred where an expression is expected.
@ CCC_SelectorName
Code completion for a selector, as in an @selector expression.
@ CCC_TopLevelOrExpression
Code completion at a top level, i.e.
@ CCC_EnumTag
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
@ CCC_UnionTag
Code completion occurred after the "union" keyword, to indicate a union name.
@ CCC_ParenthesizedExpression
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
@ CCC_TopLevel
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope.
@ CCC_ClassOrStructTag
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name.
@ CCC_ObjCClassMessage
Code completion where an Objective-C class message is expected.
@ CCC_ObjCImplementation
Code completion occurred within an Objective-C implementation or category implementation.
@ CCC_IncludedFile
Code completion inside the filename part of a #include directive.
@ CCC_ObjCInstanceMessage
Code completion where an Objective-C instance message is expected.
@ CCC_SymbolOrNewName
Code completion occurred where both a new name and an existing symbol is permissible.
@ CCC_Recovery
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
@ CCC_ObjCProtocolName
Code completion occurred where a protocol name is expected.
@ CCC_OtherWithMacros
An unspecified code-completion context where we should also add macro completions.
@ CCC_NewName
Code completion occurred where a new name is expected.
@ CCC_MacroNameUse
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
@ CCC_Symbol
Code completion occurred where an existing name(such as type, function or variable) is expected.
@ CCC_Attribute
Code completion of an attribute name.
@ CCC_Other
An unspecified code-completion context.
@ CCC_DotMemberAccess
Code completion occurred on the right-hand side of a member access expression using the dot operator.
@ CCC_MacroName
Code completion occurred where an macro is being defined.
@ CCC_Namespace
Code completion occurred where a namespace or namespace alias is expected.
@ CCC_PreprocessorDirective
Code completion occurred where a preprocessor directive is expected.
@ CCC_NaturalLanguage
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
@ CCC_ObjCInterfaceName
Code completion where the name of an Objective-C class is expected.
@ CCC_ObjCClassForwardDecl
Captures a result of code completion.
A "string" used to describe how code completion can be performed for an entity.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
std::shared_ptr< Preprocessor > getPreprocessorPtr()
std::unique_ptr< Sema > takeSema()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
bool hasASTContext() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
std::shared_ptr< CompilerInvocation > getInvocationPtr()
bool hadModuleLoaderFatalFailure() const
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
CompilerInvocation & getInvocation()
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager and virtual file system.
bool hasPreprocessor() const
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
DiagnosticOptions & getDiagnosticOpts()
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
bool isFileContext() const
bool isTranslationUnit() const
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Decl - This represents one declaration (or definition), e.g.
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
bool isInvalidDecl() const
SourceLocation getLocation() const
@ IDNS_NonMemberOperator
This declaration is a C++ operator declared in a non-class context.
@ IDNS_Ordinary
Ordinary names.
@ IDNS_Type
Types, declared with 'struct foo', typedefs, etc.
@ IDNS_Member
Members, declared with object declarations within tag definitions.
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
DeclContext * getDeclContext()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
The name of a declaration.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
SourceManager & getSourceManager() const
bool hasSourceManager() const
Concrete class used by the front-end to report problems and issues.
void setNumWarnings(unsigned NumWarnings)
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Level
The level of the diagnostic, after it has been through mapping.
DiagnosticConsumer * getClient()
unsigned getNumWarnings() const
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
Cached information about one file (either on disk or in the virtual file system).
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
llvm::vfs::FileSystem & getVirtualFileSystem() const
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
void setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Keeps track of options that affect how file operations are performed.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
bool BeforePreviousInsertions
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Abstract base class for actions which can be performed by the frontend.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned SkipFunctionBodies
Skip over function bodies to speed up parsing in cases you do not need them (e.g.
CodeCompleteOptions CodeCompleteOpts
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
A SourceLocation and its associated SourceManager.
const SourceManager & getManager() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
@ CMK_ModuleMap
Compiling a module from a module map.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
CommentOptions CommentOpts
Options for parsing comments.
bool isCompilingModule() const
Are we compiling a module?
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
The module cache used for compiling modules implicitly.
Describes a module or submodule.
bool isNamedModule() const
Does this Module is a named module of a standard named module?
This represents a decl that may have a name.
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::ArrayRef< llvm::StringRef > getFormats() const =0
Equivalent to the format passed to -fmodule-format=.
This interface provides a way to observe the actions of the preprocessor as it does its thing.
A set of callbacks to gather useful information while building a preamble.
static llvm::ErrorOr< PrecompiledPreamble > Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, IntrusiveRefCntPtr< DiagnosticsEngine > Diagnostics, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::shared_ptr< PCHContainerOperations > PCHContainerOps, bool StoreInMemory, StringRef StoragePath, PreambleCallbacks &Callbacks)
Try to build PrecompiledPreamble for Invocation.
Iteration over the preprocessed entities.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
bool SingleFileParseMode
When enabled, preprocessor is in a mode for parsing a single file only.
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
bool RetainExcludedConditionalBlocks
When enabled, excluded conditional blocks retain in the main file.
void clearRemappedFiles()
void addRemappedFile(StringRef From, StringRef To)
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
FileManager & getFileManager() const
void Initialize(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize the preprocessor using information about the target.
IdentifierTable & getIdentifierTable()
Builtin::Context & getBuiltinInfo()
const LangOptions & getLangOpts() const
void setCounterValue(unsigned V)
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
DiagnosticsEngine & getDiagnostics() const
SelectorTable & getSelectorTable()
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Sema - This implements semantic analysis and AST building for C.
const LangOptions & getLangOpts() const
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isInFileID(SourceLocation Loc, FileID FID, unsigned *RelativeOffset=nullptr) const
Given a specific FileID, returns true if Loc is inside that FileID chunk and sets relative offset (of...
FileID getPreambleFileID() const
Get the file ID for the precompiled preamble if there is one.
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
ArrayRef< FixItHint > getFixIts() const
ArrayRef< CharSourceRange > getRanges() const
DiagnosticsEngine::Level getLevel() const
const FullSourceLoc & getLocation() const
StringRef getMessage() const
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Options for controlling the target.
Token - This structure provides full information about a lexed token.
IdentifierInfo * getIdentifierInfo() const
Information about a module that has been loaded by the ASTReader.
FileEntryRef File
The file entry for the module file.
std::string FileName
The file name of the module file.
ModuleKind Kind
The type of this module.
@ CXCursor_MacroDefinition
Defines the clang::TargetInfo interface.
@ FixIt
Parse and apply any fixits to the source.
@ MK_MainFile
File is a PCH file treated as the actual main file.
The JSON file list parser is used to communicate input to InstallAPI.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromOverlayFiles(ArrayRef< std::string > VFSOverlayFiles, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
SkipFunctionBodiesScope
Enumerates the available scopes for skipping function bodies.
@ CCF_ExactTypeMatch
Divide by this factor when a code-completion result's type exactly matches the type we expect.
@ CCF_SimilarTypeMatch
Divide by this factor when a code-completion result's type is similar to the type we expect (e....
@ Parse
Parse the block; this code is always used.
std::unique_ptr< CompilerInvocation > createInvocation(ArrayRef< const char * > Args, CreateInvocationOptions Opts={})
Interpret clang arguments in preparation to parse a file.
Language
The language for the input, used to select and validate the language standard and possible actions.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion.
CaptureDiagsKind
Enumerates the available kinds for capturing diagnostics.
@ AllWithoutNonErrorsFromIncludes
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
IntrusiveRefCntPtr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
TranslationUnitKind
Describes the kind of translation unit being processed.
@ TU_Complete
The translation unit is a complete translation unit.
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
const FunctionProtoType * T
@ CCP_NestedNameSpecifier
Priority for a nested-name-specifier.
@ CCP_CodePattern
Priority for a code pattern.
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name.
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ All
Disable validation for all kinds.
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
@ CouldntCreateTargetInfo
llvm::StringRef getAsString(SyncScope S)
QualType getDeclUsageType(ASTContext &C, NestedNameSpecifier Qualifier, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression.
llvm::BitstreamWriter Stream
SmallString< 128 > Buffer
ASTWriterData(ModuleCache &ModCache, const CodeGenOptions &CGOpts)
DiagnosticsEngine::Level Level
std::vector< std::pair< unsigned, unsigned > > Ranges
std::vector< StandaloneFixIt > FixIts
std::pair< unsigned, unsigned > InsertFromRange
std::pair< unsigned, unsigned > RemoveRange
bool BeforePreviousInsertions
Optional inputs to createInvocation.
IntrusiveRefCntPtr< DiagnosticsEngine > Diags
Receives diagnostics encountered while parsing command-line flags.
bool ProbePrecompiled
Allow the driver to probe the filesystem for PCH files.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS
Used e.g.
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
unsigned Size
Size of the preamble in bytes.
Describes how types, statements, expressions, and declarations should be printed.