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/MemoryBufferCache.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Basic/VirtualFileSystem.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/FrontendActions.h"
27 #include "clang/Frontend/FrontendDiagnostic.h"
28 #include "clang/Frontend/FrontendOptions.h"
29 #include "clang/Frontend/MultiplexConsumer.h"
30 #include "clang/Frontend/Utils.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Serialization/ASTReader.h"
36 #include "clang/Serialization/ASTWriter.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringSet.h"
40 #include "llvm/Support/CrashRecoveryContext.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Mutex.h"
44 #include "llvm/Support/MutexGuard.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
53 using llvm::TimeRecord;
62 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
64 Start = TimeRecord::getCurrentTime();
67 void setOutput(const Twine &Output) {
69 this->Output = Output.str();
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
87 /// \brief Temporary files that should be removed when the ASTUnit is
89 SmallVector<std::string, 4> TemporaryFiles;
91 /// \brief Erase temporary files.
92 void CleanTemporaryFiles();
94 /// \brief Erase the preamble file.
95 void CleanPreambleFile();
97 /// \brief Erase temporary files and the preamble file.
102 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
103 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
107 static void cleanupOnDiskMapAtExit();
109 typedef llvm::DenseMap<const ASTUnit *,
110 std::unique_ptr<OnDiskData>> OnDiskDataMap;
111 static OnDiskDataMap &getOnDiskDataMap() {
112 static OnDiskDataMap M;
113 static bool hasRegisteredAtExit = false;
114 if (!hasRegisteredAtExit) {
115 hasRegisteredAtExit = true;
116 atexit(cleanupOnDiskMapAtExit);
121 static void cleanupOnDiskMapAtExit() {
122 // Use the mutex because there can be an alive thread destroying an ASTUnit.
123 llvm::MutexGuard Guard(getOnDiskMutex());
124 for (const auto &I : getOnDiskDataMap()) {
125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
131 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
132 // We require the mutex since we are modifying the structure of the
134 llvm::MutexGuard Guard(getOnDiskMutex());
135 OnDiskDataMap &M = getOnDiskDataMap();
138 D = llvm::make_unique<OnDiskData>();
142 static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
146 static void removeOnDiskEntry(const ASTUnit *AU) {
147 // We require the mutex since we are modifying the structure of the
149 llvm::MutexGuard Guard(getOnDiskMutex());
150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
153 I->second->Cleanup();
158 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
159 getOnDiskData(AU).PreambleFile = preambleFile;
162 static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
166 void OnDiskData::CleanTemporaryFiles() {
167 for (StringRef File : TemporaryFiles)
168 llvm::sys::fs::remove(File);
169 TemporaryFiles.clear();
172 void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::fs::remove(PreambleFile);
175 PreambleFile.clear();
179 void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
184 struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
189 ASTWriterData(MemoryBufferCache &PCMCache)
190 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
193 void ASTUnit::clearFileLevelDecls() {
194 llvm::DeleteContainerSeconds(FileDecls);
197 void ASTUnit::CleanTemporaryFiles() {
198 getOnDiskData(this).CleanTemporaryFiles();
201 void ASTUnit::addTemporaryFile(StringRef TempFile) {
202 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
205 /// \brief After failing to build a precompiled preamble (due to
206 /// errors in the source that occurs in the preamble), the number of
207 /// reparses during which we'll skip even trying to precompile the
209 const unsigned DefaultPreambleRebuildInterval = 5;
211 /// \brief Tracks the number of ASTUnit objects that are currently active.
213 /// Used for debugging purposes only.
214 static std::atomic<unsigned> ActiveASTUnitObjects;
216 ASTUnit::ASTUnit(bool _MainFileIsAST)
217 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
218 OnlyLocalDecls(false), CaptureDiagnostics(false),
219 MainFileIsAST(_MainFileIsAST),
220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
221 OwnsRemappedFileBuffers(true),
222 NumStoredDiagnosticsFromDriver(0),
223 PreambleRebuildCounter(0),
224 NumWarningsInPreamble(0),
225 ShouldCacheCodeCompletionResults(false),
226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
230 UnsafeToFree(false) {
231 if (getenv("LIBCLANG_OBJTRACKING"))
232 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
235 ASTUnit::~ASTUnit() {
236 // If we loaded from an AST file, balance out the BeginSourceFile call.
237 if (MainFileIsAST && getDiagnostics().getClient()) {
238 getDiagnostics().getClient()->EndSourceFile();
241 clearFileLevelDecls();
243 // Clean up the temporary files and the preamble file.
244 removeOnDiskEntry(this);
246 // Free the buffers associated with remapped files. We are required to
247 // perform this operation here because we explicitly request that the
248 // compiler instance *not* free these buffers for each invocation of the
250 if (Invocation && OwnsRemappedFileBuffers) {
251 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
252 for (const auto &RB : PPOpts.RemappedFileBuffers)
256 ClearCachedCompletionResults();
258 if (getenv("LIBCLANG_OBJTRACKING"))
259 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
262 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
263 this->PP = std::move(PP);
266 /// \brief Determine the set of code-completion contexts in which this
267 /// declaration should be shown.
268 static unsigned getDeclShowContexts(const NamedDecl *ND,
269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
278 uint64_t Contexts = 0;
279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
283 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
284 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
285 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
286 | (1LL << CodeCompletionContext::CCC_Statement)
287 | (1LL << CodeCompletionContext::CCC_Type)
288 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
292 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
305 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
307 // Part of the nested-name-specifier in C++0x.
308 if (LangOpts.CPlusPlus11)
309 IsNestedNameSpecifier = true;
310 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
311 if (Record->isUnion())
312 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
314 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
316 if (LangOpts.CPlusPlus)
317 IsNestedNameSpecifier = true;
318 } else if (isa<ClassTemplateDecl>(ND))
319 IsNestedNameSpecifier = true;
320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
322 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
323 | (1LL << CodeCompletionContext::CCC_Expression)
324 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
325 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
326 } else if (isa<ObjCProtocolDecl>(ND)) {
327 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
328 } else if (isa<ObjCCategoryDecl>(ND)) {
329 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
331 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
333 // Part of the nested-name-specifier.
334 IsNestedNameSpecifier = true;
340 void ASTUnit::CacheCodeCompletionResults() {
344 SimpleTimer Timer(WantTiming);
345 Timer.setOutput("Cache global code completions for " + getMainFileName());
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
350 // Gather the set of global code completions.
351 typedef CodeCompletionResult Result;
352 SmallVector<Result, 8> Results;
353 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
354 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
355 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
358 // Translate global code completions into cached completions.
359 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
360 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
362 for (Result &R : Results) {
364 case Result::RK_Declaration: {
365 bool IsNestedNameSpecifier = false;
366 CachedCodeCompletionResult CachedResult;
367 CachedResult.Completion = R.CreateCodeCompletionString(
368 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
369 IncludeBriefCommentsInCodeCompletion);
370 CachedResult.ShowInContexts = getDeclShowContexts(
371 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
372 CachedResult.Priority = R.Priority;
373 CachedResult.Kind = R.CursorKind;
374 CachedResult.Availability = R.Availability;
376 // Keep track of the type of this completion in an ASTContext-agnostic
378 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
379 if (UsageType.isNull()) {
380 CachedResult.TypeClass = STC_Void;
381 CachedResult.Type = 0;
383 CanQualType CanUsageType
384 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
385 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
387 // Determine whether we have already seen this type. If so, we save
388 // ourselves the work of formatting the type string by using the
389 // temporary, CanQualType-based hash table to find the associated value.
390 unsigned &TypeValue = CompletionTypes[CanUsageType];
391 if (TypeValue == 0) {
392 TypeValue = CompletionTypes.size();
393 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
397 CachedResult.Type = TypeValue;
400 CachedCompletionResults.push_back(CachedResult);
402 /// Handle nested-name-specifiers in C++.
403 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
404 !R.StartsNestedNameSpecifier) {
405 // The contexts in which a nested-name-specifier can appear in C++.
407 = (1LL << CodeCompletionContext::CCC_TopLevel)
408 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
409 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
410 | (1LL << CodeCompletionContext::CCC_Statement)
411 | (1LL << CodeCompletionContext::CCC_Expression)
412 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
413 | (1LL << CodeCompletionContext::CCC_EnumTag)
414 | (1LL << CodeCompletionContext::CCC_UnionTag)
415 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
416 | (1LL << CodeCompletionContext::CCC_Type)
417 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
418 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
420 if (isa<NamespaceDecl>(R.Declaration) ||
421 isa<NamespaceAliasDecl>(R.Declaration))
422 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
424 if (unsigned RemainingContexts
425 = NNSContexts & ~CachedResult.ShowInContexts) {
426 // If there any contexts where this completion can be a
427 // nested-name-specifier but isn't already an option, create a
428 // nested-name-specifier completion.
429 R.StartsNestedNameSpecifier = true;
430 CachedResult.Completion = R.CreateCodeCompletionString(
431 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
432 IncludeBriefCommentsInCodeCompletion);
433 CachedResult.ShowInContexts = RemainingContexts;
434 CachedResult.Priority = CCP_NestedNameSpecifier;
435 CachedResult.TypeClass = STC_Void;
436 CachedResult.Type = 0;
437 CachedCompletionResults.push_back(CachedResult);
443 case Result::RK_Keyword:
444 case Result::RK_Pattern:
445 // Ignore keywords and patterns; we don't care, since they are so
446 // easily regenerated.
449 case Result::RK_Macro: {
450 CachedCodeCompletionResult CachedResult;
451 CachedResult.Completion = R.CreateCodeCompletionString(
452 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
453 IncludeBriefCommentsInCodeCompletion);
454 CachedResult.ShowInContexts
455 = (1LL << CodeCompletionContext::CCC_TopLevel)
456 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
457 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
458 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
459 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
460 | (1LL << CodeCompletionContext::CCC_Statement)
461 | (1LL << CodeCompletionContext::CCC_Expression)
462 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
463 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
464 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
465 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
466 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
468 CachedResult.Priority = R.Priority;
469 CachedResult.Kind = R.CursorKind;
470 CachedResult.Availability = R.Availability;
471 CachedResult.TypeClass = STC_Void;
472 CachedResult.Type = 0;
473 CachedCompletionResults.push_back(CachedResult);
479 // Save the current top-level hash value.
480 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
483 void ASTUnit::ClearCachedCompletionResults() {
484 CachedCompletionResults.clear();
485 CachedCompletionTypes.clear();
486 CachedCompletionAllocator = nullptr;
491 /// \brief Gathers information from ASTReader that will be used to initialize
493 class ASTInfoCollector : public ASTReaderListener {
496 LangOptions &LangOpt;
497 std::shared_ptr<TargetOptions> &TargetOpts;
498 IntrusiveRefCntPtr<TargetInfo> &Target;
501 bool InitializedLanguage;
503 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
504 std::shared_ptr<TargetOptions> &TargetOpts,
505 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
506 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
507 Target(Target), Counter(Counter), InitializedLanguage(false) {}
509 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
510 bool AllowCompatibleDifferences) override {
511 if (InitializedLanguage)
515 InitializedLanguage = true;
521 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
522 bool AllowCompatibleDifferences) override {
523 // If we've already initialized the target, don't do it again.
527 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
529 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
535 void ReadCounter(const serialization::ModuleFile &M,
536 unsigned Value) override {
542 if (!Target || !InitializedLanguage)
545 // Inform the target of the language options.
547 // FIXME: We shouldn't need to do this, the target should be immutable once
548 // created. This complexity should be lifted elsewhere.
549 Target->adjust(LangOpt);
551 // Initialize the preprocessor.
552 PP.Initialize(*Target);
554 // Initialize the ASTContext
555 Context.InitBuiltinTypes(*Target);
557 // We didn't have access to the comment options when the ASTContext was
558 // constructed, so register them now.
559 Context.getCommentCommandTraits().registerCommentOptions(
560 LangOpt.CommentOpts);
564 /// \brief Diagnostic consumer that saves each diagnostic it is given.
565 class StoredDiagnosticConsumer : public DiagnosticConsumer {
566 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
567 SourceManager *SourceMgr;
570 explicit StoredDiagnosticConsumer(
571 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
572 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
574 void BeginSourceFile(const LangOptions &LangOpts,
575 const Preprocessor *PP = nullptr) override {
577 SourceMgr = &PP->getSourceManager();
580 void HandleDiagnostic(DiagnosticsEngine::Level Level,
581 const Diagnostic &Info) override;
584 /// \brief RAII object that optionally captures diagnostics, if
585 /// there is no diagnostic client to capture them already.
586 class CaptureDroppedDiagnostics {
587 DiagnosticsEngine &Diags;
588 StoredDiagnosticConsumer Client;
589 DiagnosticConsumer *PreviousClient;
590 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
593 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
594 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
595 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
597 if (RequestCapture || Diags.getClient() == nullptr) {
598 OwningPreviousClient = Diags.takeClient();
599 PreviousClient = Diags.getClient();
600 Diags.setClient(&Client, false);
604 ~CaptureDroppedDiagnostics() {
605 if (Diags.getClient() == &Client)
606 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
610 } // anonymous namespace
612 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
613 const Diagnostic &Info) {
614 // Default implementation (Warnings/errors count).
615 DiagnosticConsumer::HandleDiagnostic(Level, Info);
617 // Only record the diagnostic if it's part of the source manager we know
618 // about. This effectively drops diagnostics from modules we're building.
619 // FIXME: In the long run, ee don't want to drop source managers from modules.
620 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
621 StoredDiags.emplace_back(Level, Info);
624 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
628 ASTMutationListener *ASTUnit::getASTMutationListener() {
630 return &WriterData->Writer;
634 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
636 return &WriterData->Writer;
640 std::unique_ptr<llvm::MemoryBuffer>
641 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
643 auto Buffer = FileMgr->getBufferForFile(Filename);
645 return std::move(*Buffer);
647 *ErrorStr = Buffer.getError().message();
651 /// \brief Configure the diagnostics object for use with ASTUnit.
652 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
653 ASTUnit &AST, bool CaptureDiagnostics) {
654 assert(Diags.get() && "no DiagnosticsEngine was provided");
655 if (CaptureDiagnostics)
656 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
659 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
660 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
661 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
662 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
663 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
664 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
665 bool UserFilesAreVolatile) {
666 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
668 // Recover resources if we crash before exiting this method.
669 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
670 ASTUnitCleanup(AST.get());
671 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
672 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
673 DiagCleanup(Diags.get());
675 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
677 AST->OnlyLocalDecls = OnlyLocalDecls;
678 AST->CaptureDiagnostics = CaptureDiagnostics;
679 AST->Diagnostics = Diags;
680 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
681 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
682 AST->UserFilesAreVolatile = UserFilesAreVolatile;
683 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
684 AST->getFileManager(),
685 UserFilesAreVolatile);
686 AST->PCMCache = new MemoryBufferCache;
687 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
688 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
689 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
690 AST->getSourceManager(),
691 AST->getDiagnostics(),
692 AST->ASTFileLangOpts,
693 /*Target=*/nullptr));
695 auto PPOpts = std::make_shared<PreprocessorOptions>();
697 for (const auto &RemappedFile : RemappedFiles)
698 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
700 // Gather Info for preprocessor construction later on.
702 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
705 AST->PP = std::make_shared<Preprocessor>(
706 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
707 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
708 /*IILookup=*/nullptr,
709 /*OwnsHeaderSearch=*/false);
710 Preprocessor &PP = *AST->PP;
712 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
713 PP.getIdentifierTable(), PP.getSelectorTable(),
714 PP.getBuiltinInfo());
715 ASTContext &Context = *AST->Ctx;
717 bool disableValid = false;
718 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
720 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
722 /*DisableValidation=*/disableValid,
723 AllowPCHWithCompilerErrors);
725 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
726 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
729 // Attach the AST reader to the AST context as an external AST
730 // source, so that declarations will be deserialized from the
731 // AST file as needed.
732 // We need the external source to be set up before we read the AST, because
733 // eagerly-deserialized declarations may use it.
734 Context.setExternalSource(AST->Reader);
736 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
737 SourceLocation(), ASTReader::ARR_None)) {
738 case ASTReader::Success:
741 case ASTReader::Failure:
742 case ASTReader::Missing:
743 case ASTReader::OutOfDate:
744 case ASTReader::VersionMismatch:
745 case ASTReader::ConfigurationMismatch:
746 case ASTReader::HadErrors:
747 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
751 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
753 PP.setCounterValue(Counter);
755 // Create an AST consumer, even though it isn't used.
756 AST->Consumer.reset(new ASTConsumer);
758 // Create a semantic analysis object and tell the AST reader about it.
759 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
760 AST->TheSema->Initialize();
761 AST->Reader->InitializeSema(*AST->TheSema);
763 // Tell the diagnostic client that we have started a source file.
764 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
771 /// \brief Preprocessor callback class that updates a hash value with the names
772 /// of all macros that have been defined by the translation unit.
773 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
777 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
779 void MacroDefined(const Token &MacroNameTok,
780 const MacroDirective *MD) override {
781 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
785 /// \brief Add the given declaration to the hash of all top-level entities.
786 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
790 DeclContext *DC = D->getDeclContext();
794 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
797 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
798 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
799 // For an unscoped enum include the enumerators in the hash since they
800 // enter the top-level namespace.
801 if (!EnumD->isScoped()) {
802 for (const auto *EI : EnumD->enumerators()) {
803 if (EI->getIdentifier())
804 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
809 if (ND->getIdentifier())
810 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
811 else if (DeclarationName Name = ND->getDeclName()) {
812 std::string NameStr = Name.getAsString();
813 Hash = llvm::HashString(NameStr, Hash);
818 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
819 if (Module *Mod = ImportD->getImportedModule()) {
820 std::string ModName = Mod->getFullModuleName();
821 Hash = llvm::HashString(ModName, Hash);
827 class TopLevelDeclTrackerConsumer : public ASTConsumer {
832 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
833 : Unit(_Unit), Hash(Hash) {
837 void handleTopLevelDecl(Decl *D) {
841 // FIXME: Currently ObjC method declarations are incorrectly being
842 // reported as top-level declarations, even though their DeclContext
843 // is the containing ObjC @interface/@implementation. This is a
844 // fundamental problem in the parser right now.
845 if (isa<ObjCMethodDecl>(D))
848 AddTopLevelDeclarationToHash(D, Hash);
849 Unit.addTopLevelDecl(D);
851 handleFileLevelDecl(D);
854 void handleFileLevelDecl(Decl *D) {
855 Unit.addFileLevelDecl(D);
856 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
857 for (auto *I : NSD->decls())
858 handleFileLevelDecl(I);
862 bool HandleTopLevelDecl(DeclGroupRef D) override {
863 for (Decl *TopLevelDecl : D)
864 handleTopLevelDecl(TopLevelDecl);
868 // We're not interested in "interesting" decls.
869 void HandleInterestingDecl(DeclGroupRef) override {}
871 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
872 for (Decl *TopLevelDecl : D)
873 handleTopLevelDecl(TopLevelDecl);
876 ASTMutationListener *GetASTMutationListener() override {
877 return Unit.getASTMutationListener();
880 ASTDeserializationListener *GetASTDeserializationListener() override {
881 return Unit.getDeserializationListener();
885 class TopLevelDeclTrackerAction : public ASTFrontendAction {
889 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
890 StringRef InFile) override {
891 CI.getPreprocessor().addPPCallbacks(
892 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
893 Unit.getCurrentTopLevelHashValue()));
894 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
895 Unit, Unit.getCurrentTopLevelHashValue());
899 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
901 bool hasCodeCompletionSupport() const override { return false; }
902 TranslationUnitKind getTranslationUnitKind() override {
903 return Unit.getTranslationUnitKind();
907 class PrecompilePreambleAction : public ASTFrontendAction {
909 bool HasEmittedPreamblePCH;
912 explicit PrecompilePreambleAction(ASTUnit &Unit)
913 : Unit(Unit), HasEmittedPreamblePCH(false) {}
915 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
916 StringRef InFile) override;
917 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
918 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
919 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
921 bool hasCodeCompletionSupport() const override { return false; }
922 bool hasASTFileSupport() const override { return false; }
923 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
926 class PrecompilePreambleConsumer : public PCHGenerator {
929 std::vector<Decl *> TopLevelDecls;
930 PrecompilePreambleAction *Action;
931 std::unique_ptr<raw_ostream> Out;
934 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
935 const Preprocessor &PP, StringRef isysroot,
936 std::unique_ptr<raw_ostream> Out)
937 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
938 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
939 /*AllowASTWithErrors=*/true),
940 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
941 Out(std::move(Out)) {
945 bool HandleTopLevelDecl(DeclGroupRef DG) override {
947 // FIXME: Currently ObjC method declarations are incorrectly being
948 // reported as top-level declarations, even though their DeclContext
949 // is the containing ObjC @interface/@implementation. This is a
950 // fundamental problem in the parser right now.
951 if (isa<ObjCMethodDecl>(D))
953 AddTopLevelDeclarationToHash(D, Hash);
954 TopLevelDecls.push_back(D);
959 void HandleTranslationUnit(ASTContext &Ctx) override {
960 PCHGenerator::HandleTranslationUnit(Ctx);
961 if (hasEmittedPCH()) {
962 // Write the generated bitstream to "Out".
964 // Make sure it hits disk now.
967 llvm::SmallVector<char, 0> Empty;
968 getPCH() = std::move(Empty);
970 // Translate the top-level declarations we captured during
971 // parsing into declaration IDs in the precompiled
972 // preamble. This will allow us to deserialize those top-level
973 // declarations when requested.
974 for (Decl *D : TopLevelDecls) {
975 // Invalid top-level decls may not have been serialized.
976 if (D->isInvalidDecl())
978 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
981 Action->setHasEmittedPreamblePCH();
986 } // anonymous namespace
988 std::unique_ptr<ASTConsumer>
989 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
992 std::string OutputFile;
993 std::unique_ptr<raw_ostream> OS =
994 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
999 if (!CI.getFrontendOpts().RelocatablePCH)
1002 CI.getPreprocessor().addPPCallbacks(
1003 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1004 Unit.getCurrentTopLevelHashValue()));
1005 return llvm::make_unique<PrecompilePreambleConsumer>(
1006 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
1009 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1010 return StoredDiag.getLocation().isValid();
1014 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1015 // Get rid of stored diagnostics except the ones from the driver which do not
1016 // have a source location.
1018 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1022 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1024 SourceManager &SM) {
1025 // The stored diagnostic has the old source manager in it; update
1026 // the locations to refer into the new source manager. Since we've
1027 // been careful to make sure that the source manager's state
1028 // before and after are identical, so that we can reuse the source
1030 for (StoredDiagnostic &SD : StoredDiagnostics) {
1031 if (SD.getLocation().isValid()) {
1032 FullSourceLoc Loc(SD.getLocation(), SM);
1033 SD.setLocation(Loc);
1038 /// Parse the source file into a translation unit using the given compiler
1039 /// invocation, replacing the current translation unit.
1041 /// \returns True if a failure occurred that causes the ASTUnit not to
1042 /// contain any translation-unit information, false otherwise.
1043 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1044 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1045 SavedMainFileBuffer.reset();
1050 // Create the compiler instance to use for building the AST.
1051 std::unique_ptr<CompilerInstance> Clang(
1052 new CompilerInstance(std::move(PCHContainerOps)));
1054 // Recover resources if we crash before exiting this method.
1055 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1056 CICleanup(Clang.get());
1058 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1059 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1061 // Set up diagnostics, capturing any diagnostics that would
1062 // otherwise be dropped.
1063 Clang->setDiagnostics(&getDiagnostics());
1065 // Create the target instance.
1066 Clang->setTarget(TargetInfo::CreateTargetInfo(
1067 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1068 if (!Clang->hasTarget())
1071 // Inform the target of the language options.
1073 // FIXME: We shouldn't need to do this, the target should be immutable once
1074 // created. This complexity should be lifted elsewhere.
1075 Clang->getTarget().adjust(Clang->getLangOpts());
1077 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1078 "Invocation must have exactly one source file!");
1079 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1080 "FIXME: AST inputs not yet supported here!");
1081 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1082 "IR inputs not support here!");
1084 // Configure the various subsystems.
1085 LangOpts = Clang->getInvocation().LangOpts;
1086 FileSystemOpts = Clang->getFileSystemOpts();
1088 Clang->createFileManager();
1089 FileMgr = &Clang->getFileManager();
1091 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1092 UserFilesAreVolatile);
1098 // Clear out old caches and data.
1099 TopLevelDecls.clear();
1100 clearFileLevelDecls();
1101 CleanTemporaryFiles();
1103 if (!OverrideMainBuffer) {
1104 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1105 TopLevelDeclsInPreamble.clear();
1108 // Create a file manager object to provide access to and cache the filesystem.
1109 Clang->setFileManager(&getFileManager());
1111 // Create the source manager.
1112 Clang->setSourceManager(&getSourceManager());
1114 // If the main file has been overridden due to the use of a preamble,
1115 // make that override happen and introduce the preamble.
1116 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1117 if (OverrideMainBuffer) {
1118 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1119 OverrideMainBuffer.get());
1120 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1121 PreprocessorOpts.PrecompiledPreambleBytes.second
1122 = PreambleEndsAtStartOfLine;
1123 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1124 PreprocessorOpts.DisablePCHValidation = true;
1126 // The stored diagnostic has the old source manager in it; update
1127 // the locations to refer into the new source manager. Since we've
1128 // been careful to make sure that the source manager's state
1129 // before and after are identical, so that we can reuse the source
1131 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1133 // Keep track of the override buffer;
1134 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1137 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1138 new TopLevelDeclTrackerAction(*this));
1140 // Recover resources if we crash before exiting this method.
1141 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1142 ActCleanup(Act.get());
1144 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1147 if (SavedMainFileBuffer)
1148 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1149 PreambleDiagnostics, StoredDiagnostics);
1151 if (!Act->Execute())
1154 transferASTDataFromCompilerInstance(*Clang);
1156 Act->EndSourceFile();
1158 FailedParseDiagnostics.clear();
1163 // Remove the overridden buffer we used for the preamble.
1164 SavedMainFileBuffer = nullptr;
1166 // Keep the ownership of the data in the ASTUnit because the client may
1167 // want to see the diagnostics.
1168 transferASTDataFromCompilerInstance(*Clang);
1169 FailedParseDiagnostics.swap(StoredDiagnostics);
1170 StoredDiagnostics.clear();
1171 NumStoredDiagnosticsFromDriver = 0;
1175 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1176 static std::string GetPreamblePCHPath() {
1177 // FIXME: This is a hack so that we can override the preamble file during
1178 // crash-recovery testing, which is the only case where the preamble files
1179 // are not necessarily cleaned up.
1180 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1184 SmallString<128> Path;
1185 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1190 /// \brief Compute the preamble for the main file, providing the source buffer
1191 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1192 /// that describes the preamble.
1193 ASTUnit::ComputedPreamble
1194 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1195 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1196 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1198 // Try to determine if the main file has been remapped, either from the
1199 // command line (to another file) or directly through the compiler invocation
1200 // (to a memory buffer).
1201 llvm::MemoryBuffer *Buffer = nullptr;
1202 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1203 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1204 llvm::sys::fs::UniqueID MainFileID;
1205 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1206 // Check whether there is a file-file remapping of the main file
1207 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1208 std::string MPath(RF.first);
1209 llvm::sys::fs::UniqueID MID;
1210 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1211 if (MainFileID == MID) {
1212 // We found a remapping. Try to load the resulting, remapped source.
1213 BufferOwner = getBufferForFile(RF.second);
1215 return ComputedPreamble(nullptr, nullptr, 0, true);
1220 // Check whether there is a file-buffer remapping. It supercedes the
1221 // file-file remapping.
1222 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1223 std::string MPath(RB.first);
1224 llvm::sys::fs::UniqueID MID;
1225 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1226 if (MainFileID == MID) {
1227 // We found a remapping.
1228 BufferOwner.reset();
1229 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1235 // If the main source file was not remapped, load it now.
1236 if (!Buffer && !BufferOwner) {
1237 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1239 return ComputedPreamble(nullptr, nullptr, 0, true);
1243 Buffer = BufferOwner.get();
1244 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1245 *Invocation.getLangOpts(), MaxLines);
1246 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1250 ASTUnit::PreambleFileHash
1251 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1252 PreambleFileHash Result;
1254 Result.ModTime = ModTime;
1259 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1260 const llvm::MemoryBuffer *Buffer) {
1261 PreambleFileHash Result;
1262 Result.Size = Buffer->getBufferSize();
1266 MD5Ctx.update(Buffer->getBuffer().data());
1267 MD5Ctx.final(Result.MD5);
1273 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1274 const ASTUnit::PreambleFileHash &RHS) {
1275 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1278 } // namespace clang
1280 static std::pair<unsigned, unsigned>
1281 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1282 const LangOptions &LangOpts) {
1283 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1284 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1285 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1286 return std::make_pair(Offset, EndOffset);
1289 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1290 const LangOptions &LangOpts,
1291 const FixItHint &InFix) {
1292 ASTUnit::StandaloneFixIt OutFix;
1293 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1294 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1296 OutFix.CodeToInsert = InFix.CodeToInsert;
1297 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1301 static ASTUnit::StandaloneDiagnostic
1302 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1303 const StoredDiagnostic &InDiag) {
1304 ASTUnit::StandaloneDiagnostic OutDiag;
1305 OutDiag.ID = InDiag.getID();
1306 OutDiag.Level = InDiag.getLevel();
1307 OutDiag.Message = InDiag.getMessage();
1308 OutDiag.LocOffset = 0;
1309 if (InDiag.getLocation().isInvalid())
1311 const SourceManager &SM = InDiag.getLocation().getManager();
1312 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1313 OutDiag.Filename = SM.getFilename(FileLoc);
1314 if (OutDiag.Filename.empty())
1316 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1317 for (const CharSourceRange &Range : InDiag.getRanges())
1318 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1319 for (const FixItHint &FixIt : InDiag.getFixIts())
1320 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1325 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1326 /// the source file.
1328 /// This routine will compute the preamble of the main source file. If a
1329 /// non-trivial preamble is found, it will precompile that preamble into a
1330 /// precompiled header so that the precompiled preamble can be used to reduce
1331 /// reparsing time. If a precompiled preamble has already been constructed,
1332 /// this routine will determine if it is still valid and, if so, avoid
1333 /// rebuilding the precompiled preamble.
1335 /// \param AllowRebuild When true (the default), this routine is
1336 /// allowed to rebuild the precompiled preamble if it is found to be
1339 /// \param MaxLines When non-zero, the maximum number of lines that
1340 /// can occur within the preamble.
1342 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1343 /// buffer that should be used in place of the main file when doing so.
1344 /// Otherwise, returns a NULL pointer.
1345 std::unique_ptr<llvm::MemoryBuffer>
1346 ASTUnit::getMainBufferWithPrecompiledPreamble(
1347 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1348 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1349 unsigned MaxLines) {
1351 auto PreambleInvocation =
1352 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1353 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1354 PreprocessorOptions &PreprocessorOpts
1355 = PreambleInvocation->getPreprocessorOpts();
1357 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1359 if (!NewPreamble.Size) {
1360 // We couldn't find a preamble in the main source. Clear out the current
1361 // preamble, if we have one. It's obviously no good any more.
1363 erasePreambleFile(this);
1365 // The next time we actually see a preamble, precompile it.
1366 PreambleRebuildCounter = 1;
1370 if (!Preamble.empty()) {
1371 // We've previously computed a preamble. Check whether we have the same
1372 // preamble now that we did before, and that there's enough space in
1373 // the main-file buffer within the precompiled preamble to fit the
1375 if (Preamble.size() == NewPreamble.Size &&
1376 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1377 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1378 NewPreamble.Size) == 0) {
1379 // The preamble has not changed. We may be able to re-use the precompiled
1382 // Check that none of the files used by the preamble have changed.
1383 bool AnyFileChanged = false;
1385 // First, make a record of those files that have been overridden via
1386 // remapping or unsaved_files.
1387 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1388 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1393 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1394 // If we can't stat the file we're remapping to, assume that something
1395 // horrible happened.
1396 AnyFileChanged = true;
1400 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1402 llvm::sys::toTimeT(Status.getLastModificationTime()));
1405 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1410 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1411 AnyFileChanged = true;
1415 OverriddenFiles[Status.getUniqueID()] =
1416 PreambleFileHash::createForMemoryBuffer(RB.second);
1419 // Check whether anything has changed.
1420 for (llvm::StringMap<PreambleFileHash>::iterator
1421 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1422 !AnyFileChanged && F != FEnd;
1425 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1426 // If we can't stat the file, assume that something horrible happened.
1427 AnyFileChanged = true;
1431 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1432 = OverriddenFiles.find(Status.getUniqueID());
1433 if (Overridden != OverriddenFiles.end()) {
1434 // This file was remapped; check whether the newly-mapped file
1435 // matches up with the previous mapping.
1436 if (Overridden->second != F->second)
1437 AnyFileChanged = true;
1441 // The file was not remapped; check whether it has changed on disk.
1442 if (Status.getSize() != uint64_t(F->second.Size) ||
1443 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1445 AnyFileChanged = true;
1448 if (!AnyFileChanged) {
1449 // Okay! We can re-use the precompiled preamble.
1451 // Set the state of the diagnostic object to mimic its state
1452 // after parsing the preamble.
1453 getDiagnostics().Reset();
1454 ProcessWarningOptions(getDiagnostics(),
1455 PreambleInvocation->getDiagnosticOpts());
1456 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1458 return llvm::MemoryBuffer::getMemBufferCopy(
1459 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1463 // If we aren't allowed to rebuild the precompiled preamble, just
1468 // We can't reuse the previously-computed preamble. Build a new one.
1470 PreambleDiagnostics.clear();
1471 erasePreambleFile(this);
1472 PreambleRebuildCounter = 1;
1473 } else if (!AllowRebuild) {
1474 // We aren't allowed to rebuild the precompiled preamble; just
1479 // If the preamble rebuild counter > 1, it's because we previously
1480 // failed to build a preamble and we're not yet ready to try
1481 // again. Decrement the counter and return a failure.
1482 if (PreambleRebuildCounter > 1) {
1483 --PreambleRebuildCounter;
1487 // Create a temporary file for the precompiled preamble. In rare
1488 // circumstances, this can fail.
1489 std::string PreamblePCHPath = GetPreamblePCHPath();
1490 if (PreamblePCHPath.empty()) {
1491 // Try again next time.
1492 PreambleRebuildCounter = 1;
1496 // We did not previously compute a preamble, or it can't be reused anyway.
1497 SimpleTimer PreambleTimer(WantTiming);
1498 PreambleTimer.setOutput("Precompiling preamble");
1500 // Save the preamble text for later; we'll need to compare against it for
1501 // subsequent reparses.
1502 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1503 Preamble.assign(FileMgr->getFile(MainFilename),
1504 NewPreamble.Buffer->getBufferStart(),
1505 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1506 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1508 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1509 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1511 // Remap the main source file to the preamble buffer.
1512 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1513 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1515 // Tell the compiler invocation to generate a temporary precompiled header.
1516 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1517 // FIXME: Generate the precompiled header into memory?
1518 FrontendOpts.OutputFile = PreamblePCHPath;
1519 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1520 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1522 // Create the compiler instance to use for building the precompiled preamble.
1523 std::unique_ptr<CompilerInstance> Clang(
1524 new CompilerInstance(std::move(PCHContainerOps)));
1526 // Recover resources if we crash before exiting this method.
1527 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1528 CICleanup(Clang.get());
1530 Clang->setInvocation(std::move(PreambleInvocation));
1531 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1533 // Set up diagnostics, capturing all of the diagnostics produced.
1534 Clang->setDiagnostics(&getDiagnostics());
1536 // Create the target instance.
1537 Clang->setTarget(TargetInfo::CreateTargetInfo(
1538 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1539 if (!Clang->hasTarget()) {
1540 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1542 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1543 PreprocessorOpts.RemappedFileBuffers.pop_back();
1547 // Inform the target of the language options.
1549 // FIXME: We shouldn't need to do this, the target should be immutable once
1550 // created. This complexity should be lifted elsewhere.
1551 Clang->getTarget().adjust(Clang->getLangOpts());
1553 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1554 "Invocation must have exactly one source file!");
1555 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1556 "FIXME: AST inputs not yet supported here!");
1557 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1558 "IR inputs not support here!");
1560 // Clear out old caches and data.
1561 getDiagnostics().Reset();
1562 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1563 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1564 TopLevelDecls.clear();
1565 TopLevelDeclsInPreamble.clear();
1566 PreambleDiagnostics.clear();
1568 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1569 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1573 // Create a file manager object to provide access to and cache the filesystem.
1574 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1576 // Create the source manager.
1577 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1578 Clang->getFileManager()));
1580 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1581 Clang->addDependencyCollector(PreambleDepCollector);
1583 std::unique_ptr<PrecompilePreambleAction> Act;
1584 Act.reset(new PrecompilePreambleAction(*this));
1585 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1586 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1588 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1589 PreprocessorOpts.RemappedFileBuffers.pop_back();
1595 // Transfer any diagnostics generated when parsing the preamble into the set
1596 // of preamble diagnostics.
1597 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1598 E = stored_diag_end();
1600 PreambleDiagnostics.push_back(
1601 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1603 Act->EndSourceFile();
1605 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1607 if (!Act->hasEmittedPreamblePCH()) {
1608 // The preamble PCH failed (e.g. there was a module loading fatal error),
1609 // so no precompiled header was generated. Forget that we even tried.
1610 // FIXME: Should we leave a note for ourselves to try again?
1611 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1613 TopLevelDeclsInPreamble.clear();
1614 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1615 PreprocessorOpts.RemappedFileBuffers.pop_back();
1619 // Keep track of the preamble we precompiled.
1620 setPreambleFile(this, FrontendOpts.OutputFile);
1621 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1623 // Keep track of all of the files that the source manager knows about,
1624 // so we can verify whether they have changed or not.
1625 FilesInPreamble.clear();
1626 SourceManager &SourceMgr = Clang->getSourceManager();
1627 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1628 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1629 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1631 if (time_t ModTime = File->getModificationTime()) {
1632 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1633 File->getSize(), ModTime);
1635 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1636 FilesInPreamble[File->getName()] =
1637 PreambleFileHash::createForMemoryBuffer(Buffer);
1641 PreambleRebuildCounter = 1;
1642 PreprocessorOpts.RemappedFileBuffers.pop_back();
1644 // If the hash of top-level entities differs from the hash of the top-level
1645 // entities the last time we rebuilt the preamble, clear out the completion
1647 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1648 CompletionCacheTopLevelHashValue = 0;
1649 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1652 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1656 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1657 std::vector<Decl *> Resolved;
1658 Resolved.reserve(TopLevelDeclsInPreamble.size());
1659 ExternalASTSource &Source = *getASTContext().getExternalSource();
1660 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1661 // Resolve the declaration ID to an actual declaration, possibly
1662 // deserializing the declaration in the process.
1663 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1664 Resolved.push_back(D);
1666 TopLevelDeclsInPreamble.clear();
1667 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1670 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1671 // Steal the created target, context, and preprocessor if they have been
1673 assert(CI.hasInvocation() && "missing invocation");
1674 LangOpts = CI.getInvocation().LangOpts;
1675 TheSema = CI.takeSema();
1676 Consumer = CI.takeASTConsumer();
1677 if (CI.hasASTContext())
1678 Ctx = &CI.getASTContext();
1679 if (CI.hasPreprocessor())
1680 PP = CI.getPreprocessorPtr();
1681 CI.setSourceManager(nullptr);
1682 CI.setFileManager(nullptr);
1684 Target = &CI.getTarget();
1685 Reader = CI.getModuleManager();
1686 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1689 StringRef ASTUnit::getMainFileName() const {
1690 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1691 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1693 return Input.getFile();
1695 return Input.getBuffer()->getBufferIdentifier();
1699 if (const FileEntry *
1700 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1701 return FE->getName();
1707 StringRef ASTUnit::getASTFileName() const {
1708 if (!isMainFileAST())
1711 serialization::ModuleFile &
1712 Mod = Reader->getModuleManager().getPrimaryModule();
1713 return Mod.FileName;
1716 std::unique_ptr<ASTUnit>
1717 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1718 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1719 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1720 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1721 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1722 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1723 createVFSFromCompilerInvocation(*CI, *Diags);
1726 AST->Diagnostics = Diags;
1727 AST->FileSystemOpts = CI->getFileSystemOpts();
1728 AST->Invocation = std::move(CI);
1729 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1730 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1731 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1732 UserFilesAreVolatile);
1733 AST->PCMCache = new MemoryBufferCache;
1738 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1739 std::shared_ptr<CompilerInvocation> CI,
1740 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1741 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1742 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1743 bool OnlyLocalDecls, bool CaptureDiagnostics,
1744 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1745 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1746 std::unique_ptr<ASTUnit> *ErrAST) {
1747 assert(CI && "A CompilerInvocation is required");
1749 std::unique_ptr<ASTUnit> OwnAST;
1750 ASTUnit *AST = Unit;
1752 // Create the AST unit.
1753 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1759 if (!ResourceFilesPath.empty()) {
1760 // Override the resources path.
1761 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1763 AST->OnlyLocalDecls = OnlyLocalDecls;
1764 AST->CaptureDiagnostics = CaptureDiagnostics;
1765 if (PrecompilePreambleAfterNParses > 0)
1766 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1767 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1768 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1769 AST->IncludeBriefCommentsInCodeCompletion
1770 = IncludeBriefCommentsInCodeCompletion;
1772 // Recover resources if we crash before exiting this method.
1773 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1774 ASTUnitCleanup(OwnAST.get());
1775 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1776 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1777 DiagCleanup(Diags.get());
1779 // We'll manage file buffers ourselves.
1780 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1781 CI->getFrontendOpts().DisableFree = false;
1782 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1784 // Create the compiler instance to use for building the AST.
1785 std::unique_ptr<CompilerInstance> Clang(
1786 new CompilerInstance(std::move(PCHContainerOps)));
1788 // Recover resources if we crash before exiting this method.
1789 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1790 CICleanup(Clang.get());
1792 Clang->setInvocation(std::move(CI));
1793 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1795 // Set up diagnostics, capturing any diagnostics that would
1796 // otherwise be dropped.
1797 Clang->setDiagnostics(&AST->getDiagnostics());
1799 // Create the target instance.
1800 Clang->setTarget(TargetInfo::CreateTargetInfo(
1801 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1802 if (!Clang->hasTarget())
1805 // Inform the target of the language options.
1807 // FIXME: We shouldn't need to do this, the target should be immutable once
1808 // created. This complexity should be lifted elsewhere.
1809 Clang->getTarget().adjust(Clang->getLangOpts());
1811 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1812 "Invocation must have exactly one source file!");
1813 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1814 "FIXME: AST inputs not yet supported here!");
1815 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1816 "IR inputs not supported here!");
1818 // Configure the various subsystems.
1819 AST->TheSema.reset();
1822 AST->Reader = nullptr;
1824 // Create a file manager object to provide access to and cache the filesystem.
1825 Clang->setFileManager(&AST->getFileManager());
1827 // Create the source manager.
1828 Clang->setSourceManager(&AST->getSourceManager());
1830 FrontendAction *Act = Action;
1832 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1834 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1835 Act = TrackerAct.get();
1838 // Recover resources if we crash before exiting this method.
1839 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1840 ActCleanup(TrackerAct.get());
1842 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1843 AST->transferASTDataFromCompilerInstance(*Clang);
1844 if (OwnAST && ErrAST)
1845 ErrAST->swap(OwnAST);
1850 if (Persistent && !TrackerAct) {
1851 Clang->getPreprocessor().addPPCallbacks(
1852 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1853 AST->getCurrentTopLevelHashValue()));
1854 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1855 if (Clang->hasASTConsumer())
1856 Consumers.push_back(Clang->takeASTConsumer());
1857 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1858 *AST, AST->getCurrentTopLevelHashValue()));
1859 Clang->setASTConsumer(
1860 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1862 if (!Act->Execute()) {
1863 AST->transferASTDataFromCompilerInstance(*Clang);
1864 if (OwnAST && ErrAST)
1865 ErrAST->swap(OwnAST);
1870 // Steal the created target, context, and preprocessor.
1871 AST->transferASTDataFromCompilerInstance(*Clang);
1873 Act->EndSourceFile();
1876 return OwnAST.release();
1881 bool ASTUnit::LoadFromCompilerInvocation(
1882 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1883 unsigned PrecompilePreambleAfterNParses) {
1887 // We'll manage file buffers ourselves.
1888 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1889 Invocation->getFrontendOpts().DisableFree = false;
1890 getDiagnostics().Reset();
1891 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1893 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1894 if (PrecompilePreambleAfterNParses > 0) {
1895 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1896 OverrideMainBuffer =
1897 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1898 getDiagnostics().Reset();
1899 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1902 SimpleTimer ParsingTimer(WantTiming);
1903 ParsingTimer.setOutput("Parsing " + getMainFileName());
1905 // Recover resources if we crash before exiting this method.
1906 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1907 MemBufferCleanup(OverrideMainBuffer.get());
1909 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1912 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1913 std::shared_ptr<CompilerInvocation> CI,
1914 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1915 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1916 bool OnlyLocalDecls, bool CaptureDiagnostics,
1917 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1918 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1919 bool UserFilesAreVolatile) {
1920 // Create the AST unit.
1921 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1922 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1923 AST->Diagnostics = Diags;
1924 AST->OnlyLocalDecls = OnlyLocalDecls;
1925 AST->CaptureDiagnostics = CaptureDiagnostics;
1926 AST->TUKind = TUKind;
1927 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1928 AST->IncludeBriefCommentsInCodeCompletion
1929 = IncludeBriefCommentsInCodeCompletion;
1930 AST->Invocation = std::move(CI);
1931 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1932 AST->FileMgr = FileMgr;
1933 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1935 // Recover resources if we crash before exiting this method.
1936 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1937 ASTUnitCleanup(AST.get());
1938 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1939 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1940 DiagCleanup(Diags.get());
1942 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1943 PrecompilePreambleAfterNParses))
1948 ASTUnit *ASTUnit::LoadFromCommandLine(
1949 const char **ArgBegin, const char **ArgEnd,
1950 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1951 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1952 bool OnlyLocalDecls, bool CaptureDiagnostics,
1953 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1954 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1955 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1956 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1957 bool UserFilesAreVolatile, bool ForSerialization,
1958 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
1959 assert(Diags.get() && "no DiagnosticsEngine was provided");
1961 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1963 std::shared_ptr<CompilerInvocation> CI;
1967 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1970 CI = clang::createInvocationFromCommandLine(
1971 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1976 // Override any files that need remapping
1977 for (const auto &RemappedFile : RemappedFiles) {
1978 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1979 RemappedFile.second);
1981 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1982 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1983 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1985 // Override the resources path.
1986 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1988 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1991 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1993 // Create the AST unit.
1994 std::unique_ptr<ASTUnit> AST;
1995 AST.reset(new ASTUnit(false));
1996 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1997 AST->Diagnostics = Diags;
1998 AST->FileSystemOpts = CI->getFileSystemOpts();
1999 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2000 createVFSFromCompilerInvocation(*CI, *Diags);
2003 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
2004 AST->PCMCache = new MemoryBufferCache;
2005 AST->OnlyLocalDecls = OnlyLocalDecls;
2006 AST->CaptureDiagnostics = CaptureDiagnostics;
2007 AST->TUKind = TUKind;
2008 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2009 AST->IncludeBriefCommentsInCodeCompletion
2010 = IncludeBriefCommentsInCodeCompletion;
2011 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2012 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2013 AST->StoredDiagnostics.swap(StoredDiagnostics);
2014 AST->Invocation = CI;
2015 if (ForSerialization)
2016 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2017 // Zero out now to ease cleanup during crash recovery.
2021 // Recover resources if we crash before exiting this method.
2022 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2023 ASTUnitCleanup(AST.get());
2025 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2026 PrecompilePreambleAfterNParses)) {
2027 // Some error occurred, if caller wants to examine diagnostics, pass it the
2030 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2036 return AST.release();
2039 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2040 ArrayRef<RemappedFile> RemappedFiles) {
2044 clearFileLevelDecls();
2046 SimpleTimer ParsingTimer(WantTiming);
2047 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2050 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2051 for (const auto &RB : PPOpts.RemappedFileBuffers)
2054 Invocation->getPreprocessorOpts().clearRemappedFiles();
2055 for (const auto &RemappedFile : RemappedFiles) {
2056 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2057 RemappedFile.second);
2060 // If we have a preamble file lying around, or if we might try to
2061 // build a precompiled preamble, do so now.
2062 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2063 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2064 OverrideMainBuffer =
2065 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2067 // Clear out the diagnostics state.
2069 getDiagnostics().Reset();
2070 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2071 if (OverrideMainBuffer)
2072 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2074 // Parse the sources
2076 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2078 // If we're caching global code-completion results, and the top-level
2079 // declarations have changed, clear out the code-completion cache.
2080 if (!Result && ShouldCacheCodeCompletionResults &&
2081 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2082 CacheCodeCompletionResults();
2084 // We now need to clear out the completion info related to this translation
2085 // unit; it'll be recreated if necessary.
2091 //----------------------------------------------------------------------------//
2093 //----------------------------------------------------------------------------//
2096 /// \brief Code completion consumer that combines the cached code-completion
2097 /// results from an ASTUnit with the code-completion results provided to it,
2098 /// then passes the result on to
2099 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2100 uint64_t NormalContexts;
2102 CodeCompleteConsumer &Next;
2105 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2106 const CodeCompleteOptions &CodeCompleteOpts)
2107 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2108 AST(AST), Next(Next)
2110 // Compute the set of contexts in which we will look when we don't have
2111 // any information about the specific context.
2113 = (1LL << CodeCompletionContext::CCC_TopLevel)
2114 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2115 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2116 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2117 | (1LL << CodeCompletionContext::CCC_Statement)
2118 | (1LL << CodeCompletionContext::CCC_Expression)
2119 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2120 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2121 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2122 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2123 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2124 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2125 | (1LL << CodeCompletionContext::CCC_Recovery);
2127 if (AST.getASTContext().getLangOpts().CPlusPlus)
2128 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2129 | (1LL << CodeCompletionContext::CCC_UnionTag)
2130 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2133 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2134 CodeCompletionResult *Results,
2135 unsigned NumResults) override;
2137 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2138 OverloadCandidate *Candidates,
2139 unsigned NumCandidates) override {
2140 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2143 CodeCompletionAllocator &getAllocator() override {
2144 return Next.getAllocator();
2147 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2148 return Next.getCodeCompletionTUInfo();
2151 } // anonymous namespace
2153 /// \brief Helper function that computes which global names are hidden by the
2154 /// local code-completion results.
2155 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2156 CodeCompletionResult *Results,
2157 unsigned NumResults,
2159 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2160 bool OnlyTagNames = false;
2161 switch (Context.getKind()) {
2162 case CodeCompletionContext::CCC_Recovery:
2163 case CodeCompletionContext::CCC_TopLevel:
2164 case CodeCompletionContext::CCC_ObjCInterface:
2165 case CodeCompletionContext::CCC_ObjCImplementation:
2166 case CodeCompletionContext::CCC_ObjCIvarList:
2167 case CodeCompletionContext::CCC_ClassStructUnion:
2168 case CodeCompletionContext::CCC_Statement:
2169 case CodeCompletionContext::CCC_Expression:
2170 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2171 case CodeCompletionContext::CCC_DotMemberAccess:
2172 case CodeCompletionContext::CCC_ArrowMemberAccess:
2173 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2174 case CodeCompletionContext::CCC_Namespace:
2175 case CodeCompletionContext::CCC_Type:
2176 case CodeCompletionContext::CCC_Name:
2177 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2178 case CodeCompletionContext::CCC_ParenthesizedExpression:
2179 case CodeCompletionContext::CCC_ObjCInterfaceName:
2182 case CodeCompletionContext::CCC_EnumTag:
2183 case CodeCompletionContext::CCC_UnionTag:
2184 case CodeCompletionContext::CCC_ClassOrStructTag:
2185 OnlyTagNames = true;
2188 case CodeCompletionContext::CCC_ObjCProtocolName:
2189 case CodeCompletionContext::CCC_MacroName:
2190 case CodeCompletionContext::CCC_MacroNameUse:
2191 case CodeCompletionContext::CCC_PreprocessorExpression:
2192 case CodeCompletionContext::CCC_PreprocessorDirective:
2193 case CodeCompletionContext::CCC_NaturalLanguage:
2194 case CodeCompletionContext::CCC_SelectorName:
2195 case CodeCompletionContext::CCC_TypeQualifiers:
2196 case CodeCompletionContext::CCC_Other:
2197 case CodeCompletionContext::CCC_OtherWithMacros:
2198 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2199 case CodeCompletionContext::CCC_ObjCClassMessage:
2200 case CodeCompletionContext::CCC_ObjCCategoryName:
2201 // We're looking for nothing, or we're looking for names that cannot
2206 typedef CodeCompletionResult Result;
2207 for (unsigned I = 0; I != NumResults; ++I) {
2208 if (Results[I].Kind != Result::RK_Declaration)
2212 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2214 bool Hiding = false;
2216 Hiding = (IDNS & Decl::IDNS_Tag);
2218 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2219 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2220 Decl::IDNS_NonMemberOperator);
2221 if (Ctx.getLangOpts().CPlusPlus)
2222 HiddenIDNS |= Decl::IDNS_Tag;
2223 Hiding = (IDNS & HiddenIDNS);
2229 DeclarationName Name = Results[I].Declaration->getDeclName();
2230 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2231 HiddenNames.insert(Identifier->getName());
2233 HiddenNames.insert(Name.getAsString());
2237 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2238 CodeCompletionContext Context,
2239 CodeCompletionResult *Results,
2240 unsigned NumResults) {
2241 // Merge the results we were given with the results we cached.
2242 bool AddedResult = false;
2243 uint64_t InContexts =
2244 Context.getKind() == CodeCompletionContext::CCC_Recovery
2245 ? NormalContexts : (1LL << Context.getKind());
2246 // Contains the set of names that are hidden by "local" completion results.
2247 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2248 typedef CodeCompletionResult Result;
2249 SmallVector<Result, 8> AllResults;
2250 for (ASTUnit::cached_completion_iterator
2251 C = AST.cached_completion_begin(),
2252 CEnd = AST.cached_completion_end();
2254 // If the context we are in matches any of the contexts we are
2255 // interested in, we'll add this result.
2256 if ((C->ShowInContexts & InContexts) == 0)
2259 // If we haven't added any results previously, do so now.
2261 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2263 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2267 // Determine whether this global completion result is hidden by a local
2268 // completion result. If so, skip it.
2269 if (C->Kind != CXCursor_MacroDefinition &&
2270 HiddenNames.count(C->Completion->getTypedText()))
2273 // Adjust priority based on similar type classes.
2274 unsigned Priority = C->Priority;
2275 CodeCompletionString *Completion = C->Completion;
2276 if (!Context.getPreferredType().isNull()) {
2277 if (C->Kind == CXCursor_MacroDefinition) {
2278 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2280 Context.getPreferredType()->isAnyPointerType());
2281 } else if (C->Type) {
2282 CanQualType Expected
2283 = S.Context.getCanonicalType(
2284 Context.getPreferredType().getUnqualifiedType());
2285 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2286 if (ExpectedSTC == C->TypeClass) {
2287 // We know this type is similar; check for an exact match.
2288 llvm::StringMap<unsigned> &CachedCompletionTypes
2289 = AST.getCachedCompletionTypes();
2290 llvm::StringMap<unsigned>::iterator Pos
2291 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2292 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2293 Priority /= CCF_ExactTypeMatch;
2295 Priority /= CCF_SimilarTypeMatch;
2300 // Adjust the completion string, if required.
2301 if (C->Kind == CXCursor_MacroDefinition &&
2302 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2303 // Create a new code-completion string that just contains the
2304 // macro name, without its arguments.
2305 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2306 CCP_CodePattern, C->Availability);
2307 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2308 Priority = CCP_CodePattern;
2309 Completion = Builder.TakeString();
2312 AllResults.push_back(Result(Completion, Priority, C->Kind,
2316 // If we did not add any cached completion results, just forward the
2317 // results we were given to the next consumer.
2319 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2323 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2327 void ASTUnit::CodeComplete(
2328 StringRef File, unsigned Line, unsigned Column,
2329 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2330 bool IncludeCodePatterns, bool IncludeBriefComments,
2331 CodeCompleteConsumer &Consumer,
2332 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2333 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2334 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2335 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2339 SimpleTimer CompletionTimer(WantTiming);
2340 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2341 Twine(Line) + ":" + Twine(Column));
2343 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2345 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2346 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2347 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2349 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2350 CachedCompletionResults.empty();
2351 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2352 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2353 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2355 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2357 FrontendOpts.CodeCompletionAt.FileName = File;
2358 FrontendOpts.CodeCompletionAt.Line = Line;
2359 FrontendOpts.CodeCompletionAt.Column = Column;
2361 // Set the language options appropriately.
2362 LangOpts = *CCInvocation->getLangOpts();
2364 // Spell-checking and warnings are wasteful during code-completion.
2365 LangOpts.SpellChecking = false;
2366 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2368 std::unique_ptr<CompilerInstance> Clang(
2369 new CompilerInstance(PCHContainerOps));
2371 // Recover resources if we crash before exiting this method.
2372 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2373 CICleanup(Clang.get());
2375 auto &Inv = *CCInvocation;
2376 Clang->setInvocation(std::move(CCInvocation));
2377 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2379 // Set up diagnostics, capturing any diagnostics produced.
2380 Clang->setDiagnostics(&Diag);
2381 CaptureDroppedDiagnostics Capture(true,
2382 Clang->getDiagnostics(),
2384 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2386 // Create the target instance.
2387 Clang->setTarget(TargetInfo::CreateTargetInfo(
2388 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2389 if (!Clang->hasTarget()) {
2390 Clang->setInvocation(nullptr);
2394 // Inform the target of the language options.
2396 // FIXME: We shouldn't need to do this, the target should be immutable once
2397 // created. This complexity should be lifted elsewhere.
2398 Clang->getTarget().adjust(Clang->getLangOpts());
2400 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2401 "Invocation must have exactly one source file!");
2402 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2403 "FIXME: AST inputs not yet supported here!");
2404 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2405 "IR inputs not support here!");
2408 // Use the source and file managers that we were given.
2409 Clang->setFileManager(&FileMgr);
2410 Clang->setSourceManager(&SourceMgr);
2413 PreprocessorOpts.clearRemappedFiles();
2414 PreprocessorOpts.RetainRemappedFileBuffers = true;
2415 for (const auto &RemappedFile : RemappedFiles) {
2416 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2417 OwnedBuffers.push_back(RemappedFile.second);
2420 // Use the code completion consumer we were given, but adding any cached
2421 // code-completion results.
2422 AugmentedCodeCompleteConsumer *AugmentedConsumer
2423 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2424 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2426 // If we have a precompiled preamble, try to use it. We only allow
2427 // the use of the precompiled preamble if we're if the completion
2428 // point is within the main file, after the end of the precompiled
2430 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2431 if (!getPreambleFile(this).empty()) {
2432 std::string CompleteFilePath(File);
2433 llvm::sys::fs::UniqueID CompleteFileID;
2435 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2436 std::string MainPath(OriginalSourceFile);
2437 llvm::sys::fs::UniqueID MainID;
2438 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2439 if (CompleteFileID == MainID && Line > 1)
2440 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2441 PCHContainerOps, Inv, false, Line - 1);
2446 // If the main file has been overridden due to the use of a preamble,
2447 // make that override happen and introduce the preamble.
2448 if (OverrideMainBuffer) {
2449 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2450 OverrideMainBuffer.get());
2451 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2452 PreprocessorOpts.PrecompiledPreambleBytes.second
2453 = PreambleEndsAtStartOfLine;
2454 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2455 PreprocessorOpts.DisablePCHValidation = true;
2457 OwnedBuffers.push_back(OverrideMainBuffer.release());
2459 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2460 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2463 // Disable the preprocessing record if modules are not enabled.
2464 if (!Clang->getLangOpts().Modules)
2465 PreprocessorOpts.DetailedRecord = false;
2467 std::unique_ptr<SyntaxOnlyAction> Act;
2468 Act.reset(new SyntaxOnlyAction);
2469 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2471 Act->EndSourceFile();
2475 bool ASTUnit::Save(StringRef File) {
2476 if (HadModuleLoaderFatalFailure)
2479 // Write to a temporary file and later rename it to the actual file, to avoid
2480 // possible race conditions.
2481 SmallString<128> TempPath;
2483 TempPath += "-%%%%%%%%";
2485 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2488 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2489 // unconditionally create a stat cache when we parse the file?
2490 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2494 if (Out.has_error()) {
2499 if (llvm::sys::fs::rename(TempPath, File)) {
2500 llvm::sys::fs::remove(TempPath);
2507 static bool serializeUnit(ASTWriter &Writer,
2508 SmallVectorImpl<char> &Buffer,
2512 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2514 // Write the generated bitstream to "Out".
2515 if (!Buffer.empty())
2516 OS.write(Buffer.data(), Buffer.size());
2521 bool ASTUnit::serialize(raw_ostream &OS) {
2522 // For serialization we are lenient if the errors were only warn-as-error kind.
2523 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2526 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2527 getSema(), hasErrors, OS);
2529 SmallString<128> Buffer;
2530 llvm::BitstreamWriter Stream(Buffer);
2531 MemoryBufferCache PCMCache;
2532 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2533 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2536 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2538 void ASTUnit::TranslateStoredDiagnostics(
2539 FileManager &FileMgr,
2540 SourceManager &SrcMgr,
2541 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2542 SmallVectorImpl<StoredDiagnostic> &Out) {
2543 // Map the standalone diagnostic into the new source manager. We also need to
2544 // remap all the locations to the new view. This includes the diag location,
2545 // any associated source ranges, and the source ranges of associated fix-its.
2546 // FIXME: There should be a cleaner way to do this.
2548 SmallVector<StoredDiagnostic, 4> Result;
2549 Result.reserve(Diags.size());
2550 const FileEntry *PreviousFE = nullptr;
2552 for (const StandaloneDiagnostic &SD : Diags) {
2553 // Rebuild the StoredDiagnostic.
2554 if (SD.Filename.empty())
2556 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2559 if (FE != PreviousFE) {
2560 FID = SrcMgr.translateFile(FE);
2563 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2564 if (FileLoc.isInvalid())
2566 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2567 FullSourceLoc Loc(L, SrcMgr);
2569 SmallVector<CharSourceRange, 4> Ranges;
2570 Ranges.reserve(SD.Ranges.size());
2571 for (const auto &Range : SD.Ranges) {
2572 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2573 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2574 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2577 SmallVector<FixItHint, 2> FixIts;
2578 FixIts.reserve(SD.FixIts.size());
2579 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2580 FixIts.push_back(FixItHint());
2581 FixItHint &FH = FixIts.back();
2582 FH.CodeToInsert = FixIt.CodeToInsert;
2583 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2584 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2585 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2588 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2589 SD.Message, Loc, Ranges, FixIts));
2594 void ASTUnit::addFileLevelDecl(Decl *D) {
2597 // We only care about local declarations.
2598 if (D->isFromASTFile())
2601 SourceManager &SM = *SourceMgr;
2602 SourceLocation Loc = D->getLocation();
2603 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2606 // We only keep track of the file-level declarations of each file.
2607 if (!D->getLexicalDeclContext()->isFileContext())
2610 SourceLocation FileLoc = SM.getFileLoc(Loc);
2611 assert(SM.isLocalSourceLocation(FileLoc));
2614 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2615 if (FID.isInvalid())
2618 LocDeclsTy *&Decls = FileDecls[FID];
2620 Decls = new LocDeclsTy();
2622 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2624 if (Decls->empty() || Decls->back().first <= Offset) {
2625 Decls->push_back(LocDecl);
2629 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2630 LocDecl, llvm::less_first());
2632 Decls->insert(I, LocDecl);
2635 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2636 SmallVectorImpl<Decl *> &Decls) {
2637 if (File.isInvalid())
2640 if (SourceMgr->isLoadedFileID(File)) {
2641 assert(Ctx->getExternalSource() && "No external source!");
2642 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2646 FileDeclsTy::iterator I = FileDecls.find(File);
2647 if (I == FileDecls.end())
2650 LocDeclsTy &LocDecls = *I->second;
2651 if (LocDecls.empty())
2654 LocDeclsTy::iterator BeginIt =
2655 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2656 std::make_pair(Offset, (Decl *)nullptr),
2657 llvm::less_first());
2658 if (BeginIt != LocDecls.begin())
2661 // If we are pointing at a top-level decl inside an objc container, we need
2662 // to backtrack until we find it otherwise we will fail to report that the
2663 // region overlaps with an objc container.
2664 while (BeginIt != LocDecls.begin() &&
2665 BeginIt->second->isTopLevelDeclInObjCContainer())
2668 LocDeclsTy::iterator EndIt = std::upper_bound(
2669 LocDecls.begin(), LocDecls.end(),
2670 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2671 if (EndIt != LocDecls.end())
2674 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2675 Decls.push_back(DIt->second);
2678 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2679 unsigned Line, unsigned Col) const {
2680 const SourceManager &SM = getSourceManager();
2681 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2682 return SM.getMacroArgExpandedLocation(Loc);
2685 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2686 unsigned Offset) const {
2687 const SourceManager &SM = getSourceManager();
2688 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2689 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2692 /// \brief If \arg Loc is a loaded location from the preamble, returns
2693 /// the corresponding local location of the main file, otherwise it returns
2695 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2698 PreambleID = SourceMgr->getPreambleFileID();
2700 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2704 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2705 SourceLocation FileLoc
2706 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2707 return FileLoc.getLocWithOffset(Offs);
2713 /// \brief If \arg Loc is a local location of the main file but inside the
2714 /// preamble chunk, returns the corresponding loaded location from the
2715 /// preamble, otherwise it returns \arg Loc.
2716 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2719 PreambleID = SourceMgr->getPreambleFileID();
2721 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2725 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2726 Offs < Preamble.size()) {
2727 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2728 return FileLoc.getLocWithOffset(Offs);
2734 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2737 FID = SourceMgr->getPreambleFileID();
2739 if (Loc.isInvalid() || FID.isInvalid())
2742 return SourceMgr->isInFileID(Loc, FID);
2745 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2748 FID = SourceMgr->getMainFileID();
2750 if (Loc.isInvalid() || FID.isInvalid())
2753 return SourceMgr->isInFileID(Loc, FID);
2756 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2759 FID = SourceMgr->getPreambleFileID();
2761 if (FID.isInvalid())
2762 return SourceLocation();
2764 return SourceMgr->getLocForEndOfFile(FID);
2767 SourceLocation ASTUnit::getStartOfMainFileID() {
2770 FID = SourceMgr->getMainFileID();
2772 if (FID.isInvalid())
2773 return SourceLocation();
2775 return SourceMgr->getLocForStartOfFile(FID);
2778 llvm::iterator_range<PreprocessingRecord::iterator>
2779 ASTUnit::getLocalPreprocessingEntities() const {
2780 if (isMainFileAST()) {
2781 serialization::ModuleFile &
2782 Mod = Reader->getModuleManager().getPrimaryModule();
2783 return Reader->getModulePreprocessedEntities(Mod);
2786 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2787 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2789 return llvm::make_range(PreprocessingRecord::iterator(),
2790 PreprocessingRecord::iterator());
2793 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2794 if (isMainFileAST()) {
2795 serialization::ModuleFile &
2796 Mod = Reader->getModuleManager().getPrimaryModule();
2797 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2798 if (!Fn(context, D))
2805 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2806 TLEnd = top_level_end();
2807 TL != TLEnd; ++TL) {
2808 if (!Fn(context, *TL))
2815 const FileEntry *ASTUnit::getPCHFile() {
2819 serialization::ModuleFile *Mod = nullptr;
2820 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2822 case serialization::MK_ImplicitModule:
2823 case serialization::MK_ExplicitModule:
2824 case serialization::MK_PrebuiltModule:
2825 return true; // skip dependencies.
2826 case serialization::MK_PCH:
2828 return true; // found it.
2829 case serialization::MK_Preamble:
2830 return false; // look in dependencies.
2831 case serialization::MK_MainFile:
2832 return false; // look in dependencies.
2843 bool ASTUnit::isModuleFile() {
2844 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2847 void ASTUnit::PreambleData::countLines() const {
2852 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2854 if (Buffer.back() != '\n')
2859 ASTUnit::ConcurrencyState::ConcurrencyState() {
2860 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2863 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2864 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2867 void ASTUnit::ConcurrencyState::start() {
2868 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2869 assert(acquired && "Concurrent access to ASTUnit!");
2872 void ASTUnit::ConcurrencyState::finish() {
2873 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2878 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2879 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2880 void ASTUnit::ConcurrencyState::start() {}
2881 void ASTUnit::ConcurrencyState::finish() {}