1 //===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
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/Timer.h"
45 #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 && 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(std::shared_ptr<Preprocessor> PP) {
261 this->PP = std::move(PP);
264 /// \brief Determine the set of code-completion contexts in which this
265 /// declaration should be shown.
266 static unsigned getDeclShowContexts(const NamedDecl *ND,
267 const LangOptions &LangOpts,
268 bool &IsNestedNameSpecifier) {
269 IsNestedNameSpecifier = false;
271 if (isa<UsingShadowDecl>(ND))
272 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
276 uint64_t Contexts = 0;
277 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
278 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
279 // Types can appear in these contexts.
280 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
281 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
282 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
283 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
284 | (1LL << CodeCompletionContext::CCC_Statement)
285 | (1LL << CodeCompletionContext::CCC_Type)
286 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
288 // In C++, types can appear in expressions contexts (for functional casts).
289 if (LangOpts.CPlusPlus)
290 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
292 // In Objective-C, message sends can send interfaces. In Objective-C++,
293 // all types are available due to functional casts.
294 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
295 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
297 // In Objective-C, you can only be a subclass of another Objective-C class
298 if (isa<ObjCInterfaceDecl>(ND))
299 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
301 // Deal with tag names.
302 if (isa<EnumDecl>(ND)) {
303 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
305 // Part of the nested-name-specifier in C++0x.
306 if (LangOpts.CPlusPlus11)
307 IsNestedNameSpecifier = true;
308 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
309 if (Record->isUnion())
310 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
312 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
314 if (LangOpts.CPlusPlus)
315 IsNestedNameSpecifier = true;
316 } else if (isa<ClassTemplateDecl>(ND))
317 IsNestedNameSpecifier = true;
318 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
319 // Values can appear in these contexts.
320 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
321 | (1LL << CodeCompletionContext::CCC_Expression)
322 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
323 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
324 } else if (isa<ObjCProtocolDecl>(ND)) {
325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
326 } else if (isa<ObjCCategoryDecl>(ND)) {
327 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
328 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
329 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
331 // Part of the nested-name-specifier.
332 IsNestedNameSpecifier = true;
338 void ASTUnit::CacheCodeCompletionResults() {
342 SimpleTimer Timer(WantTiming);
343 Timer.setOutput("Cache global code completions for " + getMainFileName());
345 // Clear out the previous results.
346 ClearCachedCompletionResults();
348 // Gather the set of global code completions.
349 typedef CodeCompletionResult Result;
350 SmallVector<Result, 8> Results;
351 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
352 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
353 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
356 // Translate global code completions into cached completions.
357 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
358 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
360 for (Result &R : Results) {
362 case Result::RK_Declaration: {
363 bool IsNestedNameSpecifier = false;
364 CachedCodeCompletionResult CachedResult;
365 CachedResult.Completion = R.CreateCodeCompletionString(
366 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
367 IncludeBriefCommentsInCodeCompletion);
368 CachedResult.ShowInContexts = getDeclShowContexts(
369 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
370 CachedResult.Priority = R.Priority;
371 CachedResult.Kind = R.CursorKind;
372 CachedResult.Availability = R.Availability;
374 // Keep track of the type of this completion in an ASTContext-agnostic
376 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
377 if (UsageType.isNull()) {
378 CachedResult.TypeClass = STC_Void;
379 CachedResult.Type = 0;
381 CanQualType CanUsageType
382 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
383 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
385 // Determine whether we have already seen this type. If so, we save
386 // ourselves the work of formatting the type string by using the
387 // temporary, CanQualType-based hash table to find the associated value.
388 unsigned &TypeValue = CompletionTypes[CanUsageType];
389 if (TypeValue == 0) {
390 TypeValue = CompletionTypes.size();
391 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
395 CachedResult.Type = TypeValue;
398 CachedCompletionResults.push_back(CachedResult);
400 /// Handle nested-name-specifiers in C++.
401 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
402 !R.StartsNestedNameSpecifier) {
403 // The contexts in which a nested-name-specifier can appear in C++.
405 = (1LL << CodeCompletionContext::CCC_TopLevel)
406 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
407 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
408 | (1LL << CodeCompletionContext::CCC_Statement)
409 | (1LL << CodeCompletionContext::CCC_Expression)
410 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
411 | (1LL << CodeCompletionContext::CCC_EnumTag)
412 | (1LL << CodeCompletionContext::CCC_UnionTag)
413 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
414 | (1LL << CodeCompletionContext::CCC_Type)
415 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
416 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
418 if (isa<NamespaceDecl>(R.Declaration) ||
419 isa<NamespaceAliasDecl>(R.Declaration))
420 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
422 if (unsigned RemainingContexts
423 = NNSContexts & ~CachedResult.ShowInContexts) {
424 // If there any contexts where this completion can be a
425 // nested-name-specifier but isn't already an option, create a
426 // nested-name-specifier completion.
427 R.StartsNestedNameSpecifier = true;
428 CachedResult.Completion = R.CreateCodeCompletionString(
429 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
430 IncludeBriefCommentsInCodeCompletion);
431 CachedResult.ShowInContexts = RemainingContexts;
432 CachedResult.Priority = CCP_NestedNameSpecifier;
433 CachedResult.TypeClass = STC_Void;
434 CachedResult.Type = 0;
435 CachedCompletionResults.push_back(CachedResult);
441 case Result::RK_Keyword:
442 case Result::RK_Pattern:
443 // Ignore keywords and patterns; we don't care, since they are so
444 // easily regenerated.
447 case Result::RK_Macro: {
448 CachedCodeCompletionResult CachedResult;
449 CachedResult.Completion = R.CreateCodeCompletionString(
450 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
451 IncludeBriefCommentsInCodeCompletion);
452 CachedResult.ShowInContexts
453 = (1LL << CodeCompletionContext::CCC_TopLevel)
454 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
455 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
456 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
457 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
458 | (1LL << CodeCompletionContext::CCC_Statement)
459 | (1LL << CodeCompletionContext::CCC_Expression)
460 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
461 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
462 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
463 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
464 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
466 CachedResult.Priority = R.Priority;
467 CachedResult.Kind = R.CursorKind;
468 CachedResult.Availability = R.Availability;
469 CachedResult.TypeClass = STC_Void;
470 CachedResult.Type = 0;
471 CachedCompletionResults.push_back(CachedResult);
477 // Save the current top-level hash value.
478 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
481 void ASTUnit::ClearCachedCompletionResults() {
482 CachedCompletionResults.clear();
483 CachedCompletionTypes.clear();
484 CachedCompletionAllocator = nullptr;
489 /// \brief Gathers information from ASTReader that will be used to initialize
491 class ASTInfoCollector : public ASTReaderListener {
494 LangOptions &LangOpt;
495 std::shared_ptr<TargetOptions> &TargetOpts;
496 IntrusiveRefCntPtr<TargetInfo> &Target;
499 bool InitializedLanguage;
501 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
502 std::shared_ptr<TargetOptions> &TargetOpts,
503 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
504 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
505 Target(Target), Counter(Counter), InitializedLanguage(false) {}
507 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
508 bool AllowCompatibleDifferences) override {
509 if (InitializedLanguage)
513 InitializedLanguage = true;
519 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
520 bool AllowCompatibleDifferences) override {
521 // If we've already initialized the target, don't do it again.
525 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
527 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
533 void ReadCounter(const serialization::ModuleFile &M,
534 unsigned Value) override {
540 if (!Target || !InitializedLanguage)
543 // Inform the target of the language options.
545 // FIXME: We shouldn't need to do this, the target should be immutable once
546 // created. This complexity should be lifted elsewhere.
547 Target->adjust(LangOpt);
549 // Initialize the preprocessor.
550 PP.Initialize(*Target);
552 // Initialize the ASTContext
553 Context.InitBuiltinTypes(*Target);
555 // We didn't have access to the comment options when the ASTContext was
556 // constructed, so register them now.
557 Context.getCommentCommandTraits().registerCommentOptions(
558 LangOpt.CommentOpts);
562 /// \brief Diagnostic consumer that saves each diagnostic it is given.
563 class StoredDiagnosticConsumer : public DiagnosticConsumer {
564 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
565 SourceManager *SourceMgr;
568 explicit StoredDiagnosticConsumer(
569 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
570 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
572 void BeginSourceFile(const LangOptions &LangOpts,
573 const Preprocessor *PP = nullptr) override {
575 SourceMgr = &PP->getSourceManager();
578 void HandleDiagnostic(DiagnosticsEngine::Level Level,
579 const Diagnostic &Info) override;
582 /// \brief RAII object that optionally captures diagnostics, if
583 /// there is no diagnostic client to capture them already.
584 class CaptureDroppedDiagnostics {
585 DiagnosticsEngine &Diags;
586 StoredDiagnosticConsumer Client;
587 DiagnosticConsumer *PreviousClient;
588 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
591 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
592 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
593 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
595 if (RequestCapture || Diags.getClient() == nullptr) {
596 OwningPreviousClient = Diags.takeClient();
597 PreviousClient = Diags.getClient();
598 Diags.setClient(&Client, false);
602 ~CaptureDroppedDiagnostics() {
603 if (Diags.getClient() == &Client)
604 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
608 } // anonymous namespace
610 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
611 const Diagnostic &Info) {
612 // Default implementation (Warnings/errors count).
613 DiagnosticConsumer::HandleDiagnostic(Level, Info);
615 // Only record the diagnostic if it's part of the source manager we know
616 // about. This effectively drops diagnostics from modules we're building.
617 // FIXME: In the long run, ee don't want to drop source managers from modules.
618 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
619 StoredDiags.emplace_back(Level, Info);
622 ASTMutationListener *ASTUnit::getASTMutationListener() {
624 return &WriterData->Writer;
628 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
630 return &WriterData->Writer;
634 std::unique_ptr<llvm::MemoryBuffer>
635 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
637 auto Buffer = FileMgr->getBufferForFile(Filename);
639 return std::move(*Buffer);
641 *ErrorStr = Buffer.getError().message();
645 /// \brief Configure the diagnostics object for use with ASTUnit.
646 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
647 ASTUnit &AST, bool CaptureDiagnostics) {
648 assert(Diags.get() && "no DiagnosticsEngine was provided");
649 if (CaptureDiagnostics)
650 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
653 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
654 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
655 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
656 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
657 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
658 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
659 bool UserFilesAreVolatile) {
660 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
662 // Recover resources if we crash before exiting this method.
663 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
664 ASTUnitCleanup(AST.get());
665 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
666 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
667 DiagCleanup(Diags.get());
669 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
671 AST->OnlyLocalDecls = OnlyLocalDecls;
672 AST->CaptureDiagnostics = CaptureDiagnostics;
673 AST->Diagnostics = Diags;
674 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
675 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
676 AST->UserFilesAreVolatile = UserFilesAreVolatile;
677 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
678 AST->getFileManager(),
679 UserFilesAreVolatile);
680 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
681 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
682 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
683 AST->getSourceManager(),
684 AST->getDiagnostics(),
685 AST->ASTFileLangOpts,
686 /*Target=*/nullptr));
688 auto PPOpts = std::make_shared<PreprocessorOptions>();
690 for (const auto &RemappedFile : RemappedFiles)
691 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
693 // Gather Info for preprocessor construction later on.
695 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
698 AST->PP = std::make_shared<Preprocessor>(
699 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
700 AST->getSourceManager(), HeaderInfo, *AST,
701 /*IILookup=*/nullptr,
702 /*OwnsHeaderSearch=*/false);
703 Preprocessor &PP = *AST->PP;
705 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
706 PP.getIdentifierTable(), PP.getSelectorTable(),
707 PP.getBuiltinInfo());
708 ASTContext &Context = *AST->Ctx;
710 bool disableValid = false;
711 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
713 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
715 /*DisableValidation=*/disableValid,
716 AllowPCHWithCompilerErrors);
718 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
719 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
722 // Attach the AST reader to the AST context as an external AST
723 // source, so that declarations will be deserialized from the
724 // AST file as needed.
725 // We need the external source to be set up before we read the AST, because
726 // eagerly-deserialized declarations may use it.
727 Context.setExternalSource(AST->Reader);
729 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
730 SourceLocation(), ASTReader::ARR_None)) {
731 case ASTReader::Success:
734 case ASTReader::Failure:
735 case ASTReader::Missing:
736 case ASTReader::OutOfDate:
737 case ASTReader::VersionMismatch:
738 case ASTReader::ConfigurationMismatch:
739 case ASTReader::HadErrors:
740 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
744 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
746 PP.setCounterValue(Counter);
748 // Create an AST consumer, even though it isn't used.
749 AST->Consumer.reset(new ASTConsumer);
751 // Create a semantic analysis object and tell the AST reader about it.
752 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
753 AST->TheSema->Initialize();
754 AST->Reader->InitializeSema(*AST->TheSema);
756 // Tell the diagnostic client that we have started a source file.
757 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
764 /// \brief Preprocessor callback class that updates a hash value with the names
765 /// of all macros that have been defined by the translation unit.
766 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
770 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
772 void MacroDefined(const Token &MacroNameTok,
773 const MacroDirective *MD) override {
774 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
778 /// \brief Add the given declaration to the hash of all top-level entities.
779 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
783 DeclContext *DC = D->getDeclContext();
787 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
790 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
791 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
792 // For an unscoped enum include the enumerators in the hash since they
793 // enter the top-level namespace.
794 if (!EnumD->isScoped()) {
795 for (const auto *EI : EnumD->enumerators()) {
796 if (EI->getIdentifier())
797 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
802 if (ND->getIdentifier())
803 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
804 else if (DeclarationName Name = ND->getDeclName()) {
805 std::string NameStr = Name.getAsString();
806 Hash = llvm::HashString(NameStr, Hash);
811 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
812 if (Module *Mod = ImportD->getImportedModule()) {
813 std::string ModName = Mod->getFullModuleName();
814 Hash = llvm::HashString(ModName, Hash);
820 class TopLevelDeclTrackerConsumer : public ASTConsumer {
825 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
826 : Unit(_Unit), Hash(Hash) {
830 void handleTopLevelDecl(Decl *D) {
834 // FIXME: Currently ObjC method declarations are incorrectly being
835 // reported as top-level declarations, even though their DeclContext
836 // is the containing ObjC @interface/@implementation. This is a
837 // fundamental problem in the parser right now.
838 if (isa<ObjCMethodDecl>(D))
841 AddTopLevelDeclarationToHash(D, Hash);
842 Unit.addTopLevelDecl(D);
844 handleFileLevelDecl(D);
847 void handleFileLevelDecl(Decl *D) {
848 Unit.addFileLevelDecl(D);
849 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
850 for (auto *I : NSD->decls())
851 handleFileLevelDecl(I);
855 bool HandleTopLevelDecl(DeclGroupRef D) override {
856 for (Decl *TopLevelDecl : D)
857 handleTopLevelDecl(TopLevelDecl);
861 // We're not interested in "interesting" decls.
862 void HandleInterestingDecl(DeclGroupRef) override {}
864 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
865 for (Decl *TopLevelDecl : D)
866 handleTopLevelDecl(TopLevelDecl);
869 ASTMutationListener *GetASTMutationListener() override {
870 return Unit.getASTMutationListener();
873 ASTDeserializationListener *GetASTDeserializationListener() override {
874 return Unit.getDeserializationListener();
878 class TopLevelDeclTrackerAction : public ASTFrontendAction {
882 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
883 StringRef InFile) override {
884 CI.getPreprocessor().addPPCallbacks(
885 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
886 Unit.getCurrentTopLevelHashValue()));
887 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
888 Unit, Unit.getCurrentTopLevelHashValue());
892 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
894 bool hasCodeCompletionSupport() const override { return false; }
895 TranslationUnitKind getTranslationUnitKind() override {
896 return Unit.getTranslationUnitKind();
900 class PrecompilePreambleAction : public ASTFrontendAction {
902 bool HasEmittedPreamblePCH;
905 explicit PrecompilePreambleAction(ASTUnit &Unit)
906 : Unit(Unit), HasEmittedPreamblePCH(false) {}
908 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
909 StringRef InFile) override;
910 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
911 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
912 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
914 bool hasCodeCompletionSupport() const override { return false; }
915 bool hasASTFileSupport() const override { return false; }
916 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
919 class PrecompilePreambleConsumer : public PCHGenerator {
922 std::vector<Decl *> TopLevelDecls;
923 PrecompilePreambleAction *Action;
924 std::unique_ptr<raw_ostream> Out;
927 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
928 const Preprocessor &PP, StringRef isysroot,
929 std::unique_ptr<raw_ostream> Out)
930 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
931 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
932 /*AllowASTWithErrors=*/true),
933 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
934 Out(std::move(Out)) {
938 bool HandleTopLevelDecl(DeclGroupRef DG) override {
940 // FIXME: Currently ObjC method declarations are incorrectly being
941 // reported as top-level declarations, even though their DeclContext
942 // is the containing ObjC @interface/@implementation. This is a
943 // fundamental problem in the parser right now.
944 if (isa<ObjCMethodDecl>(D))
946 AddTopLevelDeclarationToHash(D, Hash);
947 TopLevelDecls.push_back(D);
952 void HandleTranslationUnit(ASTContext &Ctx) override {
953 PCHGenerator::HandleTranslationUnit(Ctx);
954 if (hasEmittedPCH()) {
955 // Write the generated bitstream to "Out".
957 // Make sure it hits disk now.
960 llvm::SmallVector<char, 0> Empty;
961 getPCH() = std::move(Empty);
963 // Translate the top-level declarations we captured during
964 // parsing into declaration IDs in the precompiled
965 // preamble. This will allow us to deserialize those top-level
966 // declarations when requested.
967 for (Decl *D : TopLevelDecls) {
968 // Invalid top-level decls may not have been serialized.
969 if (D->isInvalidDecl())
971 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
974 Action->setHasEmittedPreamblePCH();
979 } // anonymous namespace
981 std::unique_ptr<ASTConsumer>
982 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
985 std::string OutputFile;
986 std::unique_ptr<raw_ostream> OS =
987 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
992 if (!CI.getFrontendOpts().RelocatablePCH)
995 CI.getPreprocessor().addPPCallbacks(
996 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
997 Unit.getCurrentTopLevelHashValue()));
998 return llvm::make_unique<PrecompilePreambleConsumer>(
999 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
1002 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1003 return StoredDiag.getLocation().isValid();
1007 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1008 // Get rid of stored diagnostics except the ones from the driver which do not
1009 // have a source location.
1011 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1015 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1017 SourceManager &SM) {
1018 // The stored diagnostic has the old source manager in it; update
1019 // the locations to refer into the new source manager. Since we've
1020 // been careful to make sure that the source manager's state
1021 // before and after are identical, so that we can reuse the source
1023 for (StoredDiagnostic &SD : StoredDiagnostics) {
1024 if (SD.getLocation().isValid()) {
1025 FullSourceLoc Loc(SD.getLocation(), SM);
1026 SD.setLocation(Loc);
1031 /// Parse the source file into a translation unit using the given compiler
1032 /// invocation, replacing the current translation unit.
1034 /// \returns True if a failure occurred that causes the ASTUnit not to
1035 /// contain any translation-unit information, false otherwise.
1036 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1037 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1038 SavedMainFileBuffer.reset();
1043 // Create the compiler instance to use for building the AST.
1044 std::unique_ptr<CompilerInstance> Clang(
1045 new CompilerInstance(std::move(PCHContainerOps)));
1047 // Recover resources if we crash before exiting this method.
1048 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1049 CICleanup(Clang.get());
1051 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1052 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1054 // Set up diagnostics, capturing any diagnostics that would
1055 // otherwise be dropped.
1056 Clang->setDiagnostics(&getDiagnostics());
1058 // Create the target instance.
1059 Clang->setTarget(TargetInfo::CreateTargetInfo(
1060 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1061 if (!Clang->hasTarget())
1064 // Inform the target of the language options.
1066 // FIXME: We shouldn't need to do this, the target should be immutable once
1067 // created. This complexity should be lifted elsewhere.
1068 Clang->getTarget().adjust(Clang->getLangOpts());
1070 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1071 "Invocation must have exactly one source file!");
1072 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1073 "FIXME: AST inputs not yet supported here!");
1074 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1075 "IR inputs not support here!");
1077 // Configure the various subsystems.
1078 LangOpts = Clang->getInvocation().LangOpts;
1079 FileSystemOpts = Clang->getFileSystemOpts();
1081 Clang->createFileManager();
1082 FileMgr = &Clang->getFileManager();
1084 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1085 UserFilesAreVolatile);
1091 // Clear out old caches and data.
1092 TopLevelDecls.clear();
1093 clearFileLevelDecls();
1094 CleanTemporaryFiles();
1096 if (!OverrideMainBuffer) {
1097 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1098 TopLevelDeclsInPreamble.clear();
1101 // Create a file manager object to provide access to and cache the filesystem.
1102 Clang->setFileManager(&getFileManager());
1104 // Create the source manager.
1105 Clang->setSourceManager(&getSourceManager());
1107 // If the main file has been overridden due to the use of a preamble,
1108 // make that override happen and introduce the preamble.
1109 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1110 if (OverrideMainBuffer) {
1111 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1112 OverrideMainBuffer.get());
1113 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1114 PreprocessorOpts.PrecompiledPreambleBytes.second
1115 = PreambleEndsAtStartOfLine;
1116 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1117 PreprocessorOpts.DisablePCHValidation = true;
1119 // The stored diagnostic has the old source manager in it; update
1120 // the locations to refer into the new source manager. Since we've
1121 // been careful to make sure that the source manager's state
1122 // before and after are identical, so that we can reuse the source
1124 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1126 // Keep track of the override buffer;
1127 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1130 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1131 new TopLevelDeclTrackerAction(*this));
1133 // Recover resources if we crash before exiting this method.
1134 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1135 ActCleanup(Act.get());
1137 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1140 if (SavedMainFileBuffer)
1141 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1142 PreambleDiagnostics, StoredDiagnostics);
1144 if (!Act->Execute())
1147 transferASTDataFromCompilerInstance(*Clang);
1149 Act->EndSourceFile();
1151 FailedParseDiagnostics.clear();
1156 // Remove the overridden buffer we used for the preamble.
1157 SavedMainFileBuffer = nullptr;
1159 // Keep the ownership of the data in the ASTUnit because the client may
1160 // want to see the diagnostics.
1161 transferASTDataFromCompilerInstance(*Clang);
1162 FailedParseDiagnostics.swap(StoredDiagnostics);
1163 StoredDiagnostics.clear();
1164 NumStoredDiagnosticsFromDriver = 0;
1168 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1169 static std::string GetPreamblePCHPath() {
1170 // FIXME: This is a hack so that we can override the preamble file during
1171 // crash-recovery testing, which is the only case where the preamble files
1172 // are not necessarily cleaned up.
1173 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1177 SmallString<128> Path;
1178 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1183 /// \brief Compute the preamble for the main file, providing the source buffer
1184 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1185 /// that describes the preamble.
1186 ASTUnit::ComputedPreamble
1187 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1188 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1189 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1191 // Try to determine if the main file has been remapped, either from the
1192 // command line (to another file) or directly through the compiler invocation
1193 // (to a memory buffer).
1194 llvm::MemoryBuffer *Buffer = nullptr;
1195 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1196 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1197 llvm::sys::fs::UniqueID MainFileID;
1198 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1199 // Check whether there is a file-file remapping of the main file
1200 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1201 std::string MPath(RF.first);
1202 llvm::sys::fs::UniqueID MID;
1203 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1204 if (MainFileID == MID) {
1205 // We found a remapping. Try to load the resulting, remapped source.
1206 BufferOwner = getBufferForFile(RF.second);
1208 return ComputedPreamble(nullptr, nullptr, 0, true);
1213 // Check whether there is a file-buffer remapping. It supercedes the
1214 // file-file remapping.
1215 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1216 std::string MPath(RB.first);
1217 llvm::sys::fs::UniqueID MID;
1218 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1219 if (MainFileID == MID) {
1220 // We found a remapping.
1221 BufferOwner.reset();
1222 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1228 // If the main source file was not remapped, load it now.
1229 if (!Buffer && !BufferOwner) {
1230 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1232 return ComputedPreamble(nullptr, nullptr, 0, true);
1236 Buffer = BufferOwner.get();
1237 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1238 *Invocation.getLangOpts(), MaxLines);
1239 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1243 ASTUnit::PreambleFileHash
1244 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1245 PreambleFileHash Result;
1247 Result.ModTime = ModTime;
1248 memset(Result.MD5, 0, sizeof(Result.MD5));
1252 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1253 const llvm::MemoryBuffer *Buffer) {
1254 PreambleFileHash Result;
1255 Result.Size = Buffer->getBufferSize();
1259 MD5Ctx.update(Buffer->getBuffer().data());
1260 MD5Ctx.final(Result.MD5);
1266 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1267 const ASTUnit::PreambleFileHash &RHS) {
1268 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1269 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1271 } // namespace clang
1273 static std::pair<unsigned, unsigned>
1274 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1275 const LangOptions &LangOpts) {
1276 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1277 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1278 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1279 return std::make_pair(Offset, EndOffset);
1282 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1283 const LangOptions &LangOpts,
1284 const FixItHint &InFix) {
1285 ASTUnit::StandaloneFixIt OutFix;
1286 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1287 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1289 OutFix.CodeToInsert = InFix.CodeToInsert;
1290 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1294 static ASTUnit::StandaloneDiagnostic
1295 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1296 const StoredDiagnostic &InDiag) {
1297 ASTUnit::StandaloneDiagnostic OutDiag;
1298 OutDiag.ID = InDiag.getID();
1299 OutDiag.Level = InDiag.getLevel();
1300 OutDiag.Message = InDiag.getMessage();
1301 OutDiag.LocOffset = 0;
1302 if (InDiag.getLocation().isInvalid())
1304 const SourceManager &SM = InDiag.getLocation().getManager();
1305 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1306 OutDiag.Filename = SM.getFilename(FileLoc);
1307 if (OutDiag.Filename.empty())
1309 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1310 for (const CharSourceRange &Range : InDiag.getRanges())
1311 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1312 for (const FixItHint &FixIt : InDiag.getFixIts())
1313 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1318 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1319 /// the source file.
1321 /// This routine will compute the preamble of the main source file. If a
1322 /// non-trivial preamble is found, it will precompile that preamble into a
1323 /// precompiled header so that the precompiled preamble can be used to reduce
1324 /// reparsing time. If a precompiled preamble has already been constructed,
1325 /// this routine will determine if it is still valid and, if so, avoid
1326 /// rebuilding the precompiled preamble.
1328 /// \param AllowRebuild When true (the default), this routine is
1329 /// allowed to rebuild the precompiled preamble if it is found to be
1332 /// \param MaxLines When non-zero, the maximum number of lines that
1333 /// can occur within the preamble.
1335 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1336 /// buffer that should be used in place of the main file when doing so.
1337 /// Otherwise, returns a NULL pointer.
1338 std::unique_ptr<llvm::MemoryBuffer>
1339 ASTUnit::getMainBufferWithPrecompiledPreamble(
1340 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1341 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1342 unsigned MaxLines) {
1344 auto PreambleInvocation =
1345 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1346 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1347 PreprocessorOptions &PreprocessorOpts
1348 = PreambleInvocation->getPreprocessorOpts();
1350 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1352 if (!NewPreamble.Size) {
1353 // We couldn't find a preamble in the main source. Clear out the current
1354 // preamble, if we have one. It's obviously no good any more.
1356 erasePreambleFile(this);
1358 // The next time we actually see a preamble, precompile it.
1359 PreambleRebuildCounter = 1;
1363 if (!Preamble.empty()) {
1364 // We've previously computed a preamble. Check whether we have the same
1365 // preamble now that we did before, and that there's enough space in
1366 // the main-file buffer within the precompiled preamble to fit the
1368 if (Preamble.size() == NewPreamble.Size &&
1369 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1370 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1371 NewPreamble.Size) == 0) {
1372 // The preamble has not changed. We may be able to re-use the precompiled
1375 // Check that none of the files used by the preamble have changed.
1376 bool AnyFileChanged = false;
1378 // First, make a record of those files that have been overridden via
1379 // remapping or unsaved_files.
1380 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1381 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1386 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1387 // If we can't stat the file we're remapping to, assume that something
1388 // horrible happened.
1389 AnyFileChanged = true;
1393 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1395 llvm::sys::toTimeT(Status.getLastModificationTime()));
1398 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1403 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1404 AnyFileChanged = true;
1408 OverriddenFiles[Status.getUniqueID()] =
1409 PreambleFileHash::createForMemoryBuffer(RB.second);
1412 // Check whether anything has changed.
1413 for (llvm::StringMap<PreambleFileHash>::iterator
1414 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1415 !AnyFileChanged && F != FEnd;
1418 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1419 // If we can't stat the file, assume that something horrible happened.
1420 AnyFileChanged = true;
1424 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1425 = OverriddenFiles.find(Status.getUniqueID());
1426 if (Overridden != OverriddenFiles.end()) {
1427 // This file was remapped; check whether the newly-mapped file
1428 // matches up with the previous mapping.
1429 if (Overridden->second != F->second)
1430 AnyFileChanged = true;
1434 // The file was not remapped; check whether it has changed on disk.
1435 if (Status.getSize() != uint64_t(F->second.Size) ||
1436 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1438 AnyFileChanged = true;
1441 if (!AnyFileChanged) {
1442 // Okay! We can re-use the precompiled preamble.
1444 // Set the state of the diagnostic object to mimic its state
1445 // after parsing the preamble.
1446 getDiagnostics().Reset();
1447 ProcessWarningOptions(getDiagnostics(),
1448 PreambleInvocation->getDiagnosticOpts());
1449 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1451 return llvm::MemoryBuffer::getMemBufferCopy(
1452 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1456 // If we aren't allowed to rebuild the precompiled preamble, just
1461 // We can't reuse the previously-computed preamble. Build a new one.
1463 PreambleDiagnostics.clear();
1464 erasePreambleFile(this);
1465 PreambleRebuildCounter = 1;
1466 } else if (!AllowRebuild) {
1467 // We aren't allowed to rebuild the precompiled preamble; just
1472 // If the preamble rebuild counter > 1, it's because we previously
1473 // failed to build a preamble and we're not yet ready to try
1474 // again. Decrement the counter and return a failure.
1475 if (PreambleRebuildCounter > 1) {
1476 --PreambleRebuildCounter;
1480 // Create a temporary file for the precompiled preamble. In rare
1481 // circumstances, this can fail.
1482 std::string PreamblePCHPath = GetPreamblePCHPath();
1483 if (PreamblePCHPath.empty()) {
1484 // Try again next time.
1485 PreambleRebuildCounter = 1;
1489 // We did not previously compute a preamble, or it can't be reused anyway.
1490 SimpleTimer PreambleTimer(WantTiming);
1491 PreambleTimer.setOutput("Precompiling preamble");
1493 // Save the preamble text for later; we'll need to compare against it for
1494 // subsequent reparses.
1495 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1496 Preamble.assign(FileMgr->getFile(MainFilename),
1497 NewPreamble.Buffer->getBufferStart(),
1498 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1499 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1501 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1502 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1504 // Remap the main source file to the preamble buffer.
1505 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1506 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1508 // Tell the compiler invocation to generate a temporary precompiled header.
1509 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1510 // FIXME: Generate the precompiled header into memory?
1511 FrontendOpts.OutputFile = PreamblePCHPath;
1512 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1513 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1515 // Create the compiler instance to use for building the precompiled preamble.
1516 std::unique_ptr<CompilerInstance> Clang(
1517 new CompilerInstance(std::move(PCHContainerOps)));
1519 // Recover resources if we crash before exiting this method.
1520 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1521 CICleanup(Clang.get());
1523 Clang->setInvocation(std::move(PreambleInvocation));
1524 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1526 // Set up diagnostics, capturing all of the diagnostics produced.
1527 Clang->setDiagnostics(&getDiagnostics());
1529 // Create the target instance.
1530 Clang->setTarget(TargetInfo::CreateTargetInfo(
1531 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1532 if (!Clang->hasTarget()) {
1533 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1535 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1536 PreprocessorOpts.RemappedFileBuffers.pop_back();
1540 // Inform the target of the language options.
1542 // FIXME: We shouldn't need to do this, the target should be immutable once
1543 // created. This complexity should be lifted elsewhere.
1544 Clang->getTarget().adjust(Clang->getLangOpts());
1546 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1547 "Invocation must have exactly one source file!");
1548 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1549 "FIXME: AST inputs not yet supported here!");
1550 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1551 "IR inputs not support here!");
1553 // Clear out old caches and data.
1554 getDiagnostics().Reset();
1555 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1556 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1557 TopLevelDecls.clear();
1558 TopLevelDeclsInPreamble.clear();
1559 PreambleDiagnostics.clear();
1561 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1562 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1566 // Create a file manager object to provide access to and cache the filesystem.
1567 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1569 // Create the source manager.
1570 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1571 Clang->getFileManager()));
1573 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1574 Clang->addDependencyCollector(PreambleDepCollector);
1576 std::unique_ptr<PrecompilePreambleAction> Act;
1577 Act.reset(new PrecompilePreambleAction(*this));
1578 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1579 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1581 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1582 PreprocessorOpts.RemappedFileBuffers.pop_back();
1588 // Transfer any diagnostics generated when parsing the preamble into the set
1589 // of preamble diagnostics.
1590 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1591 E = stored_diag_end();
1593 PreambleDiagnostics.push_back(
1594 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1596 Act->EndSourceFile();
1598 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1600 if (!Act->hasEmittedPreamblePCH()) {
1601 // The preamble PCH failed (e.g. there was a module loading fatal error),
1602 // so no precompiled header was generated. Forget that we even tried.
1603 // FIXME: Should we leave a note for ourselves to try again?
1604 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1606 TopLevelDeclsInPreamble.clear();
1607 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1608 PreprocessorOpts.RemappedFileBuffers.pop_back();
1612 // Keep track of the preamble we precompiled.
1613 setPreambleFile(this, FrontendOpts.OutputFile);
1614 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1616 // Keep track of all of the files that the source manager knows about,
1617 // so we can verify whether they have changed or not.
1618 FilesInPreamble.clear();
1619 SourceManager &SourceMgr = Clang->getSourceManager();
1620 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1621 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1622 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1624 if (time_t ModTime = File->getModificationTime()) {
1625 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1626 File->getSize(), ModTime);
1628 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1629 FilesInPreamble[File->getName()] =
1630 PreambleFileHash::createForMemoryBuffer(Buffer);
1634 PreambleRebuildCounter = 1;
1635 PreprocessorOpts.RemappedFileBuffers.pop_back();
1637 // If the hash of top-level entities differs from the hash of the top-level
1638 // entities the last time we rebuilt the preamble, clear out the completion
1640 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1641 CompletionCacheTopLevelHashValue = 0;
1642 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1645 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1649 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1650 std::vector<Decl *> Resolved;
1651 Resolved.reserve(TopLevelDeclsInPreamble.size());
1652 ExternalASTSource &Source = *getASTContext().getExternalSource();
1653 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1654 // Resolve the declaration ID to an actual declaration, possibly
1655 // deserializing the declaration in the process.
1656 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1657 Resolved.push_back(D);
1659 TopLevelDeclsInPreamble.clear();
1660 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1663 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1664 // Steal the created target, context, and preprocessor if they have been
1666 assert(CI.hasInvocation() && "missing invocation");
1667 LangOpts = CI.getInvocation().LangOpts;
1668 TheSema = CI.takeSema();
1669 Consumer = CI.takeASTConsumer();
1670 if (CI.hasASTContext())
1671 Ctx = &CI.getASTContext();
1672 if (CI.hasPreprocessor())
1673 PP = CI.getPreprocessorPtr();
1674 CI.setSourceManager(nullptr);
1675 CI.setFileManager(nullptr);
1677 Target = &CI.getTarget();
1678 Reader = CI.getModuleManager();
1679 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1682 StringRef ASTUnit::getMainFileName() const {
1683 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1684 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1686 return Input.getFile();
1688 return Input.getBuffer()->getBufferIdentifier();
1692 if (const FileEntry *
1693 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1694 return FE->getName();
1700 StringRef ASTUnit::getASTFileName() const {
1701 if (!isMainFileAST())
1704 serialization::ModuleFile &
1705 Mod = Reader->getModuleManager().getPrimaryModule();
1706 return Mod.FileName;
1709 std::unique_ptr<ASTUnit>
1710 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1711 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1712 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1713 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1714 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1715 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1716 createVFSFromCompilerInvocation(*CI, *Diags);
1719 AST->Diagnostics = Diags;
1720 AST->FileSystemOpts = CI->getFileSystemOpts();
1721 AST->Invocation = std::move(CI);
1722 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1723 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1724 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1725 UserFilesAreVolatile);
1730 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1731 std::shared_ptr<CompilerInvocation> CI,
1732 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1733 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1734 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1735 bool OnlyLocalDecls, bool CaptureDiagnostics,
1736 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1737 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1738 std::unique_ptr<ASTUnit> *ErrAST) {
1739 assert(CI && "A CompilerInvocation is required");
1741 std::unique_ptr<ASTUnit> OwnAST;
1742 ASTUnit *AST = Unit;
1744 // Create the AST unit.
1745 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1751 if (!ResourceFilesPath.empty()) {
1752 // Override the resources path.
1753 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1755 AST->OnlyLocalDecls = OnlyLocalDecls;
1756 AST->CaptureDiagnostics = CaptureDiagnostics;
1757 if (PrecompilePreambleAfterNParses > 0)
1758 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1759 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1760 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1761 AST->IncludeBriefCommentsInCodeCompletion
1762 = IncludeBriefCommentsInCodeCompletion;
1764 // Recover resources if we crash before exiting this method.
1765 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1766 ASTUnitCleanup(OwnAST.get());
1767 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1768 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1769 DiagCleanup(Diags.get());
1771 // We'll manage file buffers ourselves.
1772 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1773 CI->getFrontendOpts().DisableFree = false;
1774 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1776 // Create the compiler instance to use for building the AST.
1777 std::unique_ptr<CompilerInstance> Clang(
1778 new CompilerInstance(std::move(PCHContainerOps)));
1780 // Recover resources if we crash before exiting this method.
1781 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1782 CICleanup(Clang.get());
1784 Clang->setInvocation(std::move(CI));
1785 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1787 // Set up diagnostics, capturing any diagnostics that would
1788 // otherwise be dropped.
1789 Clang->setDiagnostics(&AST->getDiagnostics());
1791 // Create the target instance.
1792 Clang->setTarget(TargetInfo::CreateTargetInfo(
1793 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1794 if (!Clang->hasTarget())
1797 // Inform the target of the language options.
1799 // FIXME: We shouldn't need to do this, the target should be immutable once
1800 // created. This complexity should be lifted elsewhere.
1801 Clang->getTarget().adjust(Clang->getLangOpts());
1803 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1804 "Invocation must have exactly one source file!");
1805 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1806 "FIXME: AST inputs not yet supported here!");
1807 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1808 "IR inputs not supported here!");
1810 // Configure the various subsystems.
1811 AST->TheSema.reset();
1814 AST->Reader = nullptr;
1816 // Create a file manager object to provide access to and cache the filesystem.
1817 Clang->setFileManager(&AST->getFileManager());
1819 // Create the source manager.
1820 Clang->setSourceManager(&AST->getSourceManager());
1822 FrontendAction *Act = Action;
1824 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1826 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1827 Act = TrackerAct.get();
1830 // Recover resources if we crash before exiting this method.
1831 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1832 ActCleanup(TrackerAct.get());
1834 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1835 AST->transferASTDataFromCompilerInstance(*Clang);
1836 if (OwnAST && ErrAST)
1837 ErrAST->swap(OwnAST);
1842 if (Persistent && !TrackerAct) {
1843 Clang->getPreprocessor().addPPCallbacks(
1844 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1845 AST->getCurrentTopLevelHashValue()));
1846 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1847 if (Clang->hasASTConsumer())
1848 Consumers.push_back(Clang->takeASTConsumer());
1849 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1850 *AST, AST->getCurrentTopLevelHashValue()));
1851 Clang->setASTConsumer(
1852 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1854 if (!Act->Execute()) {
1855 AST->transferASTDataFromCompilerInstance(*Clang);
1856 if (OwnAST && ErrAST)
1857 ErrAST->swap(OwnAST);
1862 // Steal the created target, context, and preprocessor.
1863 AST->transferASTDataFromCompilerInstance(*Clang);
1865 Act->EndSourceFile();
1868 return OwnAST.release();
1873 bool ASTUnit::LoadFromCompilerInvocation(
1874 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1875 unsigned PrecompilePreambleAfterNParses) {
1879 // We'll manage file buffers ourselves.
1880 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1881 Invocation->getFrontendOpts().DisableFree = false;
1882 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1884 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1885 if (PrecompilePreambleAfterNParses > 0) {
1886 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1887 OverrideMainBuffer =
1888 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1891 SimpleTimer ParsingTimer(WantTiming);
1892 ParsingTimer.setOutput("Parsing " + getMainFileName());
1894 // Recover resources if we crash before exiting this method.
1895 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1896 MemBufferCleanup(OverrideMainBuffer.get());
1898 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1901 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1902 std::shared_ptr<CompilerInvocation> CI,
1903 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1904 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1905 bool OnlyLocalDecls, bool CaptureDiagnostics,
1906 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1907 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1908 bool UserFilesAreVolatile) {
1909 // Create the AST unit.
1910 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1911 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1912 AST->Diagnostics = Diags;
1913 AST->OnlyLocalDecls = OnlyLocalDecls;
1914 AST->CaptureDiagnostics = CaptureDiagnostics;
1915 AST->TUKind = TUKind;
1916 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1917 AST->IncludeBriefCommentsInCodeCompletion
1918 = IncludeBriefCommentsInCodeCompletion;
1919 AST->Invocation = std::move(CI);
1920 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1921 AST->FileMgr = FileMgr;
1922 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1924 // Recover resources if we crash before exiting this method.
1925 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1926 ASTUnitCleanup(AST.get());
1927 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1928 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1929 DiagCleanup(Diags.get());
1931 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1932 PrecompilePreambleAfterNParses))
1937 ASTUnit *ASTUnit::LoadFromCommandLine(
1938 const char **ArgBegin, const char **ArgEnd,
1939 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1940 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1941 bool OnlyLocalDecls, bool CaptureDiagnostics,
1942 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1943 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1944 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1945 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1946 bool UserFilesAreVolatile, bool ForSerialization,
1947 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
1948 assert(Diags.get() && "no DiagnosticsEngine was provided");
1950 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1952 std::shared_ptr<CompilerInvocation> CI;
1956 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1959 CI = clang::createInvocationFromCommandLine(
1960 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1965 // Override any files that need remapping
1966 for (const auto &RemappedFile : RemappedFiles) {
1967 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1968 RemappedFile.second);
1970 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1971 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1972 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1974 // Override the resources path.
1975 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1977 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1980 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1982 // Create the AST unit.
1983 std::unique_ptr<ASTUnit> AST;
1984 AST.reset(new ASTUnit(false));
1985 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1986 AST->Diagnostics = Diags;
1987 AST->FileSystemOpts = CI->getFileSystemOpts();
1988 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1989 createVFSFromCompilerInvocation(*CI, *Diags);
1992 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1993 AST->OnlyLocalDecls = OnlyLocalDecls;
1994 AST->CaptureDiagnostics = CaptureDiagnostics;
1995 AST->TUKind = TUKind;
1996 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1997 AST->IncludeBriefCommentsInCodeCompletion
1998 = IncludeBriefCommentsInCodeCompletion;
1999 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2000 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2001 AST->StoredDiagnostics.swap(StoredDiagnostics);
2002 AST->Invocation = CI;
2003 if (ForSerialization)
2004 AST->WriterData.reset(new ASTWriterData());
2005 // Zero out now to ease cleanup during crash recovery.
2009 // Recover resources if we crash before exiting this method.
2010 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2011 ASTUnitCleanup(AST.get());
2013 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2014 PrecompilePreambleAfterNParses)) {
2015 // Some error occurred, if caller wants to examine diagnostics, pass it the
2018 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2024 return AST.release();
2027 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2028 ArrayRef<RemappedFile> RemappedFiles) {
2032 clearFileLevelDecls();
2034 SimpleTimer ParsingTimer(WantTiming);
2035 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2038 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2039 for (const auto &RB : PPOpts.RemappedFileBuffers)
2042 Invocation->getPreprocessorOpts().clearRemappedFiles();
2043 for (const auto &RemappedFile : RemappedFiles) {
2044 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2045 RemappedFile.second);
2048 // If we have a preamble file lying around, or if we might try to
2049 // build a precompiled preamble, do so now.
2050 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2051 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2052 OverrideMainBuffer =
2053 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2055 // Clear out the diagnostics state.
2057 getDiagnostics().Reset();
2058 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2059 if (OverrideMainBuffer)
2060 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2062 // Parse the sources
2064 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2066 // If we're caching global code-completion results, and the top-level
2067 // declarations have changed, clear out the code-completion cache.
2068 if (!Result && ShouldCacheCodeCompletionResults &&
2069 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2070 CacheCodeCompletionResults();
2072 // We now need to clear out the completion info related to this translation
2073 // unit; it'll be recreated if necessary.
2079 //----------------------------------------------------------------------------//
2081 //----------------------------------------------------------------------------//
2084 /// \brief Code completion consumer that combines the cached code-completion
2085 /// results from an ASTUnit with the code-completion results provided to it,
2086 /// then passes the result on to
2087 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2088 uint64_t NormalContexts;
2090 CodeCompleteConsumer &Next;
2093 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2094 const CodeCompleteOptions &CodeCompleteOpts)
2095 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2096 AST(AST), Next(Next)
2098 // Compute the set of contexts in which we will look when we don't have
2099 // any information about the specific context.
2101 = (1LL << CodeCompletionContext::CCC_TopLevel)
2102 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2103 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2104 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2105 | (1LL << CodeCompletionContext::CCC_Statement)
2106 | (1LL << CodeCompletionContext::CCC_Expression)
2107 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2108 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2109 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2110 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2111 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2112 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2113 | (1LL << CodeCompletionContext::CCC_Recovery);
2115 if (AST.getASTContext().getLangOpts().CPlusPlus)
2116 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2117 | (1LL << CodeCompletionContext::CCC_UnionTag)
2118 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2121 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2122 CodeCompletionResult *Results,
2123 unsigned NumResults) override;
2125 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2126 OverloadCandidate *Candidates,
2127 unsigned NumCandidates) override {
2128 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2131 CodeCompletionAllocator &getAllocator() override {
2132 return Next.getAllocator();
2135 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2136 return Next.getCodeCompletionTUInfo();
2139 } // anonymous namespace
2141 /// \brief Helper function that computes which global names are hidden by the
2142 /// local code-completion results.
2143 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2144 CodeCompletionResult *Results,
2145 unsigned NumResults,
2147 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2148 bool OnlyTagNames = false;
2149 switch (Context.getKind()) {
2150 case CodeCompletionContext::CCC_Recovery:
2151 case CodeCompletionContext::CCC_TopLevel:
2152 case CodeCompletionContext::CCC_ObjCInterface:
2153 case CodeCompletionContext::CCC_ObjCImplementation:
2154 case CodeCompletionContext::CCC_ObjCIvarList:
2155 case CodeCompletionContext::CCC_ClassStructUnion:
2156 case CodeCompletionContext::CCC_Statement:
2157 case CodeCompletionContext::CCC_Expression:
2158 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2159 case CodeCompletionContext::CCC_DotMemberAccess:
2160 case CodeCompletionContext::CCC_ArrowMemberAccess:
2161 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2162 case CodeCompletionContext::CCC_Namespace:
2163 case CodeCompletionContext::CCC_Type:
2164 case CodeCompletionContext::CCC_Name:
2165 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2166 case CodeCompletionContext::CCC_ParenthesizedExpression:
2167 case CodeCompletionContext::CCC_ObjCInterfaceName:
2170 case CodeCompletionContext::CCC_EnumTag:
2171 case CodeCompletionContext::CCC_UnionTag:
2172 case CodeCompletionContext::CCC_ClassOrStructTag:
2173 OnlyTagNames = true;
2176 case CodeCompletionContext::CCC_ObjCProtocolName:
2177 case CodeCompletionContext::CCC_MacroName:
2178 case CodeCompletionContext::CCC_MacroNameUse:
2179 case CodeCompletionContext::CCC_PreprocessorExpression:
2180 case CodeCompletionContext::CCC_PreprocessorDirective:
2181 case CodeCompletionContext::CCC_NaturalLanguage:
2182 case CodeCompletionContext::CCC_SelectorName:
2183 case CodeCompletionContext::CCC_TypeQualifiers:
2184 case CodeCompletionContext::CCC_Other:
2185 case CodeCompletionContext::CCC_OtherWithMacros:
2186 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2187 case CodeCompletionContext::CCC_ObjCClassMessage:
2188 case CodeCompletionContext::CCC_ObjCCategoryName:
2189 // We're looking for nothing, or we're looking for names that cannot
2194 typedef CodeCompletionResult Result;
2195 for (unsigned I = 0; I != NumResults; ++I) {
2196 if (Results[I].Kind != Result::RK_Declaration)
2200 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2202 bool Hiding = false;
2204 Hiding = (IDNS & Decl::IDNS_Tag);
2206 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2207 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2208 Decl::IDNS_NonMemberOperator);
2209 if (Ctx.getLangOpts().CPlusPlus)
2210 HiddenIDNS |= Decl::IDNS_Tag;
2211 Hiding = (IDNS & HiddenIDNS);
2217 DeclarationName Name = Results[I].Declaration->getDeclName();
2218 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2219 HiddenNames.insert(Identifier->getName());
2221 HiddenNames.insert(Name.getAsString());
2225 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2226 CodeCompletionContext Context,
2227 CodeCompletionResult *Results,
2228 unsigned NumResults) {
2229 // Merge the results we were given with the results we cached.
2230 bool AddedResult = false;
2231 uint64_t InContexts =
2232 Context.getKind() == CodeCompletionContext::CCC_Recovery
2233 ? NormalContexts : (1LL << Context.getKind());
2234 // Contains the set of names that are hidden by "local" completion results.
2235 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2236 typedef CodeCompletionResult Result;
2237 SmallVector<Result, 8> AllResults;
2238 for (ASTUnit::cached_completion_iterator
2239 C = AST.cached_completion_begin(),
2240 CEnd = AST.cached_completion_end();
2242 // If the context we are in matches any of the contexts we are
2243 // interested in, we'll add this result.
2244 if ((C->ShowInContexts & InContexts) == 0)
2247 // If we haven't added any results previously, do so now.
2249 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2251 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2255 // Determine whether this global completion result is hidden by a local
2256 // completion result. If so, skip it.
2257 if (C->Kind != CXCursor_MacroDefinition &&
2258 HiddenNames.count(C->Completion->getTypedText()))
2261 // Adjust priority based on similar type classes.
2262 unsigned Priority = C->Priority;
2263 CodeCompletionString *Completion = C->Completion;
2264 if (!Context.getPreferredType().isNull()) {
2265 if (C->Kind == CXCursor_MacroDefinition) {
2266 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2268 Context.getPreferredType()->isAnyPointerType());
2269 } else if (C->Type) {
2270 CanQualType Expected
2271 = S.Context.getCanonicalType(
2272 Context.getPreferredType().getUnqualifiedType());
2273 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2274 if (ExpectedSTC == C->TypeClass) {
2275 // We know this type is similar; check for an exact match.
2276 llvm::StringMap<unsigned> &CachedCompletionTypes
2277 = AST.getCachedCompletionTypes();
2278 llvm::StringMap<unsigned>::iterator Pos
2279 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2280 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2281 Priority /= CCF_ExactTypeMatch;
2283 Priority /= CCF_SimilarTypeMatch;
2288 // Adjust the completion string, if required.
2289 if (C->Kind == CXCursor_MacroDefinition &&
2290 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2291 // Create a new code-completion string that just contains the
2292 // macro name, without its arguments.
2293 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2294 CCP_CodePattern, C->Availability);
2295 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2296 Priority = CCP_CodePattern;
2297 Completion = Builder.TakeString();
2300 AllResults.push_back(Result(Completion, Priority, C->Kind,
2304 // If we did not add any cached completion results, just forward the
2305 // results we were given to the next consumer.
2307 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2311 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2315 void ASTUnit::CodeComplete(
2316 StringRef File, unsigned Line, unsigned Column,
2317 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2318 bool IncludeCodePatterns, bool IncludeBriefComments,
2319 CodeCompleteConsumer &Consumer,
2320 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2321 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2322 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2323 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2327 SimpleTimer CompletionTimer(WantTiming);
2328 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2329 Twine(Line) + ":" + Twine(Column));
2331 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2333 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2334 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2335 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2337 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2338 CachedCompletionResults.empty();
2339 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2340 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2341 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2343 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2345 FrontendOpts.CodeCompletionAt.FileName = File;
2346 FrontendOpts.CodeCompletionAt.Line = Line;
2347 FrontendOpts.CodeCompletionAt.Column = Column;
2349 // Set the language options appropriately.
2350 LangOpts = *CCInvocation->getLangOpts();
2352 // Spell-checking and warnings are wasteful during code-completion.
2353 LangOpts.SpellChecking = false;
2354 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2356 std::unique_ptr<CompilerInstance> Clang(
2357 new CompilerInstance(PCHContainerOps));
2359 // Recover resources if we crash before exiting this method.
2360 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2361 CICleanup(Clang.get());
2363 auto &Inv = *CCInvocation;
2364 Clang->setInvocation(std::move(CCInvocation));
2365 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2367 // Set up diagnostics, capturing any diagnostics produced.
2368 Clang->setDiagnostics(&Diag);
2369 CaptureDroppedDiagnostics Capture(true,
2370 Clang->getDiagnostics(),
2372 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2374 // Create the target instance.
2375 Clang->setTarget(TargetInfo::CreateTargetInfo(
2376 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2377 if (!Clang->hasTarget()) {
2378 Clang->setInvocation(nullptr);
2382 // Inform the target of the language options.
2384 // FIXME: We shouldn't need to do this, the target should be immutable once
2385 // created. This complexity should be lifted elsewhere.
2386 Clang->getTarget().adjust(Clang->getLangOpts());
2388 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2389 "Invocation must have exactly one source file!");
2390 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2391 "FIXME: AST inputs not yet supported here!");
2392 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2393 "IR inputs not support here!");
2396 // Use the source and file managers that we were given.
2397 Clang->setFileManager(&FileMgr);
2398 Clang->setSourceManager(&SourceMgr);
2401 PreprocessorOpts.clearRemappedFiles();
2402 PreprocessorOpts.RetainRemappedFileBuffers = true;
2403 for (const auto &RemappedFile : RemappedFiles) {
2404 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2405 OwnedBuffers.push_back(RemappedFile.second);
2408 // Use the code completion consumer we were given, but adding any cached
2409 // code-completion results.
2410 AugmentedCodeCompleteConsumer *AugmentedConsumer
2411 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2412 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2414 // If we have a precompiled preamble, try to use it. We only allow
2415 // the use of the precompiled preamble if we're if the completion
2416 // point is within the main file, after the end of the precompiled
2418 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2419 if (!getPreambleFile(this).empty()) {
2420 std::string CompleteFilePath(File);
2421 llvm::sys::fs::UniqueID CompleteFileID;
2423 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2424 std::string MainPath(OriginalSourceFile);
2425 llvm::sys::fs::UniqueID MainID;
2426 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2427 if (CompleteFileID == MainID && Line > 1)
2428 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2429 PCHContainerOps, Inv, false, Line - 1);
2434 // If the main file has been overridden due to the use of a preamble,
2435 // make that override happen and introduce the preamble.
2436 if (OverrideMainBuffer) {
2437 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2438 OverrideMainBuffer.get());
2439 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2440 PreprocessorOpts.PrecompiledPreambleBytes.second
2441 = PreambleEndsAtStartOfLine;
2442 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2443 PreprocessorOpts.DisablePCHValidation = true;
2445 OwnedBuffers.push_back(OverrideMainBuffer.release());
2447 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2448 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2451 // Disable the preprocessing record if modules are not enabled.
2452 if (!Clang->getLangOpts().Modules)
2453 PreprocessorOpts.DetailedRecord = false;
2455 std::unique_ptr<SyntaxOnlyAction> Act;
2456 Act.reset(new SyntaxOnlyAction);
2457 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2459 Act->EndSourceFile();
2463 bool ASTUnit::Save(StringRef File) {
2464 if (HadModuleLoaderFatalFailure)
2467 // Write to a temporary file and later rename it to the actual file, to avoid
2468 // possible race conditions.
2469 SmallString<128> TempPath;
2471 TempPath += "-%%%%%%%%";
2473 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2476 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2477 // unconditionally create a stat cache when we parse the file?
2478 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2482 if (Out.has_error()) {
2487 if (llvm::sys::fs::rename(TempPath, File)) {
2488 llvm::sys::fs::remove(TempPath);
2495 static bool serializeUnit(ASTWriter &Writer,
2496 SmallVectorImpl<char> &Buffer,
2500 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2502 // Write the generated bitstream to "Out".
2503 if (!Buffer.empty())
2504 OS.write(Buffer.data(), Buffer.size());
2509 bool ASTUnit::serialize(raw_ostream &OS) {
2510 // For serialization we are lenient if the errors were only warn-as-error kind.
2511 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2514 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2515 getSema(), hasErrors, OS);
2517 SmallString<128> Buffer;
2518 llvm::BitstreamWriter Stream(Buffer);
2519 ASTWriter Writer(Stream, { });
2520 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2523 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2525 void ASTUnit::TranslateStoredDiagnostics(
2526 FileManager &FileMgr,
2527 SourceManager &SrcMgr,
2528 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2529 SmallVectorImpl<StoredDiagnostic> &Out) {
2530 // Map the standalone diagnostic into the new source manager. We also need to
2531 // remap all the locations to the new view. This includes the diag location,
2532 // any associated source ranges, and the source ranges of associated fix-its.
2533 // FIXME: There should be a cleaner way to do this.
2535 SmallVector<StoredDiagnostic, 4> Result;
2536 Result.reserve(Diags.size());
2537 for (const StandaloneDiagnostic &SD : Diags) {
2538 // Rebuild the StoredDiagnostic.
2539 if (SD.Filename.empty())
2541 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2544 FileID FID = SrcMgr.translateFile(FE);
2545 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2546 if (FileLoc.isInvalid())
2548 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2549 FullSourceLoc Loc(L, SrcMgr);
2551 SmallVector<CharSourceRange, 4> Ranges;
2552 Ranges.reserve(SD.Ranges.size());
2553 for (const auto &Range : SD.Ranges) {
2554 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2555 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2556 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2559 SmallVector<FixItHint, 2> FixIts;
2560 FixIts.reserve(SD.FixIts.size());
2561 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2562 FixIts.push_back(FixItHint());
2563 FixItHint &FH = FixIts.back();
2564 FH.CodeToInsert = FixIt.CodeToInsert;
2565 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2566 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2567 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2570 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2571 SD.Message, Loc, Ranges, FixIts));
2576 void ASTUnit::addFileLevelDecl(Decl *D) {
2579 // We only care about local declarations.
2580 if (D->isFromASTFile())
2583 SourceManager &SM = *SourceMgr;
2584 SourceLocation Loc = D->getLocation();
2585 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2588 // We only keep track of the file-level declarations of each file.
2589 if (!D->getLexicalDeclContext()->isFileContext())
2592 SourceLocation FileLoc = SM.getFileLoc(Loc);
2593 assert(SM.isLocalSourceLocation(FileLoc));
2596 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2597 if (FID.isInvalid())
2600 LocDeclsTy *&Decls = FileDecls[FID];
2602 Decls = new LocDeclsTy();
2604 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2606 if (Decls->empty() || Decls->back().first <= Offset) {
2607 Decls->push_back(LocDecl);
2611 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2612 LocDecl, llvm::less_first());
2614 Decls->insert(I, LocDecl);
2617 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2618 SmallVectorImpl<Decl *> &Decls) {
2619 if (File.isInvalid())
2622 if (SourceMgr->isLoadedFileID(File)) {
2623 assert(Ctx->getExternalSource() && "No external source!");
2624 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2628 FileDeclsTy::iterator I = FileDecls.find(File);
2629 if (I == FileDecls.end())
2632 LocDeclsTy &LocDecls = *I->second;
2633 if (LocDecls.empty())
2636 LocDeclsTy::iterator BeginIt =
2637 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2638 std::make_pair(Offset, (Decl *)nullptr),
2639 llvm::less_first());
2640 if (BeginIt != LocDecls.begin())
2643 // If we are pointing at a top-level decl inside an objc container, we need
2644 // to backtrack until we find it otherwise we will fail to report that the
2645 // region overlaps with an objc container.
2646 while (BeginIt != LocDecls.begin() &&
2647 BeginIt->second->isTopLevelDeclInObjCContainer())
2650 LocDeclsTy::iterator EndIt = std::upper_bound(
2651 LocDecls.begin(), LocDecls.end(),
2652 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2653 if (EndIt != LocDecls.end())
2656 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2657 Decls.push_back(DIt->second);
2660 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2661 unsigned Line, unsigned Col) const {
2662 const SourceManager &SM = getSourceManager();
2663 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2664 return SM.getMacroArgExpandedLocation(Loc);
2667 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2668 unsigned Offset) const {
2669 const SourceManager &SM = getSourceManager();
2670 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2671 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2674 /// \brief If \arg Loc is a loaded location from the preamble, returns
2675 /// the corresponding local location of the main file, otherwise it returns
2677 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2680 PreambleID = SourceMgr->getPreambleFileID();
2682 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2686 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2687 SourceLocation FileLoc
2688 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2689 return FileLoc.getLocWithOffset(Offs);
2695 /// \brief If \arg Loc is a local location of the main file but inside the
2696 /// preamble chunk, returns the corresponding loaded location from the
2697 /// preamble, otherwise it returns \arg Loc.
2698 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2701 PreambleID = SourceMgr->getPreambleFileID();
2703 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2707 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2708 Offs < Preamble.size()) {
2709 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2710 return FileLoc.getLocWithOffset(Offs);
2716 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2719 FID = SourceMgr->getPreambleFileID();
2721 if (Loc.isInvalid() || FID.isInvalid())
2724 return SourceMgr->isInFileID(Loc, FID);
2727 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2730 FID = SourceMgr->getMainFileID();
2732 if (Loc.isInvalid() || FID.isInvalid())
2735 return SourceMgr->isInFileID(Loc, FID);
2738 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2741 FID = SourceMgr->getPreambleFileID();
2743 if (FID.isInvalid())
2744 return SourceLocation();
2746 return SourceMgr->getLocForEndOfFile(FID);
2749 SourceLocation ASTUnit::getStartOfMainFileID() {
2752 FID = SourceMgr->getMainFileID();
2754 if (FID.isInvalid())
2755 return SourceLocation();
2757 return SourceMgr->getLocForStartOfFile(FID);
2760 llvm::iterator_range<PreprocessingRecord::iterator>
2761 ASTUnit::getLocalPreprocessingEntities() const {
2762 if (isMainFileAST()) {
2763 serialization::ModuleFile &
2764 Mod = Reader->getModuleManager().getPrimaryModule();
2765 return Reader->getModulePreprocessedEntities(Mod);
2768 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2769 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2771 return llvm::make_range(PreprocessingRecord::iterator(),
2772 PreprocessingRecord::iterator());
2775 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2776 if (isMainFileAST()) {
2777 serialization::ModuleFile &
2778 Mod = Reader->getModuleManager().getPrimaryModule();
2779 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2780 if (!Fn(context, D))
2787 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2788 TLEnd = top_level_end();
2789 TL != TLEnd; ++TL) {
2790 if (!Fn(context, *TL))
2797 const FileEntry *ASTUnit::getPCHFile() {
2801 serialization::ModuleFile *Mod = nullptr;
2802 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2804 case serialization::MK_ImplicitModule:
2805 case serialization::MK_ExplicitModule:
2806 case serialization::MK_PrebuiltModule:
2807 return true; // skip dependencies.
2808 case serialization::MK_PCH:
2810 return true; // found it.
2811 case serialization::MK_Preamble:
2812 return false; // look in dependencies.
2813 case serialization::MK_MainFile:
2814 return false; // look in dependencies.
2825 bool ASTUnit::isModuleFile() {
2826 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2829 void ASTUnit::PreambleData::countLines() const {
2834 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2836 if (Buffer.back() != '\n')
2841 ASTUnit::ConcurrencyState::ConcurrencyState() {
2842 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2845 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2846 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2849 void ASTUnit::ConcurrencyState::start() {
2850 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2851 assert(acquired && "Concurrent access to ASTUnit!");
2854 void ASTUnit::ConcurrencyState::finish() {
2855 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2860 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2861 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2862 void ASTUnit::ConcurrencyState::start() {}
2863 void ASTUnit::ConcurrencyState::finish() {}