1 //===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit Implementation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeOrdering.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Basic/TargetOptions.h"
23 #include "clang/Basic/VirtualFileSystem.h"
24 #include "clang/Frontend/CompilerInstance.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/FrontendOptions.h"
28 #include "clang/Frontend/MultiplexConsumer.h"
29 #include "clang/Frontend/Utils.h"
30 #include "clang/Lex/HeaderSearch.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Sema/Sema.h"
34 #include "clang/Serialization/ASTReader.h"
35 #include "clang/Serialization/ASTWriter.h"
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());
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
86 /// \brief Temporary files that should be removed when the ASTUnit is
88 SmallVector<std::string, 4> TemporaryFiles;
90 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
96 /// \brief Erase temporary files and the preamble file.
101 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
106 static void cleanupOnDiskMapAtExit();
108 typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
110 static OnDiskDataMap &getOnDiskDataMap() {
111 static OnDiskDataMap M;
112 static bool hasRegisteredAtExit = false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit = true;
115 atexit(cleanupOnDiskMapAtExit);
120 static void cleanupOnDiskMapAtExit() {
121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
123 for (const auto &I : getOnDiskDataMap()) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
130 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
131 // We require the mutex since we are modifying the structure of the
133 llvm::MutexGuard Guard(getOnDiskMutex());
134 OnDiskDataMap &M = getOnDiskDataMap();
137 D = llvm::make_unique<OnDiskData>();
141 static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
145 static void removeOnDiskEntry(const ASTUnit *AU) {
146 // We require the mutex since we are modifying the structure of the
148 llvm::MutexGuard Guard(getOnDiskMutex());
149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
152 I->second->Cleanup();
157 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
158 getOnDiskData(AU).PreambleFile = preambleFile;
161 static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
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();
183 struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
191 void ASTUnit::clearFileLevelDecls() {
192 llvm::DeleteContainerSeconds(FileDecls);
195 void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
199 void ASTUnit::addTemporaryFile(StringRef TempFile) {
200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
203 /// \brief After failing to build a precompiled preamble (due to
204 /// errors in the source that occurs in the preamble), the number of
205 /// reparses during which we'll skip even trying to precompile the
207 const unsigned DefaultPreambleRebuildInterval = 5;
209 /// \brief Tracks the number of ASTUnit objects that are currently active.
211 /// Used for debugging purposes only.
212 static std::atomic<unsigned> ActiveASTUnitObjects;
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"))
230 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
233 ASTUnit::~ASTUnit() {
234 // If we loaded from an AST file, balance out the BeginSourceFile call.
235 if (MainFileIsAST && getDiagnostics().getClient()) {
236 getDiagnostics().getClient()->EndSourceFile();
239 clearFileLevelDecls();
241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
248 if (Invocation.get() && OwnsRemappedFileBuffers) {
249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
250 for (const auto &RB : PPOpts.RemappedFileBuffers)
254 ClearCachedCompletionResults();
256 if (getenv("LIBCLANG_OBJTRACKING"))
257 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
260 void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
262 /// \brief Determine the set of code-completion contexts in which this
263 /// declaration should be shown.
264 static unsigned getDeclShowContexts(const NamedDecl *ND,
265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
269 if (isa<UsingShadowDecl>(ND))
270 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
274 uint64_t Contexts = 0;
275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
277 // Types can appear in these contexts.
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
279 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
280 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
281 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
282 | (1LL << CodeCompletionContext::CCC_Statement)
283 | (1LL << CodeCompletionContext::CCC_Type)
284 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
290 // In Objective-C, message sends can send interfaces. In Objective-C++,
291 // all types are available due to functional casts.
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
295 // In Objective-C, you can only be a subclass of another Objective-C class
296 if (isa<ObjCInterfaceDecl>(ND))
297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
303 // Part of the nested-name-specifier in C++0x.
304 if (LangOpts.CPlusPlus11)
305 IsNestedNameSpecifier = true;
306 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
307 if (Record->isUnion())
308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
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)) {
317 // Values can appear in these contexts.
318 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
319 | (1LL << CodeCompletionContext::CCC_Expression)
320 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
321 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
322 } else if (isa<ObjCProtocolDecl>(ND)) {
323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
324 } else if (isa<ObjCCategoryDecl>(ND)) {
325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
329 // Part of the nested-name-specifier.
330 IsNestedNameSpecifier = true;
336 void ASTUnit::CacheCodeCompletionResults() {
340 SimpleTimer Timer(WantTiming);
341 Timer.setOutput("Cache global code completions for " + getMainFileName());
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
346 // Gather the set of global code completions.
347 typedef CodeCompletionResult Result;
348 SmallVector<Result, 8> Results;
349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
350 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
354 // Translate global code completions into cached completions.
355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
357 for (Result &R : Results) {
359 case Result::RK_Declaration: {
360 bool IsNestedNameSpecifier = false;
361 CachedCodeCompletionResult CachedResult;
362 CachedResult.Completion = R.CreateCodeCompletionString(
363 *TheSema, *CachedCompletionAllocator, CCTUInfo,
364 IncludeBriefCommentsInCodeCompletion);
365 CachedResult.ShowInContexts = getDeclShowContexts(
366 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
367 CachedResult.Priority = R.Priority;
368 CachedResult.Kind = R.CursorKind;
369 CachedResult.Availability = R.Availability;
371 // Keep track of the type of this completion in an ASTContext-agnostic
373 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
374 if (UsageType.isNull()) {
375 CachedResult.TypeClass = STC_Void;
376 CachedResult.Type = 0;
378 CanQualType CanUsageType
379 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
380 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
382 // Determine whether we have already seen this type. If so, we save
383 // ourselves the work of formatting the type string by using the
384 // temporary, CanQualType-based hash table to find the associated value.
385 unsigned &TypeValue = CompletionTypes[CanUsageType];
386 if (TypeValue == 0) {
387 TypeValue = CompletionTypes.size();
388 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
392 CachedResult.Type = TypeValue;
395 CachedCompletionResults.push_back(CachedResult);
397 /// Handle nested-name-specifiers in C++.
398 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
399 !R.StartsNestedNameSpecifier) {
400 // The contexts in which a nested-name-specifier can appear in C++.
402 = (1LL << CodeCompletionContext::CCC_TopLevel)
403 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
404 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
405 | (1LL << CodeCompletionContext::CCC_Statement)
406 | (1LL << CodeCompletionContext::CCC_Expression)
407 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
408 | (1LL << CodeCompletionContext::CCC_EnumTag)
409 | (1LL << CodeCompletionContext::CCC_UnionTag)
410 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
411 | (1LL << CodeCompletionContext::CCC_Type)
412 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
413 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
415 if (isa<NamespaceDecl>(R.Declaration) ||
416 isa<NamespaceAliasDecl>(R.Declaration))
417 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
419 if (unsigned RemainingContexts
420 = NNSContexts & ~CachedResult.ShowInContexts) {
421 // If there any contexts where this completion can be a
422 // nested-name-specifier but isn't already an option, create a
423 // nested-name-specifier completion.
424 R.StartsNestedNameSpecifier = true;
425 CachedResult.Completion = R.CreateCodeCompletionString(
426 *TheSema, *CachedCompletionAllocator, CCTUInfo,
427 IncludeBriefCommentsInCodeCompletion);
428 CachedResult.ShowInContexts = RemainingContexts;
429 CachedResult.Priority = CCP_NestedNameSpecifier;
430 CachedResult.TypeClass = STC_Void;
431 CachedResult.Type = 0;
432 CachedCompletionResults.push_back(CachedResult);
438 case Result::RK_Keyword:
439 case Result::RK_Pattern:
440 // Ignore keywords and patterns; we don't care, since they are so
441 // easily regenerated.
444 case Result::RK_Macro: {
445 CachedCodeCompletionResult CachedResult;
446 CachedResult.Completion = R.CreateCodeCompletionString(
447 *TheSema, *CachedCompletionAllocator, CCTUInfo,
448 IncludeBriefCommentsInCodeCompletion);
449 CachedResult.ShowInContexts
450 = (1LL << CodeCompletionContext::CCC_TopLevel)
451 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
452 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
453 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
454 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
455 | (1LL << CodeCompletionContext::CCC_Statement)
456 | (1LL << CodeCompletionContext::CCC_Expression)
457 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
458 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
459 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
460 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
461 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
463 CachedResult.Priority = R.Priority;
464 CachedResult.Kind = R.CursorKind;
465 CachedResult.Availability = R.Availability;
466 CachedResult.TypeClass = STC_Void;
467 CachedResult.Type = 0;
468 CachedCompletionResults.push_back(CachedResult);
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
478 void ASTUnit::ClearCachedCompletionResults() {
479 CachedCompletionResults.clear();
480 CachedCompletionTypes.clear();
481 CachedCompletionAllocator = nullptr;
486 /// \brief Gathers information from ASTReader that will be used to initialize
488 class ASTInfoCollector : public ASTReaderListener {
491 LangOptions &LangOpt;
492 std::shared_ptr<TargetOptions> &TargetOpts;
493 IntrusiveRefCntPtr<TargetInfo> &Target;
496 bool InitializedLanguage;
498 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
499 std::shared_ptr<TargetOptions> &TargetOpts,
500 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
501 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
502 Target(Target), Counter(Counter), InitializedLanguage(false) {}
504 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
505 bool AllowCompatibleDifferences) override {
506 if (InitializedLanguage)
510 InitializedLanguage = true;
516 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
517 bool AllowCompatibleDifferences) override {
518 // If we've already initialized the target, don't do it again.
522 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
524 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
530 void ReadCounter(const serialization::ModuleFile &M,
531 unsigned Value) override {
537 if (!Target || !InitializedLanguage)
540 // Inform the target of the language options.
542 // FIXME: We shouldn't need to do this, the target should be immutable once
543 // created. This complexity should be lifted elsewhere.
544 Target->adjust(LangOpt);
546 // Initialize the preprocessor.
547 PP.Initialize(*Target);
549 // Initialize the ASTContext
550 Context.InitBuiltinTypes(*Target);
552 // We didn't have access to the comment options when the ASTContext was
553 // constructed, so register them now.
554 Context.getCommentCommandTraits().registerCommentOptions(
555 LangOpt.CommentOpts);
559 /// \brief Diagnostic consumer that saves each diagnostic it is given.
560 class StoredDiagnosticConsumer : public DiagnosticConsumer {
561 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
562 SourceManager *SourceMgr;
565 explicit StoredDiagnosticConsumer(
566 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
567 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
569 void BeginSourceFile(const LangOptions &LangOpts,
570 const Preprocessor *PP = nullptr) override {
572 SourceMgr = &PP->getSourceManager();
575 void HandleDiagnostic(DiagnosticsEngine::Level Level,
576 const Diagnostic &Info) override;
579 /// \brief RAII object that optionally captures diagnostics, if
580 /// there is no diagnostic client to capture them already.
581 class CaptureDroppedDiagnostics {
582 DiagnosticsEngine &Diags;
583 StoredDiagnosticConsumer Client;
584 DiagnosticConsumer *PreviousClient;
585 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
588 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
590 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
592 if (RequestCapture || Diags.getClient() == nullptr) {
593 OwningPreviousClient = Diags.takeClient();
594 PreviousClient = Diags.getClient();
595 Diags.setClient(&Client, false);
599 ~CaptureDroppedDiagnostics() {
600 if (Diags.getClient() == &Client)
601 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
605 } // anonymous namespace
607 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
608 const Diagnostic &Info) {
609 // Default implementation (Warnings/errors count).
610 DiagnosticConsumer::HandleDiagnostic(Level, Info);
612 // Only record the diagnostic if it's part of the source manager we know
613 // about. This effectively drops diagnostics from modules we're building.
614 // FIXME: In the long run, ee don't want to drop source managers from modules.
615 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
616 StoredDiags.push_back(StoredDiagnostic(Level, Info));
619 ASTMutationListener *ASTUnit::getASTMutationListener() {
621 return &WriterData->Writer;
625 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
627 return &WriterData->Writer;
631 std::unique_ptr<llvm::MemoryBuffer>
632 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
634 auto Buffer = FileMgr->getBufferForFile(Filename);
636 return std::move(*Buffer);
638 *ErrorStr = Buffer.getError().message();
642 /// \brief Configure the diagnostics object for use with ASTUnit.
643 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
644 ASTUnit &AST, bool CaptureDiagnostics) {
645 assert(Diags.get() && "no DiagnosticsEngine was provided");
646 if (CaptureDiagnostics)
647 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
650 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
651 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
652 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
653 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
654 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
655 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
657 // Recover resources if we crash before exiting this method.
658 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
659 ASTUnitCleanup(AST.get());
660 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
661 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
662 DiagCleanup(Diags.get());
664 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
666 AST->OnlyLocalDecls = OnlyLocalDecls;
667 AST->CaptureDiagnostics = CaptureDiagnostics;
668 AST->Diagnostics = Diags;
669 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
670 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
671 AST->UserFilesAreVolatile = UserFilesAreVolatile;
672 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
673 AST->getFileManager(),
674 UserFilesAreVolatile);
675 AST->HSOpts = new HeaderSearchOptions();
677 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
678 AST->getSourceManager(),
679 AST->getDiagnostics(),
680 AST->ASTFileLangOpts,
681 /*Target=*/nullptr));
683 PreprocessorOptions *PPOpts = new PreprocessorOptions();
685 for (const auto &RemappedFile : RemappedFiles)
686 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
688 // Gather Info for preprocessor construction later on.
690 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
694 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
695 AST->getSourceManager(), HeaderInfo, *AST,
696 /*IILookup=*/nullptr,
697 /*OwnsHeaderSearch=*/false);
698 Preprocessor &PP = *AST->PP;
700 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
701 PP.getIdentifierTable(), PP.getSelectorTable(),
702 PP.getBuiltinInfo());
703 ASTContext &Context = *AST->Ctx;
705 bool disableValid = false;
706 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
708 AST->Reader = new ASTReader(PP, Context,
710 /*DisableValidation=*/disableValid,
711 AllowPCHWithCompilerErrors);
713 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
714 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
717 // Attach the AST reader to the AST context as an external AST
718 // source, so that declarations will be deserialized from the
719 // AST file as needed.
720 // We need the external source to be set up before we read the AST, because
721 // eagerly-deserialized declarations may use it.
722 Context.setExternalSource(AST->Reader);
724 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
725 SourceLocation(), ASTReader::ARR_None)) {
726 case ASTReader::Success:
729 case ASTReader::Failure:
730 case ASTReader::Missing:
731 case ASTReader::OutOfDate:
732 case ASTReader::VersionMismatch:
733 case ASTReader::ConfigurationMismatch:
734 case ASTReader::HadErrors:
735 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
739 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
741 PP.setCounterValue(Counter);
743 // Create an AST consumer, even though it isn't used.
744 AST->Consumer.reset(new ASTConsumer);
746 // Create a semantic analysis object and tell the AST reader about it.
747 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
748 AST->TheSema->Initialize();
749 AST->Reader->InitializeSema(*AST->TheSema);
751 // Tell the diagnostic client that we have started a source file.
752 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
759 /// \brief Preprocessor callback class that updates a hash value with the names
760 /// of all macros that have been defined by the translation unit.
761 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
765 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
767 void MacroDefined(const Token &MacroNameTok,
768 const MacroDirective *MD) override {
769 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
773 /// \brief Add the given declaration to the hash of all top-level entities.
774 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
778 DeclContext *DC = D->getDeclContext();
782 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
785 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
786 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
787 // For an unscoped enum include the enumerators in the hash since they
788 // enter the top-level namespace.
789 if (!EnumD->isScoped()) {
790 for (const auto *EI : EnumD->enumerators()) {
791 if (EI->getIdentifier())
792 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
797 if (ND->getIdentifier())
798 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
799 else if (DeclarationName Name = ND->getDeclName()) {
800 std::string NameStr = Name.getAsString();
801 Hash = llvm::HashString(NameStr, Hash);
806 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
807 if (Module *Mod = ImportD->getImportedModule()) {
808 std::string ModName = Mod->getFullModuleName();
809 Hash = llvm::HashString(ModName, Hash);
815 class TopLevelDeclTrackerConsumer : public ASTConsumer {
820 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
821 : Unit(_Unit), Hash(Hash) {
825 void handleTopLevelDecl(Decl *D) {
829 // FIXME: Currently ObjC method declarations are incorrectly being
830 // reported as top-level declarations, even though their DeclContext
831 // is the containing ObjC @interface/@implementation. This is a
832 // fundamental problem in the parser right now.
833 if (isa<ObjCMethodDecl>(D))
836 AddTopLevelDeclarationToHash(D, Hash);
837 Unit.addTopLevelDecl(D);
839 handleFileLevelDecl(D);
842 void handleFileLevelDecl(Decl *D) {
843 Unit.addFileLevelDecl(D);
844 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
845 for (auto *I : NSD->decls())
846 handleFileLevelDecl(I);
850 bool HandleTopLevelDecl(DeclGroupRef D) override {
851 for (Decl *TopLevelDecl : D)
852 handleTopLevelDecl(TopLevelDecl);
856 // We're not interested in "interesting" decls.
857 void HandleInterestingDecl(DeclGroupRef) override {}
859 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
860 for (Decl *TopLevelDecl : D)
861 handleTopLevelDecl(TopLevelDecl);
864 ASTMutationListener *GetASTMutationListener() override {
865 return Unit.getASTMutationListener();
868 ASTDeserializationListener *GetASTDeserializationListener() override {
869 return Unit.getDeserializationListener();
873 class TopLevelDeclTrackerAction : public ASTFrontendAction {
877 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
878 StringRef InFile) override {
879 CI.getPreprocessor().addPPCallbacks(
880 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
881 Unit.getCurrentTopLevelHashValue()));
882 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
883 Unit, Unit.getCurrentTopLevelHashValue());
887 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
889 bool hasCodeCompletionSupport() const override { return false; }
890 TranslationUnitKind getTranslationUnitKind() override {
891 return Unit.getTranslationUnitKind();
895 class PrecompilePreambleAction : public ASTFrontendAction {
897 bool HasEmittedPreamblePCH;
900 explicit PrecompilePreambleAction(ASTUnit &Unit)
901 : Unit(Unit), HasEmittedPreamblePCH(false) {}
903 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
904 StringRef InFile) override;
905 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
906 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
907 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
909 bool hasCodeCompletionSupport() const override { return false; }
910 bool hasASTFileSupport() const override { return false; }
911 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
914 class PrecompilePreambleConsumer : public PCHGenerator {
917 std::vector<Decl *> TopLevelDecls;
918 PrecompilePreambleAction *Action;
921 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
922 const Preprocessor &PP, StringRef isysroot,
924 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
925 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
929 bool HandleTopLevelDecl(DeclGroupRef DG) override {
931 // FIXME: Currently ObjC method declarations are incorrectly being
932 // reported as top-level declarations, even though their DeclContext
933 // is the containing ObjC @interface/@implementation. This is a
934 // fundamental problem in the parser right now.
935 if (isa<ObjCMethodDecl>(D))
937 AddTopLevelDeclarationToHash(D, Hash);
938 TopLevelDecls.push_back(D);
943 void HandleTranslationUnit(ASTContext &Ctx) override {
944 PCHGenerator::HandleTranslationUnit(Ctx);
945 if (hasEmittedPCH()) {
946 // Translate the top-level declarations we captured during
947 // parsing into declaration IDs in the precompiled
948 // preamble. This will allow us to deserialize those top-level
949 // declarations when requested.
950 for (Decl *D : TopLevelDecls) {
951 // Invalid top-level decls may not have been serialized.
952 if (D->isInvalidDecl())
954 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
957 Action->setHasEmittedPreamblePCH();
964 std::unique_ptr<ASTConsumer>
965 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
968 std::string OutputFile;
969 raw_ostream *OS = GeneratePCHAction::ComputeASTConsumerArguments(
970 CI, InFile, Sysroot, OutputFile);
974 if (!CI.getFrontendOpts().RelocatablePCH)
977 CI.getPreprocessor().addPPCallbacks(
978 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
979 Unit.getCurrentTopLevelHashValue()));
980 return llvm::make_unique<PrecompilePreambleConsumer>(
981 Unit, this, CI.getPreprocessor(), Sysroot, OS);
984 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
985 return StoredDiag.getLocation().isValid();
989 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
990 // Get rid of stored diagnostics except the ones from the driver which do not
991 // have a source location.
993 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
997 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1000 // The stored diagnostic has the old source manager in it; update
1001 // the locations to refer into the new source manager. Since we've
1002 // been careful to make sure that the source manager's state
1003 // before and after are identical, so that we can reuse the source
1005 for (StoredDiagnostic &SD : StoredDiagnostics) {
1006 if (SD.getLocation().isValid()) {
1007 FullSourceLoc Loc(SD.getLocation(), SM);
1008 SD.setLocation(Loc);
1013 /// Parse the source file into a translation unit using the given compiler
1014 /// invocation, replacing the current translation unit.
1016 /// \returns True if a failure occurred that causes the ASTUnit not to
1017 /// contain any translation-unit information, false otherwise.
1018 bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1019 SavedMainFileBuffer.reset();
1024 // Create the compiler instance to use for building the AST.
1025 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
1027 // Recover resources if we crash before exiting this method.
1028 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1029 CICleanup(Clang.get());
1031 IntrusiveRefCntPtr<CompilerInvocation>
1032 CCInvocation(new CompilerInvocation(*Invocation));
1034 Clang->setInvocation(CCInvocation.get());
1035 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1037 // Set up diagnostics, capturing any diagnostics that would
1038 // otherwise be dropped.
1039 Clang->setDiagnostics(&getDiagnostics());
1041 // Create the target instance.
1042 Clang->setTarget(TargetInfo::CreateTargetInfo(
1043 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1044 if (!Clang->hasTarget())
1047 // Inform the target of the language options.
1049 // FIXME: We shouldn't need to do this, the target should be immutable once
1050 // created. This complexity should be lifted elsewhere.
1051 Clang->getTarget().adjust(Clang->getLangOpts());
1053 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1054 "Invocation must have exactly one source file!");
1055 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1056 "FIXME: AST inputs not yet supported here!");
1057 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1058 "IR inputs not support here!");
1060 // Configure the various subsystems.
1061 LangOpts = Clang->getInvocation().LangOpts;
1062 FileSystemOpts = Clang->getFileSystemOpts();
1063 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1064 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1067 FileMgr = new FileManager(FileSystemOpts, VFS);
1068 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1069 UserFilesAreVolatile);
1075 // Clear out old caches and data.
1076 TopLevelDecls.clear();
1077 clearFileLevelDecls();
1078 CleanTemporaryFiles();
1080 if (!OverrideMainBuffer) {
1081 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1082 TopLevelDeclsInPreamble.clear();
1085 // Create a file manager object to provide access to and cache the filesystem.
1086 Clang->setFileManager(&getFileManager());
1088 // Create the source manager.
1089 Clang->setSourceManager(&getSourceManager());
1091 // If the main file has been overridden due to the use of a preamble,
1092 // make that override happen and introduce the preamble.
1093 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1094 if (OverrideMainBuffer) {
1095 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1096 OverrideMainBuffer.get());
1097 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1098 PreprocessorOpts.PrecompiledPreambleBytes.second
1099 = PreambleEndsAtStartOfLine;
1100 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1101 PreprocessorOpts.DisablePCHValidation = true;
1103 // The stored diagnostic has the old source manager in it; update
1104 // the locations to refer into the new source manager. Since we've
1105 // been careful to make sure that the source manager's state
1106 // before and after are identical, so that we can reuse the source
1108 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1110 // Keep track of the override buffer;
1111 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1114 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1115 new TopLevelDeclTrackerAction(*this));
1117 // Recover resources if we crash before exiting this method.
1118 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1119 ActCleanup(Act.get());
1121 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1124 if (SavedMainFileBuffer) {
1125 std::string ModName = getPreambleFile(this);
1126 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1127 PreambleDiagnostics, StoredDiagnostics);
1130 if (!Act->Execute())
1133 transferASTDataFromCompilerInstance(*Clang);
1135 Act->EndSourceFile();
1137 FailedParseDiagnostics.clear();
1142 // Remove the overridden buffer we used for the preamble.
1143 SavedMainFileBuffer = nullptr;
1145 // Keep the ownership of the data in the ASTUnit because the client may
1146 // want to see the diagnostics.
1147 transferASTDataFromCompilerInstance(*Clang);
1148 FailedParseDiagnostics.swap(StoredDiagnostics);
1149 StoredDiagnostics.clear();
1150 NumStoredDiagnosticsFromDriver = 0;
1154 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1155 static std::string GetPreamblePCHPath() {
1156 // FIXME: This is a hack so that we can override the preamble file during
1157 // crash-recovery testing, which is the only case where the preamble files
1158 // are not necessarily cleaned up.
1159 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1163 SmallString<128> Path;
1164 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1169 /// \brief Compute the preamble for the main file, providing the source buffer
1170 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1171 /// that describes the preamble.
1172 ASTUnit::ComputedPreamble
1173 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1174 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1175 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1177 // Try to determine if the main file has been remapped, either from the
1178 // command line (to another file) or directly through the compiler invocation
1179 // (to a memory buffer).
1180 llvm::MemoryBuffer *Buffer = nullptr;
1181 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1182 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1183 llvm::sys::fs::UniqueID MainFileID;
1184 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1185 // Check whether there is a file-file remapping of the main file
1186 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1187 std::string MPath(RF.first);
1188 llvm::sys::fs::UniqueID MID;
1189 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1190 if (MainFileID == MID) {
1191 // We found a remapping. Try to load the resulting, remapped source.
1192 BufferOwner = getBufferForFile(RF.second);
1194 return ComputedPreamble(nullptr, nullptr, 0, true);
1199 // Check whether there is a file-buffer remapping. It supercedes the
1200 // file-file remapping.
1201 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1202 std::string MPath(RB.first);
1203 llvm::sys::fs::UniqueID MID;
1204 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1205 if (MainFileID == MID) {
1206 // We found a remapping.
1207 BufferOwner.reset();
1208 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1214 // If the main source file was not remapped, load it now.
1215 if (!Buffer && !BufferOwner) {
1216 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1218 return ComputedPreamble(nullptr, nullptr, 0, true);
1222 Buffer = BufferOwner.get();
1223 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1224 *Invocation.getLangOpts(), MaxLines);
1225 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1229 ASTUnit::PreambleFileHash
1230 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1231 PreambleFileHash Result;
1233 Result.ModTime = ModTime;
1234 memset(Result.MD5, 0, sizeof(Result.MD5));
1238 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1239 const llvm::MemoryBuffer *Buffer) {
1240 PreambleFileHash Result;
1241 Result.Size = Buffer->getBufferSize();
1245 MD5Ctx.update(Buffer->getBuffer().data());
1246 MD5Ctx.final(Result.MD5);
1252 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1253 const ASTUnit::PreambleFileHash &RHS) {
1254 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1255 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1257 } // namespace clang
1259 static std::pair<unsigned, unsigned>
1260 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1261 const LangOptions &LangOpts) {
1262 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1263 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1264 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1265 return std::make_pair(Offset, EndOffset);
1268 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1269 const LangOptions &LangOpts,
1270 const FixItHint &InFix) {
1271 ASTUnit::StandaloneFixIt OutFix;
1272 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1273 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1275 OutFix.CodeToInsert = InFix.CodeToInsert;
1276 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1280 static ASTUnit::StandaloneDiagnostic
1281 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1282 const StoredDiagnostic &InDiag) {
1283 ASTUnit::StandaloneDiagnostic OutDiag;
1284 OutDiag.ID = InDiag.getID();
1285 OutDiag.Level = InDiag.getLevel();
1286 OutDiag.Message = InDiag.getMessage();
1287 OutDiag.LocOffset = 0;
1288 if (InDiag.getLocation().isInvalid())
1290 const SourceManager &SM = InDiag.getLocation().getManager();
1291 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1292 OutDiag.Filename = SM.getFilename(FileLoc);
1293 if (OutDiag.Filename.empty())
1295 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1296 for (const CharSourceRange &Range : InDiag.getRanges())
1297 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1298 for (const FixItHint &FixIt : InDiag.getFixIts())
1299 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1304 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1305 /// the source file.
1307 /// This routine will compute the preamble of the main source file. If a
1308 /// non-trivial preamble is found, it will precompile that preamble into a
1309 /// precompiled header so that the precompiled preamble can be used to reduce
1310 /// reparsing time. If a precompiled preamble has already been constructed,
1311 /// this routine will determine if it is still valid and, if so, avoid
1312 /// rebuilding the precompiled preamble.
1314 /// \param AllowRebuild When true (the default), this routine is
1315 /// allowed to rebuild the precompiled preamble if it is found to be
1318 /// \param MaxLines When non-zero, the maximum number of lines that
1319 /// can occur within the preamble.
1321 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1322 /// buffer that should be used in place of the main file when doing so.
1323 /// Otherwise, returns a NULL pointer.
1324 std::unique_ptr<llvm::MemoryBuffer>
1325 ASTUnit::getMainBufferWithPrecompiledPreamble(
1326 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1327 unsigned MaxLines) {
1329 IntrusiveRefCntPtr<CompilerInvocation>
1330 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1331 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1332 PreprocessorOptions &PreprocessorOpts
1333 = PreambleInvocation->getPreprocessorOpts();
1335 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1337 if (!NewPreamble.Size) {
1338 // We couldn't find a preamble in the main source. Clear out the current
1339 // preamble, if we have one. It's obviously no good any more.
1341 erasePreambleFile(this);
1343 // The next time we actually see a preamble, precompile it.
1344 PreambleRebuildCounter = 1;
1348 if (!Preamble.empty()) {
1349 // We've previously computed a preamble. Check whether we have the same
1350 // preamble now that we did before, and that there's enough space in
1351 // the main-file buffer within the precompiled preamble to fit the
1353 if (Preamble.size() == NewPreamble.Size &&
1354 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1355 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1356 NewPreamble.Size) == 0) {
1357 // The preamble has not changed. We may be able to re-use the precompiled
1360 // Check that none of the files used by the preamble have changed.
1361 bool AnyFileChanged = false;
1363 // First, make a record of those files that have been overridden via
1364 // remapping or unsaved_files.
1365 llvm::StringMap<PreambleFileHash> OverriddenFiles;
1366 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1371 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1372 // If we can't stat the file we're remapping to, assume that something
1373 // horrible happened.
1374 AnyFileChanged = true;
1378 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
1379 Status.getSize(), Status.getLastModificationTime().toEpochTime());
1382 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1385 OverriddenFiles[RB.first] =
1386 PreambleFileHash::createForMemoryBuffer(RB.second);
1389 // Check whether anything has changed.
1390 for (llvm::StringMap<PreambleFileHash>::iterator
1391 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1392 !AnyFileChanged && F != FEnd;
1394 llvm::StringMap<PreambleFileHash>::iterator Overridden
1395 = OverriddenFiles.find(F->first());
1396 if (Overridden != OverriddenFiles.end()) {
1397 // This file was remapped; check whether the newly-mapped file
1398 // matches up with the previous mapping.
1399 if (Overridden->second != F->second)
1400 AnyFileChanged = true;
1404 // The file was not remapped; check whether it has changed on disk.
1406 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1407 // If we can't stat the file, assume that something horrible happened.
1408 AnyFileChanged = true;
1409 } else if (Status.getSize() != uint64_t(F->second.Size) ||
1410 Status.getLastModificationTime().toEpochTime() !=
1411 uint64_t(F->second.ModTime))
1412 AnyFileChanged = true;
1415 if (!AnyFileChanged) {
1416 // Okay! We can re-use the precompiled preamble.
1418 // Set the state of the diagnostic object to mimic its state
1419 // after parsing the preamble.
1420 getDiagnostics().Reset();
1421 ProcessWarningOptions(getDiagnostics(),
1422 PreambleInvocation->getDiagnosticOpts());
1423 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1425 return llvm::MemoryBuffer::getMemBufferCopy(
1426 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1430 // If we aren't allowed to rebuild the precompiled preamble, just
1435 // We can't reuse the previously-computed preamble. Build a new one.
1437 PreambleDiagnostics.clear();
1438 erasePreambleFile(this);
1439 PreambleRebuildCounter = 1;
1440 } else if (!AllowRebuild) {
1441 // We aren't allowed to rebuild the precompiled preamble; just
1446 // If the preamble rebuild counter > 1, it's because we previously
1447 // failed to build a preamble and we're not yet ready to try
1448 // again. Decrement the counter and return a failure.
1449 if (PreambleRebuildCounter > 1) {
1450 --PreambleRebuildCounter;
1454 // Create a temporary file for the precompiled preamble. In rare
1455 // circumstances, this can fail.
1456 std::string PreamblePCHPath = GetPreamblePCHPath();
1457 if (PreamblePCHPath.empty()) {
1458 // Try again next time.
1459 PreambleRebuildCounter = 1;
1463 // We did not previously compute a preamble, or it can't be reused anyway.
1464 SimpleTimer PreambleTimer(WantTiming);
1465 PreambleTimer.setOutput("Precompiling preamble");
1467 // Save the preamble text for later; we'll need to compare against it for
1468 // subsequent reparses.
1469 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1470 Preamble.assign(FileMgr->getFile(MainFilename),
1471 NewPreamble.Buffer->getBufferStart(),
1472 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1473 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1475 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1476 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1478 // Remap the main source file to the preamble buffer.
1479 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1480 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1482 // Tell the compiler invocation to generate a temporary precompiled header.
1483 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1484 // FIXME: Generate the precompiled header into memory?
1485 FrontendOpts.OutputFile = PreamblePCHPath;
1486 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1487 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1489 // Create the compiler instance to use for building the precompiled preamble.
1490 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
1492 // Recover resources if we crash before exiting this method.
1493 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1494 CICleanup(Clang.get());
1496 Clang->setInvocation(&*PreambleInvocation);
1497 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1499 // Set up diagnostics, capturing all of the diagnostics produced.
1500 Clang->setDiagnostics(&getDiagnostics());
1502 // Create the target instance.
1503 Clang->setTarget(TargetInfo::CreateTargetInfo(
1504 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1505 if (!Clang->hasTarget()) {
1506 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1508 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1509 PreprocessorOpts.RemappedFileBuffers.pop_back();
1513 // Inform the target of the language options.
1515 // FIXME: We shouldn't need to do this, the target should be immutable once
1516 // created. This complexity should be lifted elsewhere.
1517 Clang->getTarget().adjust(Clang->getLangOpts());
1519 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1520 "Invocation must have exactly one source file!");
1521 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1522 "FIXME: AST inputs not yet supported here!");
1523 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1524 "IR inputs not support here!");
1526 // Clear out old caches and data.
1527 getDiagnostics().Reset();
1528 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1529 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1530 TopLevelDecls.clear();
1531 TopLevelDeclsInPreamble.clear();
1532 PreambleDiagnostics.clear();
1534 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1535 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1539 // Create a file manager object to provide access to and cache the filesystem.
1540 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1542 // Create the source manager.
1543 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1544 Clang->getFileManager()));
1546 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1547 Clang->addDependencyCollector(PreambleDepCollector);
1549 std::unique_ptr<PrecompilePreambleAction> Act;
1550 Act.reset(new PrecompilePreambleAction(*this));
1551 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1552 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1554 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1555 PreprocessorOpts.RemappedFileBuffers.pop_back();
1561 // Transfer any diagnostics generated when parsing the preamble into the set
1562 // of preamble diagnostics.
1563 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1564 E = stored_diag_end();
1566 PreambleDiagnostics.push_back(
1567 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1569 Act->EndSourceFile();
1571 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1573 if (!Act->hasEmittedPreamblePCH()) {
1574 // The preamble PCH failed (e.g. there was a module loading fatal error),
1575 // so no precompiled header was generated. Forget that we even tried.
1576 // FIXME: Should we leave a note for ourselves to try again?
1577 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1579 TopLevelDeclsInPreamble.clear();
1580 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1581 PreprocessorOpts.RemappedFileBuffers.pop_back();
1585 // Keep track of the preamble we precompiled.
1586 setPreambleFile(this, FrontendOpts.OutputFile);
1587 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1589 // Keep track of all of the files that the source manager knows about,
1590 // so we can verify whether they have changed or not.
1591 FilesInPreamble.clear();
1592 SourceManager &SourceMgr = Clang->getSourceManager();
1593 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1594 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1595 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1597 if (time_t ModTime = File->getModificationTime()) {
1598 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1599 File->getSize(), ModTime);
1601 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1602 FilesInPreamble[File->getName()] =
1603 PreambleFileHash::createForMemoryBuffer(Buffer);
1607 PreambleRebuildCounter = 1;
1608 PreprocessorOpts.RemappedFileBuffers.pop_back();
1610 // If the hash of top-level entities differs from the hash of the top-level
1611 // entities the last time we rebuilt the preamble, clear out the completion
1613 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1614 CompletionCacheTopLevelHashValue = 0;
1615 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1618 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1622 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1623 std::vector<Decl *> Resolved;
1624 Resolved.reserve(TopLevelDeclsInPreamble.size());
1625 ExternalASTSource &Source = *getASTContext().getExternalSource();
1626 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1627 // Resolve the declaration ID to an actual declaration, possibly
1628 // deserializing the declaration in the process.
1629 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1630 Resolved.push_back(D);
1632 TopLevelDeclsInPreamble.clear();
1633 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1636 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1637 // Steal the created target, context, and preprocessor if they have been
1639 assert(CI.hasInvocation() && "missing invocation");
1640 LangOpts = CI.getInvocation().LangOpts;
1641 TheSema = CI.takeSema();
1642 Consumer = CI.takeASTConsumer();
1643 if (CI.hasASTContext())
1644 Ctx = &CI.getASTContext();
1645 if (CI.hasPreprocessor())
1646 PP = &CI.getPreprocessor();
1647 CI.setSourceManager(nullptr);
1648 CI.setFileManager(nullptr);
1650 Target = &CI.getTarget();
1651 Reader = CI.getModuleManager();
1652 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1655 StringRef ASTUnit::getMainFileName() const {
1656 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1657 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1659 return Input.getFile();
1661 return Input.getBuffer()->getBufferIdentifier();
1665 if (const FileEntry *
1666 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1667 return FE->getName();
1673 StringRef ASTUnit::getASTFileName() const {
1674 if (!isMainFileAST())
1677 serialization::ModuleFile &
1678 Mod = Reader->getModuleManager().getPrimaryModule();
1679 return Mod.FileName;
1682 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1683 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1684 bool CaptureDiagnostics,
1685 bool UserFilesAreVolatile) {
1686 std::unique_ptr<ASTUnit> AST;
1687 AST.reset(new ASTUnit(false));
1688 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1689 AST->Diagnostics = Diags;
1690 AST->Invocation = CI;
1691 AST->FileSystemOpts = CI->getFileSystemOpts();
1692 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1693 createVFSFromCompilerInvocation(*CI, *Diags);
1696 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1697 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1698 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1699 UserFilesAreVolatile);
1701 return AST.release();
1704 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1705 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1706 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1707 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1708 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1709 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1710 std::unique_ptr<ASTUnit> *ErrAST) {
1711 assert(CI && "A CompilerInvocation is required");
1713 std::unique_ptr<ASTUnit> OwnAST;
1714 ASTUnit *AST = Unit;
1716 // Create the AST unit.
1717 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1723 if (!ResourceFilesPath.empty()) {
1724 // Override the resources path.
1725 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1727 AST->OnlyLocalDecls = OnlyLocalDecls;
1728 AST->CaptureDiagnostics = CaptureDiagnostics;
1729 if (PrecompilePreamble)
1730 AST->PreambleRebuildCounter = 2;
1731 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1732 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1733 AST->IncludeBriefCommentsInCodeCompletion
1734 = IncludeBriefCommentsInCodeCompletion;
1736 // Recover resources if we crash before exiting this method.
1737 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1738 ASTUnitCleanup(OwnAST.get());
1739 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1740 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1741 DiagCleanup(Diags.get());
1743 // We'll manage file buffers ourselves.
1744 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1745 CI->getFrontendOpts().DisableFree = false;
1746 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1748 // Create the compiler instance to use for building the AST.
1749 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
1751 // Recover resources if we crash before exiting this method.
1752 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1753 CICleanup(Clang.get());
1755 Clang->setInvocation(CI);
1756 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1758 // Set up diagnostics, capturing any diagnostics that would
1759 // otherwise be dropped.
1760 Clang->setDiagnostics(&AST->getDiagnostics());
1762 // Create the target instance.
1763 Clang->setTarget(TargetInfo::CreateTargetInfo(
1764 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1765 if (!Clang->hasTarget())
1768 // Inform the target of the language options.
1770 // FIXME: We shouldn't need to do this, the target should be immutable once
1771 // created. This complexity should be lifted elsewhere.
1772 Clang->getTarget().adjust(Clang->getLangOpts());
1774 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1775 "Invocation must have exactly one source file!");
1776 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1777 "FIXME: AST inputs not yet supported here!");
1778 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1779 "IR inputs not supported here!");
1781 // Configure the various subsystems.
1782 AST->TheSema.reset();
1785 AST->Reader = nullptr;
1787 // Create a file manager object to provide access to and cache the filesystem.
1788 Clang->setFileManager(&AST->getFileManager());
1790 // Create the source manager.
1791 Clang->setSourceManager(&AST->getSourceManager());
1793 ASTFrontendAction *Act = Action;
1795 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1797 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1798 Act = TrackerAct.get();
1801 // Recover resources if we crash before exiting this method.
1802 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1803 ActCleanup(TrackerAct.get());
1805 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1806 AST->transferASTDataFromCompilerInstance(*Clang);
1807 if (OwnAST && ErrAST)
1808 ErrAST->swap(OwnAST);
1813 if (Persistent && !TrackerAct) {
1814 Clang->getPreprocessor().addPPCallbacks(
1815 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1816 AST->getCurrentTopLevelHashValue()));
1817 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1818 if (Clang->hasASTConsumer())
1819 Consumers.push_back(Clang->takeASTConsumer());
1820 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1821 *AST, AST->getCurrentTopLevelHashValue()));
1822 Clang->setASTConsumer(
1823 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1825 if (!Act->Execute()) {
1826 AST->transferASTDataFromCompilerInstance(*Clang);
1827 if (OwnAST && ErrAST)
1828 ErrAST->swap(OwnAST);
1833 // Steal the created target, context, and preprocessor.
1834 AST->transferASTDataFromCompilerInstance(*Clang);
1836 Act->EndSourceFile();
1839 return OwnAST.release();
1844 bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1848 // We'll manage file buffers ourselves.
1849 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1850 Invocation->getFrontendOpts().DisableFree = false;
1851 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1853 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1854 if (PrecompilePreamble) {
1855 PreambleRebuildCounter = 2;
1856 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
1859 SimpleTimer ParsingTimer(WantTiming);
1860 ParsingTimer.setOutput("Parsing " + getMainFileName());
1862 // Recover resources if we crash before exiting this method.
1863 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1864 MemBufferCleanup(OverrideMainBuffer.get());
1866 return Parse(std::move(OverrideMainBuffer));
1869 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1870 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1871 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1872 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1873 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
1874 // Create the AST unit.
1875 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1876 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1877 AST->Diagnostics = Diags;
1878 AST->OnlyLocalDecls = OnlyLocalDecls;
1879 AST->CaptureDiagnostics = CaptureDiagnostics;
1880 AST->TUKind = TUKind;
1881 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1882 AST->IncludeBriefCommentsInCodeCompletion
1883 = IncludeBriefCommentsInCodeCompletion;
1884 AST->Invocation = CI;
1885 AST->FileSystemOpts = CI->getFileSystemOpts();
1886 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1887 createVFSFromCompilerInvocation(*CI, *Diags);
1890 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1891 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1893 // Recover resources if we crash before exiting this method.
1894 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1895 ASTUnitCleanup(AST.get());
1896 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1897 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1898 DiagCleanup(Diags.get());
1900 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1905 ASTUnit *ASTUnit::LoadFromCommandLine(
1906 const char **ArgBegin, const char **ArgEnd,
1907 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1908 bool OnlyLocalDecls, bool CaptureDiagnostics,
1909 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1910 bool PrecompilePreamble, TranslationUnitKind TUKind,
1911 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1912 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1913 bool UserFilesAreVolatile, bool ForSerialization,
1914 std::unique_ptr<ASTUnit> *ErrAST) {
1915 assert(Diags.get() && "no DiagnosticsEngine was provided");
1917 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1919 IntrusiveRefCntPtr<CompilerInvocation> CI;
1923 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1926 CI = clang::createInvocationFromCommandLine(
1927 llvm::makeArrayRef(ArgBegin, ArgEnd),
1933 // Override any files that need remapping
1934 for (const auto &RemappedFile : RemappedFiles) {
1935 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1936 RemappedFile.second);
1938 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1939 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1940 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1942 // Override the resources path.
1943 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1945 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1947 // Create the AST unit.
1948 std::unique_ptr<ASTUnit> AST;
1949 AST.reset(new ASTUnit(false));
1950 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1951 AST->Diagnostics = Diags;
1952 AST->FileSystemOpts = CI->getFileSystemOpts();
1953 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1954 createVFSFromCompilerInvocation(*CI, *Diags);
1957 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1958 AST->OnlyLocalDecls = OnlyLocalDecls;
1959 AST->CaptureDiagnostics = CaptureDiagnostics;
1960 AST->TUKind = TUKind;
1961 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1962 AST->IncludeBriefCommentsInCodeCompletion
1963 = IncludeBriefCommentsInCodeCompletion;
1964 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1965 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1966 AST->StoredDiagnostics.swap(StoredDiagnostics);
1967 AST->Invocation = CI;
1968 if (ForSerialization)
1969 AST->WriterData.reset(new ASTWriterData());
1970 // Zero out now to ease cleanup during crash recovery.
1974 // Recover resources if we crash before exiting this method.
1975 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1976 ASTUnitCleanup(AST.get());
1978 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1979 // Some error occurred, if caller wants to examine diagnostics, pass it the
1982 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1988 return AST.release();
1991 bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
1995 clearFileLevelDecls();
1997 SimpleTimer ParsingTimer(WantTiming);
1998 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2001 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2002 for (const auto &RB : PPOpts.RemappedFileBuffers)
2005 Invocation->getPreprocessorOpts().clearRemappedFiles();
2006 for (const auto &RemappedFile : RemappedFiles) {
2007 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2008 RemappedFile.second);
2011 // If we have a preamble file lying around, or if we might try to
2012 // build a precompiled preamble, do so now.
2013 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2014 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2015 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
2017 // Clear out the diagnostics state.
2018 getDiagnostics().Reset();
2019 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2020 if (OverrideMainBuffer)
2021 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2023 // Parse the sources
2024 bool Result = Parse(std::move(OverrideMainBuffer));
2026 // If we're caching global code-completion results, and the top-level
2027 // declarations have changed, clear out the code-completion cache.
2028 if (!Result && ShouldCacheCodeCompletionResults &&
2029 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2030 CacheCodeCompletionResults();
2032 // We now need to clear out the completion info related to this translation
2033 // unit; it'll be recreated if necessary.
2039 //----------------------------------------------------------------------------//
2041 //----------------------------------------------------------------------------//
2044 /// \brief Code completion consumer that combines the cached code-completion
2045 /// results from an ASTUnit with the code-completion results provided to it,
2046 /// then passes the result on to
2047 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2048 uint64_t NormalContexts;
2050 CodeCompleteConsumer &Next;
2053 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2054 const CodeCompleteOptions &CodeCompleteOpts)
2055 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2056 AST(AST), Next(Next)
2058 // Compute the set of contexts in which we will look when we don't have
2059 // any information about the specific context.
2061 = (1LL << CodeCompletionContext::CCC_TopLevel)
2062 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2063 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2064 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2065 | (1LL << CodeCompletionContext::CCC_Statement)
2066 | (1LL << CodeCompletionContext::CCC_Expression)
2067 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2068 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2069 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2070 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2071 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2072 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2073 | (1LL << CodeCompletionContext::CCC_Recovery);
2075 if (AST.getASTContext().getLangOpts().CPlusPlus)
2076 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2077 | (1LL << CodeCompletionContext::CCC_UnionTag)
2078 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2081 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2082 CodeCompletionResult *Results,
2083 unsigned NumResults) override;
2085 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2086 OverloadCandidate *Candidates,
2087 unsigned NumCandidates) override {
2088 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2091 CodeCompletionAllocator &getAllocator() override {
2092 return Next.getAllocator();
2095 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2096 return Next.getCodeCompletionTUInfo();
2101 /// \brief Helper function that computes which global names are hidden by the
2102 /// local code-completion results.
2103 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2104 CodeCompletionResult *Results,
2105 unsigned NumResults,
2107 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2108 bool OnlyTagNames = false;
2109 switch (Context.getKind()) {
2110 case CodeCompletionContext::CCC_Recovery:
2111 case CodeCompletionContext::CCC_TopLevel:
2112 case CodeCompletionContext::CCC_ObjCInterface:
2113 case CodeCompletionContext::CCC_ObjCImplementation:
2114 case CodeCompletionContext::CCC_ObjCIvarList:
2115 case CodeCompletionContext::CCC_ClassStructUnion:
2116 case CodeCompletionContext::CCC_Statement:
2117 case CodeCompletionContext::CCC_Expression:
2118 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2119 case CodeCompletionContext::CCC_DotMemberAccess:
2120 case CodeCompletionContext::CCC_ArrowMemberAccess:
2121 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2122 case CodeCompletionContext::CCC_Namespace:
2123 case CodeCompletionContext::CCC_Type:
2124 case CodeCompletionContext::CCC_Name:
2125 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2126 case CodeCompletionContext::CCC_ParenthesizedExpression:
2127 case CodeCompletionContext::CCC_ObjCInterfaceName:
2130 case CodeCompletionContext::CCC_EnumTag:
2131 case CodeCompletionContext::CCC_UnionTag:
2132 case CodeCompletionContext::CCC_ClassOrStructTag:
2133 OnlyTagNames = true;
2136 case CodeCompletionContext::CCC_ObjCProtocolName:
2137 case CodeCompletionContext::CCC_MacroName:
2138 case CodeCompletionContext::CCC_MacroNameUse:
2139 case CodeCompletionContext::CCC_PreprocessorExpression:
2140 case CodeCompletionContext::CCC_PreprocessorDirective:
2141 case CodeCompletionContext::CCC_NaturalLanguage:
2142 case CodeCompletionContext::CCC_SelectorName:
2143 case CodeCompletionContext::CCC_TypeQualifiers:
2144 case CodeCompletionContext::CCC_Other:
2145 case CodeCompletionContext::CCC_OtherWithMacros:
2146 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2147 case CodeCompletionContext::CCC_ObjCClassMessage:
2148 case CodeCompletionContext::CCC_ObjCCategoryName:
2149 // We're looking for nothing, or we're looking for names that cannot
2154 typedef CodeCompletionResult Result;
2155 for (unsigned I = 0; I != NumResults; ++I) {
2156 if (Results[I].Kind != Result::RK_Declaration)
2160 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2162 bool Hiding = false;
2164 Hiding = (IDNS & Decl::IDNS_Tag);
2166 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2167 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2168 Decl::IDNS_NonMemberOperator);
2169 if (Ctx.getLangOpts().CPlusPlus)
2170 HiddenIDNS |= Decl::IDNS_Tag;
2171 Hiding = (IDNS & HiddenIDNS);
2177 DeclarationName Name = Results[I].Declaration->getDeclName();
2178 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2179 HiddenNames.insert(Identifier->getName());
2181 HiddenNames.insert(Name.getAsString());
2186 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2187 CodeCompletionContext Context,
2188 CodeCompletionResult *Results,
2189 unsigned NumResults) {
2190 // Merge the results we were given with the results we cached.
2191 bool AddedResult = false;
2192 uint64_t InContexts =
2193 Context.getKind() == CodeCompletionContext::CCC_Recovery
2194 ? NormalContexts : (1LL << Context.getKind());
2195 // Contains the set of names that are hidden by "local" completion results.
2196 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2197 typedef CodeCompletionResult Result;
2198 SmallVector<Result, 8> AllResults;
2199 for (ASTUnit::cached_completion_iterator
2200 C = AST.cached_completion_begin(),
2201 CEnd = AST.cached_completion_end();
2203 // If the context we are in matches any of the contexts we are
2204 // interested in, we'll add this result.
2205 if ((C->ShowInContexts & InContexts) == 0)
2208 // If we haven't added any results previously, do so now.
2210 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2212 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2216 // Determine whether this global completion result is hidden by a local
2217 // completion result. If so, skip it.
2218 if (C->Kind != CXCursor_MacroDefinition &&
2219 HiddenNames.count(C->Completion->getTypedText()))
2222 // Adjust priority based on similar type classes.
2223 unsigned Priority = C->Priority;
2224 CodeCompletionString *Completion = C->Completion;
2225 if (!Context.getPreferredType().isNull()) {
2226 if (C->Kind == CXCursor_MacroDefinition) {
2227 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2229 Context.getPreferredType()->isAnyPointerType());
2230 } else if (C->Type) {
2231 CanQualType Expected
2232 = S.Context.getCanonicalType(
2233 Context.getPreferredType().getUnqualifiedType());
2234 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2235 if (ExpectedSTC == C->TypeClass) {
2236 // We know this type is similar; check for an exact match.
2237 llvm::StringMap<unsigned> &CachedCompletionTypes
2238 = AST.getCachedCompletionTypes();
2239 llvm::StringMap<unsigned>::iterator Pos
2240 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2241 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2242 Priority /= CCF_ExactTypeMatch;
2244 Priority /= CCF_SimilarTypeMatch;
2249 // Adjust the completion string, if required.
2250 if (C->Kind == CXCursor_MacroDefinition &&
2251 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2252 // Create a new code-completion string that just contains the
2253 // macro name, without its arguments.
2254 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2255 CCP_CodePattern, C->Availability);
2256 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2257 Priority = CCP_CodePattern;
2258 Completion = Builder.TakeString();
2261 AllResults.push_back(Result(Completion, Priority, C->Kind,
2265 // If we did not add any cached completion results, just forward the
2266 // results we were given to the next consumer.
2268 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2272 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2278 void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2279 ArrayRef<RemappedFile> RemappedFiles,
2281 bool IncludeCodePatterns,
2282 bool IncludeBriefComments,
2283 CodeCompleteConsumer &Consumer,
2284 DiagnosticsEngine &Diag, LangOptions &LangOpts,
2285 SourceManager &SourceMgr, FileManager &FileMgr,
2286 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2287 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2291 SimpleTimer CompletionTimer(WantTiming);
2292 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2293 Twine(Line) + ":" + Twine(Column));
2295 IntrusiveRefCntPtr<CompilerInvocation>
2296 CCInvocation(new CompilerInvocation(*Invocation));
2298 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2299 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2300 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2302 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2303 CachedCompletionResults.empty();
2304 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2305 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2306 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2308 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2310 FrontendOpts.CodeCompletionAt.FileName = File;
2311 FrontendOpts.CodeCompletionAt.Line = Line;
2312 FrontendOpts.CodeCompletionAt.Column = Column;
2314 // Set the language options appropriately.
2315 LangOpts = *CCInvocation->getLangOpts();
2317 // Spell-checking and warnings are wasteful during code-completion.
2318 LangOpts.SpellChecking = false;
2319 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2321 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
2323 // Recover resources if we crash before exiting this method.
2324 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2325 CICleanup(Clang.get());
2327 Clang->setInvocation(&*CCInvocation);
2328 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2330 // Set up diagnostics, capturing any diagnostics produced.
2331 Clang->setDiagnostics(&Diag);
2332 CaptureDroppedDiagnostics Capture(true,
2333 Clang->getDiagnostics(),
2335 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2337 // Create the target instance.
2338 Clang->setTarget(TargetInfo::CreateTargetInfo(
2339 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2340 if (!Clang->hasTarget()) {
2341 Clang->setInvocation(nullptr);
2345 // Inform the target of the language options.
2347 // FIXME: We shouldn't need to do this, the target should be immutable once
2348 // created. This complexity should be lifted elsewhere.
2349 Clang->getTarget().adjust(Clang->getLangOpts());
2351 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2352 "Invocation must have exactly one source file!");
2353 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2354 "FIXME: AST inputs not yet supported here!");
2355 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2356 "IR inputs not support here!");
2359 // Use the source and file managers that we were given.
2360 Clang->setFileManager(&FileMgr);
2361 Clang->setSourceManager(&SourceMgr);
2364 PreprocessorOpts.clearRemappedFiles();
2365 PreprocessorOpts.RetainRemappedFileBuffers = true;
2366 for (const auto &RemappedFile : RemappedFiles) {
2367 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2368 OwnedBuffers.push_back(RemappedFile.second);
2371 // Use the code completion consumer we were given, but adding any cached
2372 // code-completion results.
2373 AugmentedCodeCompleteConsumer *AugmentedConsumer
2374 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2375 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2377 // If we have a precompiled preamble, try to use it. We only allow
2378 // the use of the precompiled preamble if we're if the completion
2379 // point is within the main file, after the end of the precompiled
2381 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2382 if (!getPreambleFile(this).empty()) {
2383 std::string CompleteFilePath(File);
2384 llvm::sys::fs::UniqueID CompleteFileID;
2386 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2387 std::string MainPath(OriginalSourceFile);
2388 llvm::sys::fs::UniqueID MainID;
2389 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2390 if (CompleteFileID == MainID && Line > 1)
2391 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2392 *CCInvocation, false, Line - 1);
2397 // If the main file has been overridden due to the use of a preamble,
2398 // make that override happen and introduce the preamble.
2399 if (OverrideMainBuffer) {
2400 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2401 OverrideMainBuffer.get());
2402 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2403 PreprocessorOpts.PrecompiledPreambleBytes.second
2404 = PreambleEndsAtStartOfLine;
2405 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2406 PreprocessorOpts.DisablePCHValidation = true;
2408 OwnedBuffers.push_back(OverrideMainBuffer.release());
2410 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2411 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2414 // Disable the preprocessing record if modules are not enabled.
2415 if (!Clang->getLangOpts().Modules)
2416 PreprocessorOpts.DetailedRecord = false;
2418 std::unique_ptr<SyntaxOnlyAction> Act;
2419 Act.reset(new SyntaxOnlyAction);
2420 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2422 Act->EndSourceFile();
2426 bool ASTUnit::Save(StringRef File) {
2427 if (HadModuleLoaderFatalFailure)
2430 // Write to a temporary file and later rename it to the actual file, to avoid
2431 // possible race conditions.
2432 SmallString<128> TempPath;
2434 TempPath += "-%%%%%%%%";
2436 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2439 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2440 // unconditionally create a stat cache when we parse the file?
2441 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2445 if (Out.has_error()) {
2450 if (llvm::sys::fs::rename(TempPath, File)) {
2451 llvm::sys::fs::remove(TempPath);
2458 static bool serializeUnit(ASTWriter &Writer,
2459 SmallVectorImpl<char> &Buffer,
2463 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2465 // Write the generated bitstream to "Out".
2466 if (!Buffer.empty())
2467 OS.write(Buffer.data(), Buffer.size());
2472 bool ASTUnit::serialize(raw_ostream &OS) {
2473 bool hasErrors = getDiagnostics().hasErrorOccurred();
2476 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2477 getSema(), hasErrors, OS);
2479 SmallString<128> Buffer;
2480 llvm::BitstreamWriter Stream(Buffer);
2481 ASTWriter Writer(Stream);
2482 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2485 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2487 void ASTUnit::TranslateStoredDiagnostics(
2488 FileManager &FileMgr,
2489 SourceManager &SrcMgr,
2490 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2491 SmallVectorImpl<StoredDiagnostic> &Out) {
2492 // Map the standalone diagnostic into the new source manager. We also need to
2493 // remap all the locations to the new view. This includes the diag location,
2494 // any associated source ranges, and the source ranges of associated fix-its.
2495 // FIXME: There should be a cleaner way to do this.
2497 SmallVector<StoredDiagnostic, 4> Result;
2498 Result.reserve(Diags.size());
2499 for (const StandaloneDiagnostic &SD : Diags) {
2500 // Rebuild the StoredDiagnostic.
2501 if (SD.Filename.empty())
2503 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2506 FileID FID = SrcMgr.translateFile(FE);
2507 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2508 if (FileLoc.isInvalid())
2510 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2511 FullSourceLoc Loc(L, SrcMgr);
2513 SmallVector<CharSourceRange, 4> Ranges;
2514 Ranges.reserve(SD.Ranges.size());
2515 for (const auto &Range : SD.Ranges) {
2516 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2517 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2518 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2521 SmallVector<FixItHint, 2> FixIts;
2522 FixIts.reserve(SD.FixIts.size());
2523 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2524 FixIts.push_back(FixItHint());
2525 FixItHint &FH = FixIts.back();
2526 FH.CodeToInsert = FixIt.CodeToInsert;
2527 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2528 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2529 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2532 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2533 SD.Message, Loc, Ranges, FixIts));
2538 void ASTUnit::addFileLevelDecl(Decl *D) {
2541 // We only care about local declarations.
2542 if (D->isFromASTFile())
2545 SourceManager &SM = *SourceMgr;
2546 SourceLocation Loc = D->getLocation();
2547 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2550 // We only keep track of the file-level declarations of each file.
2551 if (!D->getLexicalDeclContext()->isFileContext())
2554 SourceLocation FileLoc = SM.getFileLoc(Loc);
2555 assert(SM.isLocalSourceLocation(FileLoc));
2558 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2559 if (FID.isInvalid())
2562 LocDeclsTy *&Decls = FileDecls[FID];
2564 Decls = new LocDeclsTy();
2566 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2568 if (Decls->empty() || Decls->back().first <= Offset) {
2569 Decls->push_back(LocDecl);
2573 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2574 LocDecl, llvm::less_first());
2576 Decls->insert(I, LocDecl);
2579 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2580 SmallVectorImpl<Decl *> &Decls) {
2581 if (File.isInvalid())
2584 if (SourceMgr->isLoadedFileID(File)) {
2585 assert(Ctx->getExternalSource() && "No external source!");
2586 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2590 FileDeclsTy::iterator I = FileDecls.find(File);
2591 if (I == FileDecls.end())
2594 LocDeclsTy &LocDecls = *I->second;
2595 if (LocDecls.empty())
2598 LocDeclsTy::iterator BeginIt =
2599 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2600 std::make_pair(Offset, (Decl *)nullptr),
2601 llvm::less_first());
2602 if (BeginIt != LocDecls.begin())
2605 // If we are pointing at a top-level decl inside an objc container, we need
2606 // to backtrack until we find it otherwise we will fail to report that the
2607 // region overlaps with an objc container.
2608 while (BeginIt != LocDecls.begin() &&
2609 BeginIt->second->isTopLevelDeclInObjCContainer())
2612 LocDeclsTy::iterator EndIt = std::upper_bound(
2613 LocDecls.begin(), LocDecls.end(),
2614 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2615 if (EndIt != LocDecls.end())
2618 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2619 Decls.push_back(DIt->second);
2622 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2623 unsigned Line, unsigned Col) const {
2624 const SourceManager &SM = getSourceManager();
2625 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2626 return SM.getMacroArgExpandedLocation(Loc);
2629 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2630 unsigned Offset) const {
2631 const SourceManager &SM = getSourceManager();
2632 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2633 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2636 /// \brief If \arg Loc is a loaded location from the preamble, returns
2637 /// the corresponding local location of the main file, otherwise it returns
2639 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2642 PreambleID = SourceMgr->getPreambleFileID();
2644 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2648 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2649 SourceLocation FileLoc
2650 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2651 return FileLoc.getLocWithOffset(Offs);
2657 /// \brief If \arg Loc is a local location of the main file but inside the
2658 /// preamble chunk, returns the corresponding loaded location from the
2659 /// preamble, otherwise it returns \arg Loc.
2660 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2663 PreambleID = SourceMgr->getPreambleFileID();
2665 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2669 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2670 Offs < Preamble.size()) {
2671 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2672 return FileLoc.getLocWithOffset(Offs);
2678 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2681 FID = SourceMgr->getPreambleFileID();
2683 if (Loc.isInvalid() || FID.isInvalid())
2686 return SourceMgr->isInFileID(Loc, FID);
2689 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2692 FID = SourceMgr->getMainFileID();
2694 if (Loc.isInvalid() || FID.isInvalid())
2697 return SourceMgr->isInFileID(Loc, FID);
2700 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2703 FID = SourceMgr->getPreambleFileID();
2705 if (FID.isInvalid())
2706 return SourceLocation();
2708 return SourceMgr->getLocForEndOfFile(FID);
2711 SourceLocation ASTUnit::getStartOfMainFileID() {
2714 FID = SourceMgr->getMainFileID();
2716 if (FID.isInvalid())
2717 return SourceLocation();
2719 return SourceMgr->getLocForStartOfFile(FID);
2722 llvm::iterator_range<PreprocessingRecord::iterator>
2723 ASTUnit::getLocalPreprocessingEntities() const {
2724 if (isMainFileAST()) {
2725 serialization::ModuleFile &
2726 Mod = Reader->getModuleManager().getPrimaryModule();
2727 return Reader->getModulePreprocessedEntities(Mod);
2730 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2731 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2733 return llvm::make_range(PreprocessingRecord::iterator(),
2734 PreprocessingRecord::iterator());
2737 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2738 if (isMainFileAST()) {
2739 serialization::ModuleFile &
2740 Mod = Reader->getModuleManager().getPrimaryModule();
2741 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2742 if (!Fn(context, D))
2749 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2750 TLEnd = top_level_end();
2751 TL != TLEnd; ++TL) {
2752 if (!Fn(context, *TL))
2760 struct PCHLocatorInfo {
2761 serialization::ModuleFile *Mod;
2762 PCHLocatorInfo() : Mod(nullptr) {}
2766 static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2767 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2769 case serialization::MK_ImplicitModule:
2770 case serialization::MK_ExplicitModule:
2771 return true; // skip dependencies.
2772 case serialization::MK_PCH:
2774 return true; // found it.
2775 case serialization::MK_Preamble:
2776 return false; // look in dependencies.
2777 case serialization::MK_MainFile:
2778 return false; // look in dependencies.
2784 const FileEntry *ASTUnit::getPCHFile() {
2788 PCHLocatorInfo Info;
2789 Reader->getModuleManager().visit(PCHLocator, &Info);
2791 return Info.Mod->File;
2796 bool ASTUnit::isModuleFile() {
2797 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2800 void ASTUnit::PreambleData::countLines() const {
2805 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2807 if (Buffer.back() != '\n')
2812 ASTUnit::ConcurrencyState::ConcurrencyState() {
2813 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2816 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2817 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2820 void ASTUnit::ConcurrencyState::start() {
2821 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2822 assert(acquired && "Concurrent access to ASTUnit!");
2825 void ASTUnit::ConcurrencyState::finish() {
2826 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2831 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
2832 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2833 void ASTUnit::ConcurrencyState::start() {}
2834 void ASTUnit::ConcurrencyState::finish() {}