67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/IntrusiveRefCntPtr.h"
70#include "llvm/ADT/STLExtras.h"
71#include "llvm/ADT/ScopeExit.h"
72#include "llvm/ADT/SmallVector.h"
73#include "llvm/ADT/StringMap.h"
74#include "llvm/ADT/StringRef.h"
75#include "llvm/ADT/StringSet.h"
76#include "llvm/ADT/Twine.h"
77#include "llvm/ADT/iterator_range.h"
78#include "llvm/Bitstream/BitstreamWriter.h"
79#include "llvm/Support/Allocator.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/CrashRecoveryContext.h"
82#include "llvm/Support/DJB.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/ErrorOr.h"
85#include "llvm/Support/FileSystem.h"
86#include "llvm/Support/MemoryBuffer.h"
87#include "llvm/Support/SaveAndRestore.h"
88#include "llvm/Support/Timer.h"
89#include "llvm/Support/VirtualFileSystem.h"
90#include "llvm/Support/raw_ostream.h"
105using namespace clang;
107using llvm::TimeRecord;
117 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
119 Start = TimeRecord::getCurrentTime();
124 TimeRecord Elapsed = TimeRecord::getCurrentTime();
126 llvm::errs() << Output <<
':';
127 Elapsed.print(Elapsed, llvm::errs());
128 llvm::errs() <<
'\n';
132 void setOutput(
const Twine &Output) {
134 this->Output = Output.str();
141static std::unique_ptr<T>
valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
144 return std::move(*Val);
151 Output = std::move(*Val);
157static std::unique_ptr<llvm::MemoryBuffer>
159 llvm::vfs::FileSystem *VFS,
160 StringRef FilePath,
bool isVolatile) {
166 llvm::MemoryBuffer *Buffer =
nullptr;
167 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
168 auto FileStatus = VFS->status(FilePath);
170 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
173 for (
const auto &RF : PreprocessorOpts.RemappedFiles) {
174 std::string MPath(RF.first);
175 auto MPathStatus = VFS->status(MPath);
177 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
178 if (MainFileID == MID) {
180 BufferOwner =
valueOrNull(VFS->getBufferForFile(RF.second, -1,
true, isVolatile));
189 for (
const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
190 std::string MPath(RB.first);
191 auto MPathStatus = VFS->status(MPath);
193 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
194 if (MainFileID == MID) {
197 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
204 if (!Buffer && !BufferOwner) {
205 BufferOwner =
valueOrNull(VFS->getBufferForFile(FilePath, -1,
true, isVolatile));
214 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
226void ASTUnit::clearFileLevelDecls() {
241ASTUnit::ASTUnit(
bool _MainFileIsAST)
242 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv(
"LIBCLANG_TIMING")),
243 ShouldCacheCodeCompletionResults(
false),
244 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
245 UnsafeToFree(
false) {
246 if (getenv(
"LIBCLANG_OBJTRACKING"))
256 clearFileLevelDecls();
262 if (Invocation && OwnsRemappedFileBuffers) {
268 ClearCachedCompletionResults();
270 if (getenv(
"LIBCLANG_OBJTRACKING"))
275 this->PP = std::move(PP);
280 "Bad context for source file");
288 bool &IsNestedNameSpecifier) {
289 IsNestedNameSpecifier =
false;
291 if (isa<UsingShadowDecl>(ND))
296 uint64_t Contexts = 0;
297 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
298 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
299 isa<TypeAliasTemplateDecl>(ND)) {
301 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
310 if (LangOpts.CPlusPlus)
315 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
319 if (
const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
321 if (ID->getDefinition())
328 if (isa<EnumDecl>(ND)) {
332 if (LangOpts.CPlusPlus11)
333 IsNestedNameSpecifier =
true;
334 }
else if (
const auto *
Record = dyn_cast<RecordDecl>(ND)) {
340 if (LangOpts.CPlusPlus)
341 IsNestedNameSpecifier =
true;
342 }
else if (isa<ClassTemplateDecl>(ND))
343 IsNestedNameSpecifier =
true;
344 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
350 }
else if (isa<ObjCProtocolDecl>(ND)) {
352 }
else if (isa<ObjCCategoryDecl>(ND)) {
354 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
358 IsNestedNameSpecifier =
true;
364void ASTUnit::CacheCodeCompletionResults() {
368 SimpleTimer Timer(WantTiming);
369 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
372 ClearCachedCompletionResults();
377 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
379 TheSema->CodeCompletion().GatherGlobalCodeCompletions(
380 *CachedCompletionAllocator, CCTUInfo, Results);
383 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
386 for (
auto &R : Results) {
388 case Result::RK_Declaration: {
389 bool IsNestedNameSpecifier =
false;
390 CachedCodeCompletionResult CachedResult;
391 CachedResult.Completion = R.CreateCodeCompletionString(
392 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
393 IncludeBriefCommentsInCodeCompletion);
395 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
396 CachedResult.Priority = R.Priority;
397 CachedResult.Kind = R.CursorKind;
398 CachedResult.Availability = R.Availability;
405 CachedResult.Type = 0;
414 unsigned &TypeValue = CompletionTypes[CanUsageType];
415 if (TypeValue == 0) {
416 TypeValue = CompletionTypes.size();
421 CachedResult.Type = TypeValue;
424 CachedCompletionResults.push_back(CachedResult);
427 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
428 !R.StartsNestedNameSpecifier) {
444 if (isa<NamespaceDecl>(R.Declaration) ||
445 isa<NamespaceAliasDecl>(R.Declaration))
448 if (uint64_t RemainingContexts
449 = NNSContexts & ~CachedResult.ShowInContexts) {
453 R.StartsNestedNameSpecifier =
true;
454 CachedResult.Completion = R.CreateCodeCompletionString(
455 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
456 IncludeBriefCommentsInCodeCompletion);
457 CachedResult.ShowInContexts = RemainingContexts;
460 CachedResult.Type = 0;
461 CachedCompletionResults.push_back(CachedResult);
467 case Result::RK_Keyword:
468 case Result::RK_Pattern:
473 case Result::RK_Macro: {
474 CachedCodeCompletionResult CachedResult;
475 CachedResult.Completion = R.CreateCodeCompletionString(
476 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
477 IncludeBriefCommentsInCodeCompletion);
478 CachedResult.ShowInContexts
492 CachedResult.Priority = R.Priority;
493 CachedResult.Kind = R.CursorKind;
494 CachedResult.Availability = R.Availability;
496 CachedResult.Type = 0;
497 CachedCompletionResults.push_back(CachedResult);
504 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
507void ASTUnit::ClearCachedCompletionResults() {
508 CachedCompletionResults.clear();
509 CachedCompletionTypes.clear();
510 CachedCompletionAllocator =
nullptr;
523 std::shared_ptr<TargetOptions> &TargetOpts;
526 bool InitializedLanguage =
false;
527 bool InitializedHeaderSearchPaths =
false;
533 std::shared_ptr<TargetOptions> &TargetOpts,
535 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
536 LangOpt(LangOpt), TargetOpts(TargetOpts),
Target(
Target),
539 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
540 bool AllowCompatibleDifferences)
override {
541 if (InitializedLanguage)
547 auto PICLevel = LangOpt.PICLevel;
548 auto PIE = LangOpt.PIE;
552 LangOpt.PICLevel = PICLevel;
555 InitializedLanguage =
true;
562 StringRef SpecificModuleCachePath,
563 bool Complain)
override {
565 auto ForceCheckCXX20ModulesInputFiles =
571 this->HSOpts = HSOpts;
573 ForceCheckCXX20ModulesInputFiles;
579 bool Complain)
override {
580 if (InitializedHeaderSearchPaths)
594 InitializedHeaderSearchPaths =
true;
600 bool ReadMacros,
bool Complain,
601 std::string &SuggestedPredefines)
override {
602 this->PPOpts = PPOpts;
606 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
607 bool AllowCompatibleDifferences)
override {
612 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
621 unsigned Value)
override {
627 if (!
Target || !InitializedLanguage)
659 bool CaptureNonErrorsFromIncludes =
true;
664 FilterAndStoreDiagnosticConsumer(
667 bool CaptureNonErrorsFromIncludes)
668 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
669 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
670 assert((StoredDiags || StandaloneDiags) &&
671 "No output collections were passed to StoredDiagnosticConsumer.");
676 this->LangOpts = &LangOpts;
687class CaptureDroppedDiagnostics {
689 FilterAndStoreDiagnosticConsumer Client;
691 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
694 CaptureDroppedDiagnostics(
699 Client(StoredDiags, StandaloneDiags,
700 CaptureDiagnostics !=
702 if (CaptureDiagnostics != CaptureDiagsKind::None ||
710 ~CaptureDroppedDiagnostics() {
712 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
726 auto &M =
D.getSourceManager();
727 return M.isWrittenInMainFile(M.getExpansionLoc(
D.
getLocation()));
730void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
746 StoredDiags->emplace_back(Level, Info);
747 ResultDiag = &StoredDiags->back();
750 if (StandaloneDiags) {
751 std::optional<StoredDiagnostic> StoredDiag;
753 StoredDiag.emplace(Level, Info);
754 ResultDiag = &*StoredDiag;
756 StandaloneDiags->push_back(
768 return &WriterData->Writer;
774 return &WriterData->Writer;
778std::unique_ptr<llvm::MemoryBuffer>
781 auto Buffer = FileMgr->getBufferForFile(
Filename, UserFilesAreVolatile);
783 return std::move(*Buffer);
785 *ErrorStr = Buffer.getError().message();
793 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
795 Diags->setClient(
new FilterAndStoreDiagnosticConsumer(
796 &AST.StoredDiagnostics,
nullptr,
804 std::shared_ptr<HeaderSearchOptions> HSOpts,
805 std::shared_ptr<LangOptions> LangOpts,
bool OnlyLocalDecls,
808 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
811 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
812 ASTUnitCleanup(AST.get());
814 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
815 DiagCleanup(Diags.get());
817 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
819 AST->LangOpts = LangOpts ? LangOpts : std::make_shared<LangOptions>();
820 AST->OnlyLocalDecls = OnlyLocalDecls;
821 AST->CaptureDiagnostics = CaptureDiagnostics;
822 AST->Diagnostics = Diags;
823 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
824 AST->UserFilesAreVolatile = UserFilesAreVolatile;
826 AST->getFileManager(),
827 UserFilesAreVolatile);
829 AST->HSOpts = HSOpts ? HSOpts : std::make_shared<HeaderSearchOptions>();
830 AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.
getFormats().front());
832 AST->getSourceManager(),
833 AST->getDiagnostics(),
836 AST->PPOpts = std::make_shared<PreprocessorOptions>();
842 AST->PP = std::make_shared<Preprocessor>(
843 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
844 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
850 AST->Ctx =
new ASTContext(*AST->LangOpts, AST->getSourceManager(),
853 AST->getTranslationUnitKind());
857 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
860 PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
862 disableValid, AllowASTWithCompilerErrors);
864 unsigned Counter = 0;
865 AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
866 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
867 AST->TargetOpts, AST->Target, Counter));
875 AST->Ctx->setExternalSource(AST->Reader);
888 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
892 AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
897 if (M && AST->getLangOpts().isCompilingModule() && M->
isNamedModule())
898 AST->Ctx->setCurrentNamedModule(M);
906 AST->TheSema.reset(
new Sema(PP, *AST->Ctx, *AST->Consumer));
907 AST->TheSema->Initialize();
908 AST->Reader->InitializeSema(*AST->TheSema);
912 AST->getDiagnostics().getClient()->BeginSourceFile(PP.
getLangOpts(), &PP);
926class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
930 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) {}
932 void MacroDefined(
const Token &MacroNameTok,
952 if (
const auto *ND = dyn_cast<NamedDecl>(
D)) {
953 if (
const auto *EnumD = dyn_cast<EnumDecl>(
D)) {
956 if (!EnumD->isScoped()) {
957 for (
const auto *EI : EnumD->enumerators()) {
958 if (EI->getIdentifier())
959 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
964 if (ND->getIdentifier())
965 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
967 std::string NameStr = Name.getAsString();
968 Hash = llvm::djbHash(NameStr, Hash);
973 if (
const auto *ImportD = dyn_cast<ImportDecl>(
D)) {
974 if (
const Module *Mod = ImportD->getImportedModule()) {
975 std::string ModName = Mod->getFullModuleName();
976 Hash = llvm::djbHash(ModName, Hash);
984class TopLevelDeclTrackerConsumer :
public ASTConsumer {
989 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
990 : Unit(_Unit), Hash(Hash) {
994 void handleTopLevelDecl(
Decl *
D) {
1002 if (isa<ObjCMethodDecl>(
D))
1008 handleFileLevelDecl(
D);
1011 void handleFileLevelDecl(
Decl *
D) {
1013 if (
auto *NSD = dyn_cast<NamespaceDecl>(
D)) {
1014 for (
auto *I : NSD->decls())
1015 handleFileLevelDecl(I);
1020 for (
auto *TopLevelDecl :
D)
1021 handleTopLevelDecl(TopLevelDecl);
1028 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
1029 for (
auto *TopLevelDecl :
D)
1030 handleTopLevelDecl(TopLevelDecl);
1047 StringRef InFile)
override {
1049 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1051 return std::make_unique<TopLevelDeclTrackerConsumer>(
1056 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
1058 bool hasCodeCompletionSupport()
const override {
return false; }
1067 unsigned getHash()
const {
return Hash; }
1069 std::vector<Decl *> takeTopLevelDecls() {
return std::move(TopLevelDecls); }
1071 std::vector<LocalDeclID> takeTopLevelDeclIDs() {
1072 return std::move(TopLevelDeclIDs);
1075 void AfterPCHEmitted(
ASTWriter &Writer)
override {
1076 TopLevelDeclIDs.reserve(TopLevelDecls.size());
1077 for (
const auto *
D : TopLevelDecls) {
1081 TopLevelDeclIDs.push_back(Writer.
getDeclID(
D));
1086 for (
auto *
D : DG) {
1091 if (isa<ObjCMethodDecl>(
D))
1094 TopLevelDecls.push_back(
D);
1098 std::unique_ptr<PPCallbacks> createPPCallbacks()
override {
1099 return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1104 std::vector<Decl *> TopLevelDecls;
1105 std::vector<LocalDeclID> TopLevelDeclIDs;
1130 for (
auto &SD : StoredDiagnostics) {
1131 if (SD.getLocation().isValid()) {
1133 SD.setLocation(
Loc);
1143bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1144 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1150 assert(VFS == &FileMgr->getVirtualFileSystem() &&
1151 "VFS passed to Parse and VFS in FileMgr are different");
1153 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1154 if (OverrideMainBuffer) {
1156 "No preamble was built, but OverrideMainBuffer is not null");
1157 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1162 std::unique_ptr<CompilerInstance> Clang(
1164 Clang->setInvocation(CCInvocation);
1167 auto CleanOnError = llvm::make_scope_exit([&]() {
1169 SavedMainFileBuffer =
nullptr;
1173 transferASTDataFromCompilerInstance(*Clang);
1174 FailedParseDiagnostics.swap(StoredDiagnostics);
1175 StoredDiagnostics.clear();
1176 NumStoredDiagnosticsFromDriver = 0;
1182 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() ==
VFS)
1183 Clang->setFileManager(&*FileMgr);
1185 FileMgr = Clang->createFileManager(std::move(VFS));
1188 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1189 CICleanup(Clang.get());
1191 OriginalSourceFile =
1192 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1199 if (!Clang->createTarget())
1202 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1203 "Invocation must have exactly one source file!");
1204 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1206 "FIXME: AST inputs not yet supported here!");
1207 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1209 "IR inputs not support here!");
1212 LangOpts = Clang->getInvocation().LangOpts;
1213 FileSystemOpts = Clang->getFileSystemOpts();
1218 UserFilesAreVolatile);
1219 if (!OverrideMainBuffer) {
1221 TopLevelDeclsInPreamble.clear();
1229 if (OverrideMainBuffer) {
1238 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1241 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1242 new TopLevelDeclTrackerAction(*
this));
1245 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1246 ActCleanup(Act.get());
1248 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1251 if (SavedMainFileBuffer)
1253 PreambleDiagnostics, StoredDiagnostics);
1255 PreambleSrcLocCache.clear();
1257 if (llvm::Error Err = Act->Execute()) {
1258 consumeError(std::move(Err));
1262 transferASTDataFromCompilerInstance(*Clang);
1264 Act->EndSourceFile();
1266 FailedParseDiagnostics.clear();
1268 CleanOnError.release();
1273static std::pair<unsigned, unsigned>
1277 unsigned Offset =
SM.getFileOffset(FileRange.
getBegin());
1278 unsigned EndOffset =
SM.getFileOffset(FileRange.
getEnd());
1279 return std::make_pair(Offset, EndOffset);
1306 OutDiag.
Filename = std::string(
SM.getFilename(FileLoc));
1312 for (
const auto &FixIt : InDiag.
getFixIts())
1338std::unique_ptr<llvm::MemoryBuffer>
1339ASTUnit::getMainBufferWithPrecompiledPreamble(
1340 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1343 unsigned MaxLines) {
1346 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1348 MainFilePath, UserFilesAreVolatile);
1349 if (!MainFileBuffer)
1353 PreambleInvocationIn.
getLangOpts(), *MainFileBuffer, MaxLines);
1358 if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
1369 PreambleRebuildCountdown = 1;
1370 return MainFileBuffer;
1373 PreambleDiagnostics.clear();
1374 TopLevelDeclsInPreamble.clear();
1375 PreambleSrcLocCache.clear();
1376 PreambleRebuildCountdown = 1;
1383 if (PreambleRebuildCountdown > 1) {
1384 --PreambleRebuildCountdown;
1388 assert(!Preamble &&
"No Preamble should be stored at that point");
1398 ASTUnitPreambleCallbacks Callbacks;
1400 std::optional<CaptureDroppedDiagnostics>
Capture;
1402 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1403 &NewPreambleDiagsStandalone);
1406 SimpleTimer PreambleTimer(WantTiming);
1407 PreambleTimer.setOutput(
"Precompiling preamble");
1409 const bool PreviousSkipFunctionBodies =
1415 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1416 PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath,
1420 PreviousSkipFunctionBodies;
1423 Preamble = std::move(*NewPreamble);
1424 PreambleRebuildCountdown = 1;
1429 PreambleRebuildCountdown = 1;
1439 llvm_unreachable(
"unexpected BuildPreambleError");
1443 assert(Preamble &&
"Preamble wasn't built");
1445 TopLevelDecls.clear();
1446 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1447 PreambleTopLevelHashValue = Callbacks.getHash();
1452 StoredDiagnostics = std::move(NewPreambleDiags);
1453 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1458 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1459 CompletionCacheTopLevelHashValue = 0;
1460 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1463 return MainFileBuffer;
1466void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1467 assert(Preamble &&
"Should only be called when preamble was built");
1469 std::vector<Decl *> Resolved;
1470 Resolved.reserve(TopLevelDeclsInPreamble.size());
1473 for (
const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1476 if (
Decl *
D = Reader->GetLocalDecl(MF, TopLevelDecl))
1477 Resolved.push_back(
D);
1479 TopLevelDeclsInPreamble.clear();
1480 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1503 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1508 return Input.
getBuffer().getBufferIdentifier();
1514 return FE->getName();
1525 Mod = Reader->getModuleManager().getPrimaryModule();
1529std::unique_ptr<ASTUnit>
1533 bool UserFilesAreVolatile) {
1534 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1535 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1538 AST->Diagnostics = Diags;
1539 AST->FileSystemOpts = CI->getFileSystemOpts();
1540 AST->Invocation = std::move(CI);
1541 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1542 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1543 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1544 UserFilesAreVolatile);
1551 std::shared_ptr<CompilerInvocation> CI,
1552 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1554 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1556 unsigned PrecompilePreambleAfterNParses,
bool CacheCodeCompletionResults,
1557 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1558 assert(CI &&
"A CompilerInvocation is required");
1560 std::unique_ptr<ASTUnit> OwnAST;
1564 OwnAST =
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1570 if (!ResourceFilesPath.empty()) {
1574 AST->OnlyLocalDecls = OnlyLocalDecls;
1575 AST->CaptureDiagnostics = CaptureDiagnostics;
1576 if (PrecompilePreambleAfterNParses > 0)
1577 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1579 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1580 AST->IncludeBriefCommentsInCodeCompletion =
false;
1583 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1584 ASTUnitCleanup(OwnAST.get());
1586 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1587 DiagCleanup(Diags.get());
1590 CI->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1591 CI->getFrontendOpts().DisableFree =
false;
1595 std::unique_ptr<CompilerInstance> Clang(
1599 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1600 CICleanup(Clang.get());
1602 Clang->setInvocation(std::move(CI));
1603 AST->OriginalSourceFile =
1604 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1611 if (!Clang->createTarget())
1614 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1615 "Invocation must have exactly one source file!");
1616 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1618 "FIXME: AST inputs not yet supported here!");
1619 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1621 "IR inputs not support here!");
1624 AST->TheSema.reset();
1627 AST->Reader =
nullptr;
1637 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1639 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1640 Act = TrackerAct.get();
1644 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1645 ActCleanup(TrackerAct.get());
1647 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1648 AST->transferASTDataFromCompilerInstance(*Clang);
1649 if (OwnAST && ErrAST)
1650 ErrAST->swap(OwnAST);
1655 if (Persistent && !TrackerAct) {
1656 Clang->getPreprocessor().addPPCallbacks(
1657 std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1659 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1660 if (Clang->hasASTConsumer())
1661 Consumers.push_back(Clang->takeASTConsumer());
1662 Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1664 Clang->setASTConsumer(
1665 std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1667 if (llvm::Error Err = Act->
Execute()) {
1668 consumeError(std::move(Err));
1669 AST->transferASTDataFromCompilerInstance(*Clang);
1670 if (OwnAST && ErrAST)
1671 ErrAST->swap(OwnAST);
1677 AST->transferASTDataFromCompilerInstance(*Clang);
1682 return OwnAST.release();
1687bool ASTUnit::LoadFromCompilerInvocation(
1688 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1689 unsigned PrecompilePreambleAfterNParses,
1694 assert(VFS &&
"VFS is null");
1697 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers =
true;
1698 Invocation->getFrontendOpts().DisableFree =
false;
1702 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1703 if (PrecompilePreambleAfterNParses > 0) {
1704 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1705 OverrideMainBuffer =
1706 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1711 SimpleTimer ParsingTimer(WantTiming);
1715 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1716 MemBufferCleanup(OverrideMainBuffer.get());
1718 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1721std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1722 std::shared_ptr<CompilerInvocation> CI,
1723 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1727 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1728 bool UserFilesAreVolatile) {
1730 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1731 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1732 AST->Diagnostics = Diags;
1733 AST->OnlyLocalDecls = OnlyLocalDecls;
1734 AST->CaptureDiagnostics = CaptureDiagnostics;
1735 AST->TUKind = TUKind;
1736 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1737 AST->IncludeBriefCommentsInCodeCompletion
1738 = IncludeBriefCommentsInCodeCompletion;
1739 AST->Invocation = std::move(CI);
1741 AST->FileMgr = FileMgr;
1742 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1745 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1746 ASTUnitCleanup(AST.get());
1748 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1749 DiagCleanup(Diags.get());
1751 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1752 PrecompilePreambleAfterNParses,
1753 &AST->FileMgr->getVirtualFileSystem()))
1759 const char **ArgBegin,
const char **ArgEnd,
1760 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1762 bool StorePreamblesInMemory, StringRef PreambleStoragePath,
1766 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1768 bool SingleFileParse,
bool UserFilesAreVolatile,
bool ForSerialization,
1769 bool RetainExcludedConditionalBlocks, std::optional<StringRef> ModuleFormat,
1770 std::unique_ptr<ASTUnit> *ErrAST,
1772 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1778 VFS = llvm::vfs::createPhysicalFileSystem();
1782 std::shared_ptr<CompilerInvocation> CI;
1785 CaptureDroppedDiagnostics
Capture(CaptureDiagnostics, *Diags,
1786 &StoredDiagnostics,
nullptr);
1790 CIOpts.
Diags = Diags;
1799 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1809 CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1811 CI->getFrontendOpts().SkipFunctionBodies =
1815 CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat);
1818 std::unique_ptr<ASTUnit> AST;
1819 AST.reset(
new ASTUnit(
false));
1820 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1821 AST->StoredDiagnostics.swap(StoredDiagnostics);
1822 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1823 AST->Diagnostics = Diags;
1824 AST->FileSystemOpts = CI->getFileSystemOpts();
1826 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1827 AST->StorePreamblesInMemory = StorePreamblesInMemory;
1828 AST->PreambleStoragePath = PreambleStoragePath;
1830 AST->OnlyLocalDecls = OnlyLocalDecls;
1831 AST->CaptureDiagnostics = CaptureDiagnostics;
1832 AST->TUKind = TUKind;
1833 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1834 AST->IncludeBriefCommentsInCodeCompletion
1835 = IncludeBriefCommentsInCodeCompletion;
1836 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1837 AST->Invocation = CI;
1838 AST->SkipFunctionBodies = SkipFunctionBodies;
1839 if (ForSerialization)
1840 AST->WriterData.reset(
new ASTWriterData(*AST->ModuleCache));
1846 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1847 ASTUnitCleanup(AST.get());
1849 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1850 PrecompilePreambleAfterNParses,
1855 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1871 assert(FileMgr &&
"FileMgr is null on Reparse call");
1872 VFS = &FileMgr->getVirtualFileSystem();
1875 clearFileLevelDecls();
1877 SimpleTimer ParsingTimer(WantTiming);
1885 Invocation->getPreprocessorOpts().clearRemappedFiles();
1887 Invocation->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1893 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1894 if (Preamble || PreambleRebuildCountdown > 0)
1895 OverrideMainBuffer =
1896 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1902 if (OverrideMainBuffer)
1907 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1911 if (!
Result && ShouldCacheCodeCompletionResults &&
1912 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1913 CacheCodeCompletionResults();
1923 SavedMainFileBuffer.reset();
1931 TopLevelDecls.clear();
1932 clearFileLevelDecls();
1945 uint64_t NormalContexts;
1978 unsigned NumResults)
override;
1980 void ProcessOverloadCandidates(
Sema &S,
unsigned CurrentArg,
1982 unsigned NumCandidates,
1984 bool Braced)
override {
1985 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1986 OpenParLoc, Braced);
1990 return Next.getAllocator();
1994 return Next.getCodeCompletionTUInfo();
2004 unsigned NumResults,
2006 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2007 bool OnlyTagNames =
false;
2008 switch (Context.getKind()) {
2033 OnlyTagNames =
true;
2059 for (
unsigned I = 0; I != NumResults; ++I) {
2060 if (Results[I].Kind != Result::RK_Declaration)
2064 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2066 bool Hiding =
false;
2075 Hiding = (IDNS & HiddenIDNS);
2085 HiddenNames.insert(Name.getAsString());
2089void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2092 unsigned NumResults) {
2094 bool AddedResult =
false;
2097 ? NormalContexts : (1LL << Context.getKind());
2099 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2108 if ((
C->ShowInContexts & InContexts) == 0)
2115 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2122 HiddenNames.count(
C->Completion->getTypedText()))
2128 if (!Context.getPreferredType().isNull()) {
2132 Context.getPreferredType()->isAnyPointerType());
2133 }
else if (
C->Type) {
2136 Context.getPreferredType().getUnqualifiedType());
2138 if (ExpectedSTC ==
C->TypeClass) {
2140 llvm::StringMap<unsigned> &CachedCompletionTypes
2142 llvm::StringMap<unsigned>::iterator Pos
2144 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2159 Builder.AddTypedTextChunk(
C->Completion->getTypedText());
2161 Completion = Builder.TakeString();
2164 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2171 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2175 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2182 bool IncludeCodePatterns,
bool IncludeBriefComments,
2184 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2188 std::unique_ptr<SyntaxOnlyAction> Act) {
2192 SimpleTimer CompletionTimer(WantTiming);
2193 CompletionTimer.setOutput(
"Code completion @ " +
File +
":" +
2196 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2203 CachedCompletionResults.empty();
2205 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2210 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2217 LangOpts = CCInvocation->getLangOpts();
2220 LangOpts.SpellChecking =
false;
2221 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2223 std::unique_ptr<CompilerInstance> Clang(
2227 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2228 CICleanup(Clang.get());
2230 auto &Inv = *CCInvocation;
2231 Clang->setInvocation(std::move(CCInvocation));
2232 OriginalSourceFile =
2233 std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2236 Clang->setDiagnostics(&
Diag);
2238 Clang->getDiagnostics(),
2239 &StoredDiagnostics,
nullptr);
2243 if (!Clang->createTarget()) {
2244 Clang->setInvocation(
nullptr);
2248 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2249 "Invocation must have exactly one source file!");
2250 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2252 "FIXME: AST inputs not yet supported here!");
2253 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2255 "IR inputs not support here!");
2258 Clang->setFileManager(&FileMgr);
2259 Clang->setSourceManager(&SourceMgr);
2271 AugmentedCodeCompleteConsumer *AugmentedConsumer
2272 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2273 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2276 [&FileMgr](StringRef
Filename) -> std::optional<llvm::sys::fs::UniqueID> {
2278 return Status->getUniqueID();
2279 return std::nullopt;
2282 auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
2285 if (
auto LHSID = getUniqueID(LHS))
2286 if (
auto RHSID = getUniqueID(RHS))
2287 return *LHSID == *RHSID;
2295 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2296 if (Preamble &&
Line > 1 && hasSameUniqueID(
File, OriginalSourceFile)) {
2297 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2303 if (OverrideMainBuffer) {
2305 "No preamble was built, but OverrideMainBuffer is not null");
2309 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2310 OverrideMainBuffer.get());
2315 OwnedBuffers.push_back(OverrideMainBuffer.release());
2322 if (!Clang->getLangOpts().Modules)
2328 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2329 if (llvm::Error Err = Act->Execute()) {
2330 consumeError(std::move(Err));
2332 Act->EndSourceFile();
2337 if (HadModuleLoaderFatalFailure)
2343 if (llvm::Error Err = llvm::writeToOutput(
2344 File, [
this](llvm::raw_ostream &Out) {
2345 return serialize(Out) ? llvm::make_error<llvm::StringError>(
2346 "ASTUnit serialization failed",
2347 llvm::inconvertibleErrorCode())
2348 : llvm::Error::success();
2350 consumeError(std::move(Err));
2357 Sema &S, raw_ostream &OS) {
2358 Writer.
WriteAST(S, std::string(),
nullptr,
"");
2361 if (!Buffer.empty())
2362 OS.write(Buffer.data(), Buffer.size());
2372 llvm::BitstreamWriter Stream(Buffer);
2374 ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2378void ASTUnit::TranslateStoredDiagnostics(
2388 Result.reserve(Diags.size());
2390 for (
const auto &SD : Diags) {
2392 if (SD.Filename.empty())
2394 auto FE = FileMgr.
getFile(SD.Filename);
2398 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2399 if (ItFileID == PreambleSrcLocCache.end()) {
2402 PreambleSrcLocCache[SD.Filename] = FileLoc;
2404 FileLoc = ItFileID->getValue();
2413 Ranges.reserve(SD.Ranges.size());
2414 for (
const auto &
Range : SD.Ranges) {
2421 FixIts.reserve(SD.FixIts.size());
2422 for (
const auto &FixIt : SD.FixIts) {
2432 SD.Message,
Loc, Ranges, FixIts));
2454 assert(
SM.isLocalSourceLocation(FileLoc));
2457 std::tie(FID, Offset) =
SM.getDecomposedLoc(FileLoc);
2461 std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2463 Decls = std::make_unique<LocDeclsTy>();
2465 std::pair<unsigned, Decl *> LocDecl(Offset,
D);
2467 if (Decls->empty() || Decls->back().first <= Offset) {
2468 Decls->push_back(LocDecl);
2472 LocDeclsTy::iterator I =
2473 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2475 Decls->insert(I, LocDecl);
2480 if (
File.isInvalid())
2484 assert(Ctx->getExternalSource() &&
"No external source!");
2485 return Ctx->getExternalSource()->FindFileRegionDecls(
File, Offset, Length,
2489 FileDeclsTy::iterator I = FileDecls.find(
File);
2490 if (I == FileDecls.end())
2494 if (LocDecls.empty())
2497 LocDeclsTy::iterator BeginIt =
2498 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2499 return LD.first < Offset;
2501 if (BeginIt != LocDecls.begin())
2507 while (BeginIt != LocDecls.begin() &&
2508 BeginIt->second->isTopLevelDeclInObjCContainer())
2511 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2512 LocDecls, std::make_pair(Offset + Length, (
Decl *)
nullptr),
2513 llvm::less_first());
2514 if (EndIt != LocDecls.end())
2517 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2518 Decls.push_back(DIt->second);
2522 unsigned Line,
unsigned Col)
const {
2525 return SM.getMacroArgExpandedLocation(
Loc);
2529 unsigned Offset)
const {
2547 if (SourceMgr->
isInFileID(
Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
2569 Offs < Preamble->getBounds().Size) {
2621llvm::iterator_range<PreprocessingRecord::iterator>
2625 Mod = Reader->getModuleManager().getPrimaryModule();
2626 return Reader->getModulePreprocessedEntities(Mod);
2630 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2639 Mod = Reader->getModuleManager().getPrimaryModule();
2640 for (
const auto *
D : Reader->getModuleFileLevelDecls(Mod)) {
2641 if (!Fn(context,
D))
2650 TL != TLEnd; ++TL) {
2651 if (!Fn(context, *TL))
2660 return std::nullopt;
2665 case serialization::MK_ImplicitModule:
2666 case serialization::MK_ExplicitModule:
2667 case serialization::MK_PrebuiltModule:
2669 case serialization::MK_PCH:
2672 case serialization::MK_Preamble:
2674 case serialization::MK_MainFile:
2683 return std::nullopt;
2694 if (LangOpts.OpenCL)
2696 else if (LangOpts.CUDA)
2698 else if (LangOpts.RenderScript)
2700 else if (LangOpts.CPlusPlus)
2716ASTUnit::ConcurrencyState::ConcurrencyState() {
2717 Mutex =
new std::recursive_mutex;
2720ASTUnit::ConcurrencyState::~ConcurrencyState() {
2721 delete static_cast<std::recursive_mutex *
>(Mutex);
2724void ASTUnit::ConcurrencyState::start() {
2725 bool acquired =
static_cast<std::recursive_mutex *
>(Mutex)->try_lock();
2726 assert(acquired &&
"Concurrent access to ASTUnit!");
2729void ASTUnit::ConcurrencyState::finish() {
2730 static_cast<std::recursive_mutex *
>(Mutex)->unlock();
2735ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex =
nullptr; }
2736ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2737void ASTUnit::ConcurrencyState::start() {}
2738void 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.
Reads an AST files chain containing the contents of a translation unit.
@ 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
static std::unique_ptr< ASTUnit > LoadFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool StorePreamblesInMemory=false, StringRef PreambleStoragePath=StringRef(), bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, ArrayRef< RemappedFile > RemappedFiles=std::nullopt, 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 CodeComplete(StringRef File, unsigned Line, unsigned Column, ArrayRef< RemappedFile > RemappedFiles, bool IncludeMacros, bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr< PCHContainerOperations > PCHContainerOps, DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, 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=std::nullopt, 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.
InputKind getInputKind() const
Determine the input kind this AST unit represents.
OptionalFileEntryRef getPCHFile()
Get the PCH file if one was included.
StringRef getMainFileName() const
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
@ 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
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.
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.
static std::unique_ptr< ASTUnit > create(std::shared_ptr< CompilerInvocation > CI, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, CaptureDiagsKind CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
const HeaderSearchOptions & getHeaderSearchOpts() const
void addTopLevelDecl(Decl *D)
Add a new top-level declaration.
static ASTUnit * LoadFromCompilerInvocationAction(std::shared_ptr< CompilerInvocation > CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, 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...
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.
static std::unique_ptr< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, std::shared_ptr< HeaderSearchOptions > HSOpts, std::shared_ptr< 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.
Writes an AST file containing the contents of a translation unit.
ASTFileSignature WriteAST(Sema &SemaRef, StringRef OutputFile, Module *WritingModule, StringRef isysroot, bool ShouldCacheASTInMemory=false)
Write a precompiled header for the given semantic analysis.
LocalDeclID getDeclID(const Decl *D)
Determine the local declaration ID of an already-emitted declaration.
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.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
std::shared_ptr< Preprocessor > getPreprocessorPtr()
std::unique_ptr< Sema > takeSema()
IntrusiveRefCntPtr< ASTReader > getASTReader() const
bool hasASTContext() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
bool hasInvocation() const
bool hadModuleLoaderFatalFailure() const
CompilerInvocation & getInvocation()
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
TargetInfo & getTarget() const
bool hasPreprocessor() const
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
std::shared_ptr< LangOptions > LangOpts
Base class internals.
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) ...
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
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
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.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
llvm::Error Execute()
Set the source manager's main input file, and run the action.
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
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.
In-memory cache for modules.
@ 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,...
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, 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, const std::shared_ptr< 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)
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
SkipFunctionBodiesScope
Enumerates the available scopes for skipping function bodies.
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)
@ 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....
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.
@ CCP_NestedNameSpecifier
Priority for a nested-name-specifier.
@ CCP_CodePattern
Priority for a code pattern.
const FunctionProtoType * T
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)
llvm::BitstreamWriter Stream
SmallString< 128 > Buffer
ASTWriterData(InMemoryModuleCache &ModuleCache)
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.