36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringSet.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
50 using namespace clang;
52 using llvm::TimeRecord;
61 explicit SimpleTimer(
bool WantTiming) : WantTiming(WantTiming) {
63 Start = TimeRecord::getCurrentTime();
66 void setOutput(
const Twine &Output) {
68 this->Output = Output.str();
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 llvm::errs() << Output <<
':';
76 Elapsed.print(Elapsed, llvm::errs());
84 std::string PreambleFile;
91 void CleanTemporaryFiles();
94 void CleanPreambleFile();
102 static llvm::sys::SmartMutex<false> M(
true);
108 typedef llvm::DenseMap<
const ASTUnit *,
112 static bool hasRegisteredAtExit =
false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit =
true;
137 D = llvm::make_unique<OnDiskData>();
150 OnDiskDataMap::iterator I = M.find(AU);
152 I->second->Cleanup();
165 void OnDiskData::CleanTemporaryFiles() {
166 for (StringRef File : TemporaryFiles)
167 llvm::sys::fs::remove(File);
168 TemporaryFiles.clear();
171 void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
173 llvm::sys::fs::remove(PreambleFile);
174 PreambleFile.clear();
178 void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
191 void ASTUnit::clearFileLevelDecls() {
192 llvm::DeleteContainerSeconds(FileDecls);
195 void ASTUnit::CleanTemporaryFiles() {
214 ASTUnit::ASTUnit(
bool _MainFileIsAST)
215 : Reader(nullptr), HadModuleLoaderFatalFailure(
false),
216 OnlyLocalDecls(
false), CaptureDiagnostics(
false),
217 MainFileIsAST(_MainFileIsAST),
218 TUKind(
TU_Complete), WantTiming(getenv(
"LIBCLANG_TIMING")),
219 OwnsRemappedFileBuffers(
true),
220 NumStoredDiagnosticsFromDriver(0),
221 PreambleRebuildCounter(0),
222 NumWarningsInPreamble(0),
223 ShouldCacheCodeCompletionResults(
false),
224 IncludeBriefCommentsInCodeCompletion(
false), UserFilesAreVolatile(
false),
225 CompletionCacheTopLevelHashValue(0),
226 PreambleTopLevelHashValue(0),
227 CurrentTopLevelHashValue(0),
228 UnsafeToFree(
false) {
229 if (getenv(
"LIBCLANG_OBJTRACKING"))
233 ASTUnit::~ASTUnit() {
239 clearFileLevelDecls();
248 if (Invocation.get() && OwnsRemappedFileBuffers) {
254 ClearCachedCompletionResults();
256 if (getenv(
"LIBCLANG_OBJTRACKING"))
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier =
false;
269 if (isa<UsingShadowDecl>(ND))
275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
287 if (LangOpts.CPlusPlus)
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
296 if (isa<ObjCInterfaceDecl>(ND))
300 if (isa<EnumDecl>(ND)) {
304 if (LangOpts.CPlusPlus11)
305 IsNestedNameSpecifier =
true;
306 }
else if (
const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
307 if (Record->isUnion())
312 if (LangOpts.CPlusPlus)
313 IsNestedNameSpecifier =
true;
314 }
else if (isa<ClassTemplateDecl>(ND))
315 IsNestedNameSpecifier =
true;
316 }
else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
322 }
else if (isa<ObjCProtocolDecl>(ND)) {
324 }
else if (isa<ObjCCategoryDecl>(ND)) {
326 }
else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
330 IsNestedNameSpecifier =
true;
336 void ASTUnit::CacheCodeCompletionResults() {
340 SimpleTimer Timer(WantTiming);
341 Timer.setOutput(
"Cache global code completions for " +
getMainFileName());
344 ClearCachedCompletionResults();
351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
358 for (Result &R : Results) {
360 case Result::RK_Declaration: {
361 bool IsNestedNameSpecifier =
false;
362 CachedCodeCompletionResult CachedResult;
363 CachedResult.Completion = R.CreateCodeCompletionString(
364 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
365 IncludeBriefCommentsInCodeCompletion);
367 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
368 CachedResult.Priority = R.Priority;
369 CachedResult.Kind = R.CursorKind;
370 CachedResult.Availability = R.Availability;
377 CachedResult.Type = 0;
386 unsigned &TypeValue = CompletionTypes[CanUsageType];
387 if (TypeValue == 0) {
388 TypeValue = CompletionTypes.size();
393 CachedResult.Type = TypeValue;
396 CachedCompletionResults.push_back(CachedResult);
399 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
400 !R.StartsNestedNameSpecifier) {
416 if (isa<NamespaceDecl>(R.Declaration) ||
417 isa<NamespaceAliasDecl>(R.Declaration))
420 if (
unsigned RemainingContexts
421 = NNSContexts & ~CachedResult.ShowInContexts) {
425 R.StartsNestedNameSpecifier =
true;
426 CachedResult.Completion = R.CreateCodeCompletionString(
427 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
428 IncludeBriefCommentsInCodeCompletion);
429 CachedResult.ShowInContexts = RemainingContexts;
432 CachedResult.Type = 0;
433 CachedCompletionResults.push_back(CachedResult);
439 case Result::RK_Keyword:
440 case Result::RK_Pattern:
445 case Result::RK_Macro: {
446 CachedCodeCompletionResult CachedResult;
447 CachedResult.Completion = R.CreateCodeCompletionString(
448 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
449 IncludeBriefCommentsInCodeCompletion);
450 CachedResult.ShowInContexts
464 CachedResult.Priority = R.Priority;
465 CachedResult.Kind = R.CursorKind;
466 CachedResult.Availability = R.Availability;
468 CachedResult.Type = 0;
469 CachedCompletionResults.push_back(CachedResult);
476 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
479 void ASTUnit::ClearCachedCompletionResults() {
480 CachedCompletionResults.clear();
481 CachedCompletionTypes.clear();
482 CachedCompletionAllocator =
nullptr;
493 std::shared_ptr<TargetOptions> &TargetOpts;
497 bool InitializedLanguage;
500 std::shared_ptr<TargetOptions> &TargetOpts,
502 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
503 Target(Target), Counter(Counter), InitializedLanguage(
false) {}
505 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
506 bool AllowCompatibleDifferences)
override {
507 if (InitializedLanguage)
511 InitializedLanguage =
true;
517 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
518 bool AllowCompatibleDifferences)
override {
523 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
532 unsigned Value)
override {
538 if (!Target || !InitializedLanguage)
545 Target->adjust(LangOpt);
548 PP.Initialize(*Target);
556 LangOpt.CommentOpts);
566 explicit StoredDiagnosticConsumer(
568 : StoredDiags(StoredDiags),
SourceMgr(nullptr) {}
582 class CaptureDroppedDiagnostics {
584 StoredDiagnosticConsumer Client;
586 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
591 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
593 if (RequestCapture || Diags.
getClient() ==
nullptr) {
600 ~CaptureDroppedDiagnostics() {
602 Diags.
setClient(PreviousClient, !!OwningPreviousClient.release());
617 StoredDiags.emplace_back(Level, Info);
622 return &WriterData->Writer;
628 return &WriterData->Writer;
632 std::unique_ptr<llvm::MemoryBuffer>
635 auto Buffer = FileMgr->getBufferForFile(Filename);
637 return std::move(*Buffer);
639 *ErrorStr = Buffer.getError().message();
645 ASTUnit &AST,
bool CaptureDiagnostics) {
646 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
647 if (CaptureDiagnostics)
648 Diags->setClient(
new StoredDiagnosticConsumer(AST.StoredDiagnostics));
652 const std::string &Filename,
657 bool AllowPCHWithCompilerErrors,
bool UserFilesAreVolatile) {
658 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
true));
661 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
662 ASTUnitCleanup(AST.get());
664 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
665 DiagCleanup(Diags.get());
667 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
669 AST->OnlyLocalDecls = OnlyLocalDecls;
670 AST->CaptureDiagnostics = CaptureDiagnostics;
671 AST->Diagnostics = Diags;
673 AST->FileMgr =
new FileManager(FileSystemOpts, VFS);
674 AST->UserFilesAreVolatile = UserFilesAreVolatile;
676 AST->getFileManager(),
677 UserFilesAreVolatile);
679 AST->HSOpts->ModuleFormat = PCHContainerRdr.
getFormat();
681 AST->getSourceManager(),
682 AST->getDiagnostics(),
683 AST->ASTFileLangOpts,
697 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
698 AST->getSourceManager(), HeaderInfo, *AST,
703 AST->Ctx =
new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
704 PP.getIdentifierTable(), PP.getSelectorTable(),
705 PP.getBuiltinInfo());
708 bool disableValid =
false;
709 if (::getenv(
"LIBCLANG_DISABLE_PCH_VALIDATION"))
711 AST->Reader =
new ASTReader(PP, Context, PCHContainerRdr,
714 AllowPCHWithCompilerErrors);
716 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
717 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
725 Context.setExternalSource(AST->Reader);
738 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
742 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
744 PP.setCounterValue(Counter);
750 AST->TheSema.reset(
new Sema(PP, Context, *AST->Consumer));
751 AST->TheSema->Initialize();
752 AST->Reader->InitializeSema(*AST->TheSema);
755 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
764 class MacroDefinitionTrackerPPCallbacks :
public PPCallbacks {
768 explicit MacroDefinitionTrackerPPCallbacks(
unsigned &Hash) : Hash(Hash) { }
770 void MacroDefined(
const Token &MacroNameTok,
777 void AddTopLevelDeclarationToHash(
Decl *D,
unsigned &Hash) {
788 if (
NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
789 if (
EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
792 if (!EnumD->isScoped()) {
793 for (
const auto *EI : EnumD->enumerators()) {
794 if (EI->getIdentifier())
795 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
800 if (ND->getIdentifier())
801 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
803 std::string NameStr = Name.getAsString();
804 Hash = llvm::HashString(NameStr, Hash);
809 if (
ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
810 if (
Module *Mod = ImportD->getImportedModule()) {
811 std::string ModName = Mod->getFullModuleName();
812 Hash = llvm::HashString(ModName, Hash);
818 class TopLevelDeclTrackerConsumer :
public ASTConsumer {
823 TopLevelDeclTrackerConsumer(
ASTUnit &_Unit,
unsigned &Hash)
824 : Unit(_Unit), Hash(Hash) {
828 void handleTopLevelDecl(
Decl *D) {
836 if (isa<ObjCMethodDecl>(D))
839 AddTopLevelDeclarationToHash(D, Hash);
840 Unit.addTopLevelDecl(D);
842 handleFileLevelDecl(D);
845 void handleFileLevelDecl(
Decl *D) {
846 Unit.addFileLevelDecl(D);
848 for (
auto *I : NSD->decls())
849 handleFileLevelDecl(I);
854 for (
Decl *TopLevelDecl : D)
855 handleTopLevelDecl(TopLevelDecl);
862 void HandleTopLevelDeclInObjCContainer(
DeclGroupRef D)
override {
863 for (
Decl *TopLevelDecl : D)
864 handleTopLevelDecl(TopLevelDecl);
868 return Unit.getASTMutationListener();
872 return Unit.getDeserializationListener();
881 StringRef InFile)
override {
883 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
884 Unit.getCurrentTopLevelHashValue()));
885 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
886 Unit, Unit.getCurrentTopLevelHashValue());
890 TopLevelDeclTrackerAction(
ASTUnit &_Unit) : Unit(_Unit) {}
892 bool hasCodeCompletionSupport()
const override {
return false; }
894 return Unit.getTranslationUnitKind();
900 bool HasEmittedPreamblePCH;
903 explicit PrecompilePreambleAction(
ASTUnit &Unit)
904 : Unit(Unit), HasEmittedPreamblePCH(
false) {}
907 StringRef InFile)
override;
908 bool hasEmittedPreamblePCH()
const {
return HasEmittedPreamblePCH; }
909 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH =
true; }
910 bool shouldEraseOutputFiles()
override {
return !hasEmittedPreamblePCH(); }
912 bool hasCodeCompletionSupport()
const override {
return false; }
913 bool hasASTFileSupport()
const override {
return false; }
917 class PrecompilePreambleConsumer :
public PCHGenerator {
920 std::vector<Decl *> TopLevelDecls;
921 PrecompilePreambleAction *
Action;
925 PrecompilePreambleConsumer(
ASTUnit &Unit, PrecompilePreambleAction *
Action,
930 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
941 if (isa<ObjCMethodDecl>(D))
943 AddTopLevelDeclarationToHash(D, Hash);
944 TopLevelDecls.push_back(D);
949 void HandleTranslationUnit(
ASTContext &Ctx)
override {
951 if (hasEmittedPCH()) {
958 getPCH() = std::move(Empty);
964 for (
Decl *D : TopLevelDecls) {
966 if (D->isInvalidDecl())
968 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
971 Action->setHasEmittedPreamblePCH();
978 std::unique_ptr<ASTConsumer>
982 std::string OutputFile;
984 CI, InFile, Sysroot, OutputFile);
992 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
993 Unit.getCurrentTopLevelHashValue()));
994 return llvm::make_unique<PrecompilePreambleConsumer>(
1007 std::remove_if(StoredDiags.begin(), StoredDiags.end(),
isNonDriverDiag),
1020 if (SD.getLocation().isValid()) {
1022 SD.setLocation(Loc);
1032 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1033 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1034 SavedMainFileBuffer.reset();
1040 std::unique_ptr<CompilerInstance> Clang(
1044 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1045 CICleanup(Clang.get());
1050 Clang->setInvocation(CCInvocation.get());
1051 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1059 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1060 if (!Clang->hasTarget())
1067 Clang->getTarget().adjust(Clang->getLangOpts());
1069 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1070 "Invocation must have exactly one source file!");
1071 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1072 "FIXME: AST inputs not yet supported here!");
1073 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1074 "IR inputs not support here!");
1077 LangOpts = Clang->getInvocation().LangOpts;
1078 FileSystemOpts = Clang->getFileSystemOpts();
1085 UserFilesAreVolatile);
1092 TopLevelDecls.clear();
1093 clearFileLevelDecls();
1094 CleanTemporaryFiles();
1096 if (!OverrideMainBuffer) {
1098 TopLevelDeclsInPreamble.clear();
1110 if (OverrideMainBuffer) {
1112 OverrideMainBuffer.get());
1115 = PreambleEndsAtStartOfLine;
1127 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1130 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1131 new TopLevelDeclTrackerAction(*
this));
1134 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1135 ActCleanup(Act.get());
1137 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1140 if (SavedMainFileBuffer) {
1143 PreambleDiagnostics, StoredDiagnostics);
1146 if (!Act->Execute())
1149 transferASTDataFromCompilerInstance(*Clang);
1151 Act->EndSourceFile();
1153 FailedParseDiagnostics.clear();
1159 SavedMainFileBuffer =
nullptr;
1163 transferASTDataFromCompilerInstance(*Clang);
1164 FailedParseDiagnostics.swap(StoredDiagnostics);
1165 StoredDiagnostics.clear();
1166 NumStoredDiagnosticsFromDriver = 0;
1175 const char *TmpFile = ::getenv(
"CINDEXTEST_PREAMBLE_FILE");
1180 llvm::sys::fs::createTemporaryFile(
"preamble",
"pch", Path);
1188 ASTUnit::ComputedPreamble
1196 llvm::MemoryBuffer *Buffer =
nullptr;
1197 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1198 std::string MainFilePath(FrontendOpts.
Inputs[0].getFile());
1199 llvm::sys::fs::UniqueID MainFileID;
1200 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1203 std::string MPath(RF.first);
1204 llvm::sys::fs::UniqueID MID;
1205 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1206 if (MainFileID == MID) {
1210 return ComputedPreamble(
nullptr,
nullptr, 0,
true);
1218 std::string MPath(RB.first);
1219 llvm::sys::fs::UniqueID MID;
1220 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1221 if (MainFileID == MID) {
1223 BufferOwner.reset();
1224 Buffer =
const_cast<llvm::MemoryBuffer *
>(RB.second);
1231 if (!Buffer && !BufferOwner) {
1234 return ComputedPreamble(
nullptr,
nullptr, 0,
true);
1238 Buffer = BufferOwner.get();
1241 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1250 memset(Result.
MD5, 0,
sizeof(Result.
MD5));
1255 const llvm::MemoryBuffer *Buffer) {
1257 Result.
Size = Buffer->getBufferSize();
1261 MD5Ctx.update(Buffer->getBuffer().data());
1262 MD5Ctx.final(Result.
MD5);
1271 memcmp(LHS.
MD5, RHS.
MD5,
sizeof(LHS.
MD5)) == 0;
1275 static std::pair<unsigned, unsigned>
1281 return std::make_pair(Offset, EndOffset);
1340 std::unique_ptr<llvm::MemoryBuffer>
1341 ASTUnit::getMainBufferWithPrecompiledPreamble(
1342 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1344 unsigned MaxLines) {
1348 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1350 = PreambleInvocation->getPreprocessorOpts();
1352 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1354 if (!NewPreamble.Size) {
1361 PreambleRebuildCounter = 1;
1365 if (!Preamble.
empty()) {
1370 if (Preamble.
size() == NewPreamble.Size &&
1371 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1372 memcmp(Preamble.
getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1373 NewPreamble.Size) == 0) {
1378 bool AnyFileChanged =
false;
1382 llvm::StringMap<PreambleFileHash> OverriddenFiles;
1388 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1391 AnyFileChanged =
true;
1402 OverriddenFiles[RB.first] =
1407 for (llvm::StringMap<PreambleFileHash>::iterator
1408 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1409 !AnyFileChanged && F != FEnd;
1411 llvm::StringMap<PreambleFileHash>::iterator Overridden
1412 = OverriddenFiles.find(F->first());
1413 if (Overridden != OverriddenFiles.end()) {
1416 if (Overridden->second != F->second)
1417 AnyFileChanged =
true;
1423 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1425 AnyFileChanged =
true;
1426 }
else if (Status.
getSize() != uint64_t(F->second.Size) ||
1428 uint64_t(F->second.ModTime))
1429 AnyFileChanged =
true;
1432 if (!AnyFileChanged) {
1439 PreambleInvocation->getDiagnosticOpts());
1442 return llvm::MemoryBuffer::getMemBufferCopy(
1443 NewPreamble.Buffer->getBuffer(), FrontendOpts.
Inputs[0].getFile());
1454 PreambleDiagnostics.clear();
1456 PreambleRebuildCounter = 1;
1457 }
else if (!AllowRebuild) {
1466 if (PreambleRebuildCounter > 1) {
1467 --PreambleRebuildCounter;
1474 if (PreamblePCHPath.empty()) {
1476 PreambleRebuildCounter = 1;
1481 SimpleTimer PreambleTimer(WantTiming);
1482 PreambleTimer.setOutput(
"Precompiling preamble");
1486 StringRef MainFilename = FrontendOpts.
Inputs[0].getFile();
1487 Preamble.
assign(FileMgr->getFile(MainFilename),
1488 NewPreamble.Buffer->getBufferStart(),
1489 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1490 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1492 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1493 NewPreamble.Buffer->getBuffer().slice(0, Preamble.
size()), MainFilename);
1496 StringRef MainFilePath = FrontendOpts.
Inputs[0].getFile();
1507 std::unique_ptr<CompilerInstance> Clang(
1511 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1512 CICleanup(Clang.get());
1514 Clang->setInvocation(&*PreambleInvocation);
1515 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1522 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1523 if (!Clang->hasTarget()) {
1524 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1535 Clang->getTarget().adjust(Clang->getLangOpts());
1537 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1538 "Invocation must have exactly one source file!");
1539 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1540 "FIXME: AST inputs not yet supported here!");
1541 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1542 "IR inputs not support here!");
1548 TopLevelDecls.clear();
1549 TopLevelDeclsInPreamble.clear();
1550 PreambleDiagnostics.clear();
1558 Clang->setFileManager(
new FileManager(Clang->getFileSystemOpts(), VFS));
1562 Clang->getFileManager()));
1564 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1565 Clang->addDependencyCollector(PreambleDepCollector);
1567 std::unique_ptr<PrecompilePreambleAction> Act;
1568 Act.reset(
new PrecompilePreambleAction(*
this));
1569 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1570 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1584 PreambleDiagnostics.push_back(
1587 Act->EndSourceFile();
1591 if (!Act->hasEmittedPreamblePCH()) {
1595 llvm::sys::fs::remove(FrontendOpts.
OutputFile);
1597 TopLevelDeclsInPreamble.clear();
1609 FilesInPreamble.clear();
1611 for (
auto &Filename : PreambleDepCollector->getDependencies()) {
1612 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1620 FilesInPreamble[File->
getName()] =
1625 PreambleRebuildCounter = 1;
1631 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1632 CompletionCacheTopLevelHashValue = 0;
1633 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1636 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1640 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1641 std::vector<Decl *> Resolved;
1642 Resolved.reserve(TopLevelDeclsInPreamble.size());
1648 Resolved.push_back(D);
1650 TopLevelDeclsInPreamble.clear();
1651 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1679 return Input.
getBuffer()->getBufferIdentifier();
1685 return FE->getName();
1696 Mod = Reader->getModuleManager().getPrimaryModule();
1702 bool CaptureDiagnostics,
1703 bool UserFilesAreVolatile) {
1704 std::unique_ptr<ASTUnit> AST;
1705 AST.reset(
new ASTUnit(
false));
1706 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1707 AST->Diagnostics = Diags;
1708 AST->Invocation = CI;
1714 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1715 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1716 AST->SourceMgr =
new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1717 UserFilesAreVolatile);
1719 return AST.release();
1724 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1726 ASTUnit *Unit,
bool Persistent, StringRef ResourceFilesPath,
1727 bool OnlyLocalDecls,
bool CaptureDiagnostics,
bool PrecompilePreamble,
1728 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1729 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1730 assert(CI &&
"A CompilerInvocation is required");
1732 std::unique_ptr<ASTUnit> OwnAST;
1736 OwnAST.reset(
create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1742 if (!ResourceFilesPath.empty()) {
1746 AST->OnlyLocalDecls = OnlyLocalDecls;
1747 AST->CaptureDiagnostics = CaptureDiagnostics;
1748 if (PrecompilePreamble)
1749 AST->PreambleRebuildCounter = 2;
1751 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1752 AST->IncludeBriefCommentsInCodeCompletion
1753 = IncludeBriefCommentsInCodeCompletion;
1756 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1757 ASTUnitCleanup(OwnAST.get());
1759 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1760 DiagCleanup(Diags.get());
1768 std::unique_ptr<CompilerInstance> Clang(
1772 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1773 CICleanup(Clang.get());
1775 Clang->setInvocation(CI);
1776 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1784 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1785 if (!Clang->hasTarget())
1792 Clang->getTarget().adjust(Clang->getLangOpts());
1794 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1795 "Invocation must have exactly one source file!");
1796 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
1797 "FIXME: AST inputs not yet supported here!");
1798 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
1799 "IR inputs not supported here!");
1802 AST->TheSema.reset();
1805 AST->Reader =
nullptr;
1815 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1817 TrackerAct.reset(
new TopLevelDeclTrackerAction(*AST));
1818 Act = TrackerAct.get();
1822 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1823 ActCleanup(TrackerAct.get());
1825 if (!Act->
BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1826 AST->transferASTDataFromCompilerInstance(*Clang);
1827 if (OwnAST && ErrAST)
1828 ErrAST->swap(OwnAST);
1833 if (Persistent && !TrackerAct) {
1834 Clang->getPreprocessor().addPPCallbacks(
1835 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1837 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1838 if (Clang->hasASTConsumer())
1839 Consumers.push_back(Clang->takeASTConsumer());
1840 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1842 Clang->setASTConsumer(
1843 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1846 AST->transferASTDataFromCompilerInstance(*Clang);
1847 if (OwnAST && ErrAST)
1848 ErrAST->swap(OwnAST);
1854 AST->transferASTDataFromCompilerInstance(*Clang);
1859 return OwnAST.release();
1864 bool ASTUnit::LoadFromCompilerInvocation(
1865 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1866 bool PrecompilePreamble) {
1875 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1876 if (PrecompilePreamble) {
1877 PreambleRebuildCounter = 2;
1878 OverrideMainBuffer =
1879 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1882 SimpleTimer ParsingTimer(WantTiming);
1886 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1887 MemBufferCleanup(OverrideMainBuffer.get());
1889 return Parse(PCHContainerOps, std::move(OverrideMainBuffer));
1892 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1894 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1896 bool CaptureDiagnostics,
bool PrecompilePreamble,
1898 bool IncludeBriefCommentsInCodeCompletion,
bool UserFilesAreVolatile) {
1900 std::unique_ptr<ASTUnit> AST(
new ASTUnit(
false));
1901 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1902 AST->Diagnostics = Diags;
1903 AST->OnlyLocalDecls = OnlyLocalDecls;
1904 AST->CaptureDiagnostics = CaptureDiagnostics;
1905 AST->TUKind = TUKind;
1906 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1907 AST->IncludeBriefCommentsInCodeCompletion
1908 = IncludeBriefCommentsInCodeCompletion;
1909 AST->Invocation = CI;
1915 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1916 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1919 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1920 ASTUnitCleanup(AST.get());
1922 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1923 DiagCleanup(Diags.get());
1925 if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble))
1931 const char **ArgBegin,
const char **ArgEnd,
1932 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1934 bool OnlyLocalDecls,
bool CaptureDiagnostics,
1937 bool CacheCodeCompletionResults,
bool IncludeBriefCommentsInCodeCompletion,
1938 bool AllowPCHWithCompilerErrors,
bool SkipFunctionBodies,
1939 bool UserFilesAreVolatile,
bool ForSerialization,
1940 std::unique_ptr<ASTUnit> *ErrAST) {
1941 assert(Diags.get() &&
"no DiagnosticsEngine was provided");
1949 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1953 llvm::makeArrayRef(ArgBegin, ArgEnd),
1961 CI->getPreprocessorOpts().addRemappedFile(
RemappedFile.first,
1969 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1971 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1974 std::unique_ptr<ASTUnit> AST;
1975 AST.reset(
new ASTUnit(
false));
1976 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1977 AST->Diagnostics = Diags;
1978 AST->FileSystemOpts = CI->getFileSystemOpts();
1983 AST->FileMgr =
new FileManager(AST->FileSystemOpts, VFS);
1984 AST->OnlyLocalDecls = OnlyLocalDecls;
1985 AST->CaptureDiagnostics = CaptureDiagnostics;
1986 AST->TUKind = TUKind;
1987 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1988 AST->IncludeBriefCommentsInCodeCompletion
1989 = IncludeBriefCommentsInCodeCompletion;
1990 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1991 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1992 AST->StoredDiagnostics.swap(StoredDiagnostics);
1993 AST->Invocation = CI;
1994 if (ForSerialization)
2001 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2002 ASTUnitCleanup(AST.get());
2004 if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble)) {
2008 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2014 return AST.release();
2022 clearFileLevelDecls();
2024 SimpleTimer ParsingTimer(WantTiming);
2040 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2042 OverrideMainBuffer =
2043 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2048 if (OverrideMainBuffer)
2052 bool Result = Parse(PCHContainerOps, std::move(OverrideMainBuffer));
2056 if (!Result && ShouldCacheCodeCompletionResults &&
2057 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2058 CacheCodeCompletionResults();
2076 uint64_t NormalContexts;
2084 AST(AST), Next(Next)
2111 unsigned NumResults)
override;
2113 void ProcessOverloadCandidates(
Sema &
S,
unsigned CurrentArg,
2115 unsigned NumCandidates)
override {
2133 unsigned NumResults,
2135 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2136 bool OnlyTagNames =
false;
2161 OnlyTagNames =
true;
2183 for (
unsigned I = 0; I != NumResults; ++I) {
2184 if (Results[I].
Kind != Result::RK_Declaration)
2190 bool Hiding =
false;
2199 Hiding = (IDNS & HiddenIDNS);
2207 HiddenNames.insert(Identifier->getName());
2214 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(
Sema &S,
2217 unsigned NumResults) {
2219 bool AddedResult =
false;
2220 uint64_t InContexts =
2222 ? NormalContexts : (1LL << Context.
getKind());
2224 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2233 if ((
C->ShowInContexts & InContexts) == 0)
2240 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2247 HiddenNames.count(
C->Completion->getTypedText()))
2251 unsigned Priority =
C->Priority;
2258 }
else if (
C->Type) {
2263 if (ExpectedSTC ==
C->TypeClass) {
2265 llvm::StringMap<unsigned> &CachedCompletionTypes
2267 llvm::StringMap<unsigned>::iterator Pos
2268 = CachedCompletionTypes.find(
QualType(Expected).getAsString());
2269 if (Pos != CachedCompletionTypes.end() && Pos->second ==
C->Type)
2284 Builder.AddTypedTextChunk(
C->Completion->getTypedText());
2286 Completion =
Builder.TakeString();
2289 AllResults.push_back(
Result(Completion, Priority,
C->Kind,
2305 StringRef File,
unsigned Line,
unsigned Column,
2307 bool IncludeCodePatterns,
bool IncludeBriefComments,
2309 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2316 SimpleTimer CompletionTimer(WantTiming);
2317 CompletionTimer.setOutput(
"Code completion @ " + File +
":" +
2318 Twine(Line) +
":" + Twine(Column));
2328 CachedCompletionResults.empty();
2330 CodeCompleteOpts.
IncludeGlobals = CachedCompletionResults.empty();
2333 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2340 LangOpts = *CCInvocation->getLangOpts();
2343 LangOpts.SpellChecking =
false;
2344 CCInvocation->getDiagnosticOpts().IgnoreWarnings =
true;
2346 std::unique_ptr<CompilerInstance> Clang(
2350 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2351 CICleanup(Clang.get());
2353 Clang->setInvocation(&*CCInvocation);
2354 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2357 Clang->setDiagnostics(&Diag);
2358 CaptureDroppedDiagnostics Capture(
true,
2359 Clang->getDiagnostics(),
2365 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2366 if (!Clang->hasTarget()) {
2367 Clang->setInvocation(
nullptr);
2375 Clang->getTarget().adjust(Clang->getLangOpts());
2377 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2378 "Invocation must have exactly one source file!");
2379 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_AST &&
2380 "FIXME: AST inputs not yet supported here!");
2381 assert(Clang->getFrontendOpts().Inputs[0].getKind() !=
IK_LLVM_IR &&
2382 "IR inputs not support here!");
2386 Clang->setFileManager(&FileMgr);
2387 Clang->setSourceManager(&SourceMgr);
2399 AugmentedCodeCompleteConsumer *AugmentedConsumer
2400 =
new AugmentedCodeCompleteConsumer(*
this, Consumer, CodeCompleteOpts);
2401 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2407 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2409 std::string CompleteFilePath(File);
2410 llvm::sys::fs::UniqueID CompleteFileID;
2412 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2413 std::string MainPath(OriginalSourceFile);
2414 llvm::sys::fs::UniqueID MainID;
2415 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2416 if (CompleteFileID == MainID && Line > 1)
2417 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2418 PCHContainerOps, *CCInvocation,
false, Line - 1);
2425 if (OverrideMainBuffer) {
2427 OverrideMainBuffer.get());
2430 = PreambleEndsAtStartOfLine;
2434 OwnedBuffers.push_back(OverrideMainBuffer.release());
2441 if (!Clang->getLangOpts().Modules)
2444 std::unique_ptr<SyntaxOnlyAction> Act;
2446 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2448 Act->EndSourceFile();
2453 if (HadModuleLoaderFatalFailure)
2460 TempPath +=
"-%%%%%%%%";
2462 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2467 llvm::raw_fd_ostream Out(fd,
true);
2471 if (Out.has_error()) {
2476 if (llvm::sys::fs::rename(TempPath, File)) {
2477 llvm::sys::fs::remove(TempPath);
2489 Writer.
WriteAST(S, std::string(),
nullptr,
"", hasErrors);
2492 if (!Buffer.empty())
2493 OS.write(Buffer.data(), Buffer.size());
2502 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2506 llvm::BitstreamWriter Stream(Buffer);
2513 void ASTUnit::TranslateStoredDiagnostics(
2524 Result.reserve(Diags.size());
2525 for (
const StandaloneDiagnostic &SD : Diags) {
2527 if (SD.Filename.empty())
2540 Ranges.reserve(SD.Ranges.size());
2541 for (
const auto &Range : SD.Ranges) {
2548 FixIts.reserve(SD.FixIts.size());
2549 for (
const StandaloneFixIt &
FixIt : SD.FixIts) {
2559 SD.Message, Loc, Ranges, FixIts));
2585 if (FID.isInvalid())
2592 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2594 if (Decls->empty() || Decls->back().first <=
Offset) {
2595 Decls->push_back(LocDecl);
2599 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2600 LocDecl, llvm::less_first());
2602 Decls->insert(I, LocDecl);
2616 FileDeclsTy::iterator I = FileDecls.find(File);
2617 if (I == FileDecls.end())
2621 if (LocDecls.empty())
2624 LocDeclsTy::iterator BeginIt =
2625 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2626 std::make_pair(Offset, (
Decl *)
nullptr),
2627 llvm::less_first());
2628 if (BeginIt != LocDecls.begin())
2634 while (BeginIt != LocDecls.begin() &&
2635 BeginIt->second->isTopLevelDeclInObjCContainer())
2638 LocDeclsTy::iterator EndIt = std::upper_bound(
2639 LocDecls.begin(), LocDecls.end(),
2640 std::make_pair(Offset + Length, (
Decl *)
nullptr), llvm::less_first());
2641 if (EndIt != LocDecls.end())
2644 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2645 Decls.push_back(DIt->second);
2649 unsigned Line,
unsigned Col)
const {
2674 if (SourceMgr->
isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.
size()) {
2696 Offs < Preamble.
size()) {
2748 llvm::iterator_range<PreprocessingRecord::iterator>
2752 Mod = Reader->getModuleManager().getPrimaryModule();
2753 return Reader->getModulePreprocessedEntities(Mod);
2757 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2766 Mod = Reader->getModuleManager().getPrimaryModule();
2767 for (
const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2768 if (!Fn(context, D))
2777 TL != TLEnd; ++TL) {
2778 if (!Fn(context, *TL))
2786 struct PCHLocatorInfo {
2788 PCHLocatorInfo() : Mod(nullptr) {}
2793 PCHLocatorInfo &Info = *
static_cast<PCHLocatorInfo*
>(UserData);
2814 PCHLocatorInfo Info;
2815 Reader->getModuleManager().visit(
PCHLocator, &Info);
2817 return Info.Mod->File;
2826 void ASTUnit::PreambleData::countLines()
const {
2831 NumLines = std::count(Buffer.begin(), Buffer.end(),
'\n');
2833 if (Buffer.back() !=
'\n')
2838 ASTUnit::ConcurrencyState::ConcurrencyState() {
2839 Mutex =
new llvm::sys::MutexImpl(
true);
2842 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2843 delete static_cast<llvm::sys::MutexImpl *
>(Mutex);
2846 void ASTUnit::ConcurrencyState::start() {
2847 bool acquired =
static_cast<llvm::sys::MutexImpl *
>(Mutex)->tryacquire();
2848 assert(acquired &&
"Concurrent access to ASTUnit!");
2851 void ASTUnit::ConcurrencyState::finish() {
2852 static_cast<llvm::sys::MutexImpl *
>(Mutex)->release();
2857 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
2858 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2859 void ASTUnit::ConcurrencyState::start() {}
2860 void ASTUnit::ConcurrencyState::finish() {}
HeaderSearchOptions & getHeaderSearchOpts()
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
std::string OutputFile
The output file, if any.
stored_diag_iterator stored_diag_afterDriver_begin()
Defines the clang::ASTContext interface.
ASTContext & getASTContext() const
StringRef getMainFileName() const
llvm::iterator_range< PreprocessingRecord::iterator > getLocalPreprocessingEntities() const
Returns an iterator range for the local preprocessing entities of the local Preprocessor, if this is a parsed source file, or the loaded preprocessing entities of the primary module if this is an AST file.
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.
CompilerInvocation & getInvocation()
unsigned getNumWarnings() const
bool isInMainFileID(SourceLocation Loc)
DiagnosticConsumer * getClient()
virtual Decl * GetExternalDecl(uint32_t ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
SourceLocation getBegin() const
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
Implements support for file system lookup, file system caching, and directory search management...
bool isLoadedFileID(FileID FID) const
Returns true if FID came from a PCH/Module.
std::pair< unsigned, unsigned > InsertFromRange
static std::pair< unsigned, bool > ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
bool operator==(CanQual< T > x, CanQual< U > y)
Code completion for a selector, as in an @selector expression.
void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
const LangOptions & getLangOpts() const
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...
Code completion where an Objective-C class message is expected.
const DiagnosticsEngine & getDiagnostics() const
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
Code completion within a type-qualifier list.
StringRef getMessage() const
SourceLocation getEndOfPreambleFileID()
ModuleKind Kind
The type of this module.
const unsigned DefaultPreambleRebuildInterval
After failing to build a precompiled preamble (due to errors in the source that occurs in the preambl...
Represents a diagnostic in a form that can be retained until its corresponding source manager is dest...
The translation unit is a prefix to a translation unit, and is not complete.
static const std::string & getPreambleFile(const ASTUnit *AU)
bool hasErrorOccurred() const
const SourceManager & getManager() const
std::string getAsString() const
IdentifierInfo * getAsIdentifierInfo() const
const FullSourceLoc & getLocation() const
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
An unspecified code-completion context.
NamespaceDecl - Represent a C++ namespace.
Allocator for a cached set of global code completions.
bool hasInvocation() const
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
llvm::sys::TimeValue getLastModificationTime() const
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Code completion occurred where an Objective-C message receiver is expected.
void assign(const FileEntry *F, const char *begin, const char *end)
static OnDiskDataMap & getOnDiskDataMap()
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
TargetInfo & getTarget() const
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
bool(* DeclVisitorFn)(void *context, const Decl *D)
Type for a function iterating over a number of declarations.
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Data used to determine if a file used in the preamble has been changed.
Options for controlling the target.
void addRemappedFile(StringRef From, StringRef To)
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
bool isModuleFile()
Returns true if the ASTUnit was constructed from a serialized module file.
static void checkAndSanitizeDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SourceManager &SM)
Code completion occurred within the instance variable list of an Objective-C interface, implementation, or category implementation.
This interface provides a way to observe the actions of the preprocessor as it does its thing...
Parse and apply any fixits to the source.
static PreambleFileHash createForMemoryBuffer(const llvm::MemoryBuffer *Buffer)
static ASTUnit * create(CompilerInvocation *CI, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, bool CaptureDiagnostics, bool UserFilesAreVolatile)
Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
std::vector< std::pair< unsigned, unsigned > > Ranges
comments::CommandTraits & getCommentCommandTraits() const
cached_completion_iterator cached_completion_end()
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Utility class for loading a ASTContext from an AST file.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
A "string" used to describe how code completion can be performed for an entity.
void HandleTranslationUnit(ASTContext &Ctx) override
bool isAnyPointerType() const
static std::atomic< unsigned > ActiveASTUnitObjects
Tracks the number of ASTUnit objects that are currently active.
unsigned getIdentifierNamespace() const
bool isTranslationUnit() const
static std::unique_ptr< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls=false, ArrayRef< RemappedFile > RemappedFiles=None, bool CaptureDiagnostics=false, bool AllowPCHWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
unsigned DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::unique_ptr< llvm::MemoryBuffer > getBufferForFile(StringRef Filename, std::string *ErrorStr=nullptr)
bool BeforePreviousInsertions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Describes a module or submodule.
const SourceManager & getSourceManager() const
virtual 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. Length can be 0 to indicate a ...
An allocator used specifically for the purpose of code completion.
DiagnosticsEngine::Level Level
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
const LangOptions & getLangOpts() const
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
FrontendOptions & getFrontendOpts()
const FileEntry * getPCHFile()
Get the PCH file if one was included.
Code completion occurred where a preprocessor directive is expected.
bool serialize(raw_ostream &OS)
Serialize this translation unit with the given output stream.
Concrete class used by the front-end to report problems and issues.
virtual CodeCompletionTUInfo & getCodeCompletionTUInfo()=0
Code completion occurred within an Objective-C implementation or category implementation.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
void addFileLevelDecl(Decl *D)
Add a new local file-level declaration.
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...
Code completion occurred where a namespace or namespace alias is expected.
ASTDeserializationListener * getDeserializationListener()
DeclContext * getLexicalDeclContext()
The result of a status operation.
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag)
void Reset()
Reset the state of the diagnostic object to its initial configuration.
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
The AST file itself appears corrupted.
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
QualType getPreferredType() const
Retrieve the type that this expression would prefer to have, e.g., if the expression is a variable in...
void WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false)
Write a precompiled header for the given semantic analysis.
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...
FrontendOptions & getFrontendOpts()
Code completion where an Objective-C category name is expected.
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static void checkAndRemoveNonDriverDiags(SmallVectorImpl< StoredDiagnostic > &StoredDiags)
Sema - This implements semantic analysis and AST building for C.
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope...
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Divide by this factor when a code-completion result's type exactly matches the type we expect...
std::string CurrentModule
The name of the current module.
StringRef getASTFileName() const
If this ASTUnit came from an AST file, returns the filename for it.
SourceLocation getLocForEndOfFile(FileID FID) const
Return the source location corresponding to the last byte of the specified file.
void setPreprocessor(Preprocessor *pp)
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
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...
const FileManager & getFileManager() const
Code completion occurred where a protocol name is expected.
SourceLocation getMacroArgExpandedLocation(SourceLocation Loc) const
If Loc points inside a function macro argument, the returned location will be the macro location in w...
bool hadModuleLoaderFatalFailure() const
Allows QualTypes to be sorted and hence used in maps and sets.
static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile)
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. Length can be 0 to indicate a ...
CodeCompletionTUInfo & getCodeCompletionTUInfo()
StringRef getName() const
Return the actual identifier string.
Code completion occurred where a new name is expected.
Represents a character-granular source range.
std::pair< unsigned, unsigned > RemoveRange
off_t Size
All files have size set.
SourceLocation getEnd() const
unsigned & getCurrentTopLevelHashValue()
Retrieve a reference to the current top-level name hash value.
static void erasePreambleFile(const ASTUnit *AU)
unsigned IncludeCodePatterns
Show code patterns in code completion results.
virtual void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults)
Process the finalized code-completion results.
std::vector< StandaloneFixIt > FixIts
Defines the clang::Preprocessor interface.
IntrusiveRefCntPtr< vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
static PreambleFileHash createForFile(off_t Size, time_t ModTime)
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to. In the latter case...
FileID getPreambleFileID() const
Get the file ID for the precompiled preamble if there is one.
DeclContext * getDeclContext()
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
stored_diag_const_iterator stored_diag_end() const
Information about a module that has been loaded by the ASTReader.
Captures a result of code completion.
Code completion occurred where a new name is expected and a qualified name is permissible.
static unsigned getDeclShowContexts(const NamedDecl *ND, const LangOptions &LangOpts, bool &IsNestedNameSpecifier)
Determine the set of code-completion contexts in which this declaration should be shown...
static std::string GetPreamblePCHPath()
Simple function to retrieve a path for a preamble precompiled header.
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
std::string FileName
The file name of the module file.
bool BeforePreviousInsertions
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
static llvm::sys::SmartMutex< false > & getOnDiskMutex()
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
SmallString< 128 > Buffer
DeclarationName getDeclName() const
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, const LangOptions &LangOpts, const FixItHint &InFix)
top_level_iterator top_level_begin()
The result type of a method or function.
The client can't handle any AST loading failures.
The AST file was missing.
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
std::unique_ptr< Sema > takeSema()
static OnDiskData & getOnDiskData(const ASTUnit *AU)
static CharSourceRange getCharRange(SourceRange R)
Options controlling the behavior of code completion.
The context in which code completion occurred, so that the code-completion consumer can process the r...
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
CharSourceRange RemoveRange
Code that should be replaced to correct the error. Empty for an insertion hint.
Abstract interface for external sources of AST nodes.
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...
ArrayRef< FixItHint > getFixIts() const
The control block was read successfully. Aside from failures, the AST file is safe to read into the c...
Code completion occurred within a class, struct, or union.
static void cleanupOnDiskMapAtExit()
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
File is a PCH file treated as the preamble.
ContinuousRangeMap< unsigned, int, 2 > SLocRemap
const char * getName() const
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
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...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
bool Execute()
Set the source manager's main input file, and run the action.
File is a PCH file treated as such.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool isValid() const
Return true if this is a valid SourceLocation object.
llvm::StringMap< unsigned > & getCachedCompletionTypes()
Retrieve the mapping from formatted type names to unique type identifiers.
std::vector< FrontendInputFile > Inputs
The input files and their types.
File is an implicitly-loaded module.
Cached information about one file (either on disk or in the virtual file system). ...
Code completion where the name of an Objective-C class is expected.
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
Abstract base class to use for AST consumer-based frontend actions.
Code completion occurred within an Objective-C interface, protocol, or category interface.
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates)
Defines the clang::TargetOptions class.
llvm::MemoryBuffer * getMemoryBufferForFile(const FileEntry *File, bool *Invalid=nullptr)
Retrieve the memory buffer associated with the given file.
static std::pair< unsigned, unsigned > makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
llvm::DenseMap< const ASTUnit *, std::unique_ptr< OnDiskData > > OnDiskDataMap
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.
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
static ASTUnit * LoadFromCompilerInvocationAction(CompilerInvocation *CI, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, ASTFrontendAction *Action=nullptr, ASTUnit *Unit=nullptr, bool Persistent=true, StringRef ResourceFilesPath=StringRef(), bool OnlyLocalDecls=false, bool CaptureDiagnostics=false, bool PrecompilePreamble=false, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=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...
llvm::BitstreamWriter Stream
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isFileContext() const
void setNumWarnings(unsigned NumWarnings)
The AST file was writtten with a different language/target configuration.
bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn)
Iterate over local declarations (locally parsed if this is a parsed source file or the loaded declara...
StoredDiagnostic * stored_diag_iterator
const ASTContext & getASTContext() const
File is a PCH file treated as the actual main file.
bool isInPreambleFileID(SourceLocation Loc)
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Priority for a nested-name-specifier.
virtual StringRef getFormat() const =0
Equivalent to the format passed to -fmodule-format=.
static ASTUnit * LoadFromCommandLine(const char **ArgBegin, const char **ArgEnd, std::shared_ptr< PCHContainerOperations > PCHContainerOps, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, StringRef ResourceFilesPath, bool OnlyLocalDecls=false, bool CaptureDiagnostics=false, ArrayRef< RemappedFile > RemappedFiles=None, bool RemappedFilesKeepOriginalName=true, bool PrecompilePreamble=false, TranslationUnitKind TUKind=TU_Complete, bool CacheCodeCompletionResults=false, bool IncludeBriefCommentsInCodeCompletion=false, bool AllowPCHWithCompilerErrors=false, bool SkipFunctionBodies=false, bool UserFilesAreVolatile=false, bool ForSerialization=false, std::unique_ptr< ASTUnit > *ErrAST=nullptr)
Abstract interface for a consumer of code-completion information.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
static ASTUnit::StandaloneDiagnostic makeStandaloneDiagnostic(const LangOptions &LangOpts, const StoredDiagnostic &InDiag)
unsigned IncludeGlobals
Show top-level decls in code completion results.
bool Reparse(std::shared_ptr< PCHContainerOperations > PCHContainerOps, ArrayRef< RemappedFile > RemappedFiles=None)
Reparse the source files using the same command-line options that were originally used to produce thi...
Code completion occurred where an macro is being defined.
bool hasSourceManager() const
PreprocessorOptions & getPreprocessorOpts()
frontend::ActionKind ProgramAction
The frontend action to perform.
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name...
Reads an AST files chain containing the contents of a translation unit.
File is an explicitly-loaded module.
CompilerInvocation * createInvocationFromCommandLine(ArrayRef< const char * > Args, IntrusiveRefCntPtr< DiagnosticsEngine > Diags=IntrusiveRefCntPtr< DiagnosticsEngine >())
Code completion occurred after the "union" keyword, to indicate a union name.
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
std::vector< Decl * >::iterator top_level_iterator
A builder class used to construct new code-completion strings.
Code completion where an Objective-C instance message is expected.
ASTMutationListener * getASTMutationListener()
Helper class for holding the data necessary to invoke the compiler.
DiagnosticOptions & getDiagnosticOpts() const
Defines the virtual file system interface vfs::FileSystem.
static bool PCHLocator(serialization::ModuleFile &M, void *UserData)
void addTemporaryFile(StringRef TempFile)
Add a temporary file that the ASTUnit depends on.
top_level_iterator top_level_end()
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
A map from continuous integer ranges to some value, with a very specialized interface.
FrontendOptions - Options for controlling the behavior of the frontend.
FileID translateFile(const FileEntry *SourceFile) const
Get the FileID for the given file.
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
bool isMainFileAST() const
SourceLocation getStartOfMainFileID()
Code completion occurred on the right-hand side of an Objective-C property access expression...
SmallVector< Context, 8 > Contexts
Defines the Diagnostic-related interfaces.
SourceLocation mapLocationFromPreamble(SourceLocation Loc)
If Loc is a loaded location from the preamble, returns the corresponding local location of the main f...
bool Save(StringRef File)
Save this translation unit to a file with the given name.
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
cached_completion_iterator cached_completion_begin()
time_t getModificationTime() const
Abstract interface for callback invocations by the ASTReader.
SourceManager & getSourceManager() const
enum Kind getKind() const
Retrieve the kind of code-completion context.
CodeCompleteOptions CodeCompleteOpts
bool hasASTContext() const
ArrayRef< CharSourceRange > getRanges() const
Keeps track of options that affect how file operations are performed.
unsigned DisableFree
Disable memory freeing on exit.
Generate pre-compiled header.
static bool serializeUnit(ASTWriter &Writer, SmallVectorImpl< char > &Buffer, Sema &S, bool hasErrors, raw_ostream &OS)
Code completion occurred within a preprocessor expression.
Code completion occurred where an expression is expected.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
BoundNodesTreeBuilder *const Builder
virtual CodeCompletionAllocator & getAllocator()=0
Retrieve the allocator that will be used to allocate code completion strings.
SourceLocation getLocation(const FileEntry *File, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
An unspecified code-completion context where we should also add macro completions.
unsigned IncludeMacros
Show macros in code completion results.
Level
The level of the diagnostic, after it has been through mapping.
std::vector< CachedCodeCompletionResult >::iterator cached_completion_iterator
TranslationUnitKind
Describes the kind of translation unit being processed.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
FileSystemOptions & getFileSystemOpts()
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
Writes an AST file containing the contents of a translation unit.
DiagnosticsEngine::Level getLevel() const
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
The AST file is out-of-date relative to its input files, and needs to be regenerated.
A SourceLocation and its associated SourceManager.
The translation unit is a complete translation unit.
SourceLocation mapLocationToPreamble(SourceLocation Loc)
If Loc is a local location of the main file but inside the preamble chunk, returns the corresponding ...
bool hasPreprocessor() const
const char * getBufferStart() const
std::unique_ptr< ASTConsumer > takeASTConsumer()
The AST file was written by a different version of Clang.
Code completion occurred on the right-hand side of a member access expression using the dot operator...
void clearRemappedFiles()
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion...
AST and semantic-analysis consumer that generates a precompiled header from the parsed source code...
Code completion occurred where a type name is expected.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
static raw_pwrite_stream * ComputeASTConsumerArguments(CompilerInstance &CI, StringRef InFile, std::string &Sysroot, std::string &OutputFile)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
void InitBuiltinTypes(const TargetInfo &Target)
Initialize built-in types.
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
SourceLocation getLocation() 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, DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, FileManager &FileMgr, SmallVectorImpl< StoredDiagnostic > &StoredDiagnostics, SmallVectorImpl< const llvm::MemoryBuffer * > &OwnedBuffers)
Perform code completion at the given file, line, and column within this translation unit...
LangOptions * getLangOpts()
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
This class handles loading and caching of source files into memory.
Divide by this factor when a code-completion result's type is similar to the type we expect (e...
Priority for a code pattern.
static void removeOnDiskEntry(const ASTUnit *AU)
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
IdentifierInfo * getIdentifierInfo() const