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().getFormat() ==
1080 InputKind::Source &&
1081 "FIXME: AST inputs not yet supported here!");
1082 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1083 InputKind::LLVM_IR &&
1084 "IR inputs not support here!");
1086 // Configure the various subsystems.
1087 LangOpts = Clang->getInvocation().LangOpts;
1088 FileSystemOpts = Clang->getFileSystemOpts();
1090 Clang->createFileManager();
1091 FileMgr = &Clang->getFileManager();
1093 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1094 UserFilesAreVolatile);
1100 // Clear out old caches and data.
1101 TopLevelDecls.clear();
1102 clearFileLevelDecls();
1103 CleanTemporaryFiles();
1105 if (!OverrideMainBuffer) {
1106 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1107 TopLevelDeclsInPreamble.clear();
1110 // Create a file manager object to provide access to and cache the filesystem.
1111 Clang->setFileManager(&getFileManager());
1113 // Create the source manager.
1114 Clang->setSourceManager(&getSourceManager());
1116 // If the main file has been overridden due to the use of a preamble,
1117 // make that override happen and introduce the preamble.
1118 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1119 if (OverrideMainBuffer) {
1120 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1121 OverrideMainBuffer.get());
1122 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1123 PreprocessorOpts.PrecompiledPreambleBytes.second
1124 = PreambleEndsAtStartOfLine;
1125 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1126 PreprocessorOpts.DisablePCHValidation = true;
1128 // The stored diagnostic has the old source manager in it; update
1129 // the locations to refer into the new source manager. Since we've
1130 // been careful to make sure that the source manager's state
1131 // before and after are identical, so that we can reuse the source
1133 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1135 // Keep track of the override buffer;
1136 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1139 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1140 new TopLevelDeclTrackerAction(*this));
1142 // Recover resources if we crash before exiting this method.
1143 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1144 ActCleanup(Act.get());
1146 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1149 if (SavedMainFileBuffer)
1150 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1151 PreambleDiagnostics, StoredDiagnostics);
1153 if (!Act->Execute())
1156 transferASTDataFromCompilerInstance(*Clang);
1158 Act->EndSourceFile();
1160 FailedParseDiagnostics.clear();
1165 // Remove the overridden buffer we used for the preamble.
1166 SavedMainFileBuffer = nullptr;
1168 // Keep the ownership of the data in the ASTUnit because the client may
1169 // want to see the diagnostics.
1170 transferASTDataFromCompilerInstance(*Clang);
1171 FailedParseDiagnostics.swap(StoredDiagnostics);
1172 StoredDiagnostics.clear();
1173 NumStoredDiagnosticsFromDriver = 0;
1177 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1178 static std::string GetPreamblePCHPath() {
1179 // FIXME: This is a hack so that we can override the preamble file during
1180 // crash-recovery testing, which is the only case where the preamble files
1181 // are not necessarily cleaned up.
1182 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1186 SmallString<128> Path;
1187 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1192 /// \brief Compute the preamble for the main file, providing the source buffer
1193 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1194 /// that describes the preamble.
1195 ASTUnit::ComputedPreamble
1196 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1197 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1198 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1200 // Try to determine if the main file has been remapped, either from the
1201 // command line (to another file) or directly through the compiler invocation
1202 // (to a memory buffer).
1203 llvm::MemoryBuffer *Buffer = nullptr;
1204 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1205 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1206 llvm::sys::fs::UniqueID MainFileID;
1207 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1208 // Check whether there is a file-file remapping of the main file
1209 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1210 std::string MPath(RF.first);
1211 llvm::sys::fs::UniqueID MID;
1212 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1213 if (MainFileID == MID) {
1214 // We found a remapping. Try to load the resulting, remapped source.
1215 BufferOwner = getBufferForFile(RF.second);
1217 return ComputedPreamble(nullptr, nullptr, 0, true);
1222 // Check whether there is a file-buffer remapping. It supercedes the
1223 // file-file remapping.
1224 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1225 std::string MPath(RB.first);
1226 llvm::sys::fs::UniqueID MID;
1227 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1228 if (MainFileID == MID) {
1229 // We found a remapping.
1230 BufferOwner.reset();
1231 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1237 // If the main source file was not remapped, load it now.
1238 if (!Buffer && !BufferOwner) {
1239 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1241 return ComputedPreamble(nullptr, nullptr, 0, true);
1245 Buffer = BufferOwner.get();
1246 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1247 *Invocation.getLangOpts(), MaxLines);
1248 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1252 ASTUnit::PreambleFileHash
1253 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1254 PreambleFileHash Result;
1256 Result.ModTime = ModTime;
1261 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1262 const llvm::MemoryBuffer *Buffer) {
1263 PreambleFileHash Result;
1264 Result.Size = Buffer->getBufferSize();
1268 MD5Ctx.update(Buffer->getBuffer().data());
1269 MD5Ctx.final(Result.MD5);
1275 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1276 const ASTUnit::PreambleFileHash &RHS) {
1277 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1280 } // namespace clang
1282 static std::pair<unsigned, unsigned>
1283 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1284 const LangOptions &LangOpts) {
1285 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1286 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1287 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1288 return std::make_pair(Offset, EndOffset);
1291 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1292 const LangOptions &LangOpts,
1293 const FixItHint &InFix) {
1294 ASTUnit::StandaloneFixIt OutFix;
1295 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1296 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1298 OutFix.CodeToInsert = InFix.CodeToInsert;
1299 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1303 static ASTUnit::StandaloneDiagnostic
1304 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1305 const StoredDiagnostic &InDiag) {
1306 ASTUnit::StandaloneDiagnostic OutDiag;
1307 OutDiag.ID = InDiag.getID();
1308 OutDiag.Level = InDiag.getLevel();
1309 OutDiag.Message = InDiag.getMessage();
1310 OutDiag.LocOffset = 0;
1311 if (InDiag.getLocation().isInvalid())
1313 const SourceManager &SM = InDiag.getLocation().getManager();
1314 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1315 OutDiag.Filename = SM.getFilename(FileLoc);
1316 if (OutDiag.Filename.empty())
1318 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1319 for (const CharSourceRange &Range : InDiag.getRanges())
1320 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1321 for (const FixItHint &FixIt : InDiag.getFixIts())
1322 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1327 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1328 /// the source file.
1330 /// This routine will compute the preamble of the main source file. If a
1331 /// non-trivial preamble is found, it will precompile that preamble into a
1332 /// precompiled header so that the precompiled preamble can be used to reduce
1333 /// reparsing time. If a precompiled preamble has already been constructed,
1334 /// this routine will determine if it is still valid and, if so, avoid
1335 /// rebuilding the precompiled preamble.
1337 /// \param AllowRebuild When true (the default), this routine is
1338 /// allowed to rebuild the precompiled preamble if it is found to be
1341 /// \param MaxLines When non-zero, the maximum number of lines that
1342 /// can occur within the preamble.
1344 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1345 /// buffer that should be used in place of the main file when doing so.
1346 /// Otherwise, returns a NULL pointer.
1347 std::unique_ptr<llvm::MemoryBuffer>
1348 ASTUnit::getMainBufferWithPrecompiledPreamble(
1349 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1350 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1351 unsigned MaxLines) {
1353 auto PreambleInvocation =
1354 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1355 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1356 PreprocessorOptions &PreprocessorOpts
1357 = PreambleInvocation->getPreprocessorOpts();
1359 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1361 if (!NewPreamble.Size) {
1362 // We couldn't find a preamble in the main source. Clear out the current
1363 // preamble, if we have one. It's obviously no good any more.
1365 erasePreambleFile(this);
1367 // The next time we actually see a preamble, precompile it.
1368 PreambleRebuildCounter = 1;
1372 if (!Preamble.empty()) {
1373 // We've previously computed a preamble. Check whether we have the same
1374 // preamble now that we did before, and that there's enough space in
1375 // the main-file buffer within the precompiled preamble to fit the
1377 if (Preamble.size() == NewPreamble.Size &&
1378 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1379 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1380 NewPreamble.Size) == 0) {
1381 // The preamble has not changed. We may be able to re-use the precompiled
1384 // Check that none of the files used by the preamble have changed.
1385 bool AnyFileChanged = false;
1387 // First, make a record of those files that have been overridden via
1388 // remapping or unsaved_files.
1389 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1390 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1395 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1396 // If we can't stat the file we're remapping to, assume that something
1397 // horrible happened.
1398 AnyFileChanged = true;
1402 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1404 llvm::sys::toTimeT(Status.getLastModificationTime()));
1407 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1412 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1413 AnyFileChanged = true;
1417 OverriddenFiles[Status.getUniqueID()] =
1418 PreambleFileHash::createForMemoryBuffer(RB.second);
1421 // Check whether anything has changed.
1422 for (llvm::StringMap<PreambleFileHash>::iterator
1423 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1424 !AnyFileChanged && F != FEnd;
1427 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1428 // If we can't stat the file, assume that something horrible happened.
1429 AnyFileChanged = true;
1433 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1434 = OverriddenFiles.find(Status.getUniqueID());
1435 if (Overridden != OverriddenFiles.end()) {
1436 // This file was remapped; check whether the newly-mapped file
1437 // matches up with the previous mapping.
1438 if (Overridden->second != F->second)
1439 AnyFileChanged = true;
1443 // The file was not remapped; check whether it has changed on disk.
1444 if (Status.getSize() != uint64_t(F->second.Size) ||
1445 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1447 AnyFileChanged = true;
1450 if (!AnyFileChanged) {
1451 // Okay! We can re-use the precompiled preamble.
1453 // Set the state of the diagnostic object to mimic its state
1454 // after parsing the preamble.
1455 getDiagnostics().Reset();
1456 ProcessWarningOptions(getDiagnostics(),
1457 PreambleInvocation->getDiagnosticOpts());
1458 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1460 return llvm::MemoryBuffer::getMemBufferCopy(
1461 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1465 // If we aren't allowed to rebuild the precompiled preamble, just
1470 // We can't reuse the previously-computed preamble. Build a new one.
1472 PreambleDiagnostics.clear();
1473 erasePreambleFile(this);
1474 PreambleRebuildCounter = 1;
1475 } else if (!AllowRebuild) {
1476 // We aren't allowed to rebuild the precompiled preamble; just
1481 // If the preamble rebuild counter > 1, it's because we previously
1482 // failed to build a preamble and we're not yet ready to try
1483 // again. Decrement the counter and return a failure.
1484 if (PreambleRebuildCounter > 1) {
1485 --PreambleRebuildCounter;
1489 // Create a temporary file for the precompiled preamble. In rare
1490 // circumstances, this can fail.
1491 std::string PreamblePCHPath = GetPreamblePCHPath();
1492 if (PreamblePCHPath.empty()) {
1493 // Try again next time.
1494 PreambleRebuildCounter = 1;
1498 // We did not previously compute a preamble, or it can't be reused anyway.
1499 SimpleTimer PreambleTimer(WantTiming);
1500 PreambleTimer.setOutput("Precompiling preamble");
1502 // Save the preamble text for later; we'll need to compare against it for
1503 // subsequent reparses.
1504 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1505 Preamble.assign(FileMgr->getFile(MainFilename),
1506 NewPreamble.Buffer->getBufferStart(),
1507 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1508 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1510 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1511 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1513 // Remap the main source file to the preamble buffer.
1514 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1515 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1517 // Tell the compiler invocation to generate a temporary precompiled header.
1518 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1519 // FIXME: Generate the precompiled header into memory?
1520 FrontendOpts.OutputFile = PreamblePCHPath;
1521 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1522 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1524 // Create the compiler instance to use for building the precompiled preamble.
1525 std::unique_ptr<CompilerInstance> Clang(
1526 new CompilerInstance(std::move(PCHContainerOps)));
1528 // Recover resources if we crash before exiting this method.
1529 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1530 CICleanup(Clang.get());
1532 Clang->setInvocation(std::move(PreambleInvocation));
1533 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1535 // Set up diagnostics, capturing all of the diagnostics produced.
1536 Clang->setDiagnostics(&getDiagnostics());
1538 // Create the target instance.
1539 Clang->setTarget(TargetInfo::CreateTargetInfo(
1540 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1541 if (!Clang->hasTarget()) {
1542 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1544 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1545 PreprocessorOpts.RemappedFileBuffers.pop_back();
1549 // Inform the target of the language options.
1551 // FIXME: We shouldn't need to do this, the target should be immutable once
1552 // created. This complexity should be lifted elsewhere.
1553 Clang->getTarget().adjust(Clang->getLangOpts());
1555 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1556 "Invocation must have exactly one source file!");
1557 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1558 InputKind::Source &&
1559 "FIXME: AST inputs not yet supported here!");
1560 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1561 InputKind::LLVM_IR &&
1562 "IR inputs not support here!");
1564 // Clear out old caches and data.
1565 getDiagnostics().Reset();
1566 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1567 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1568 TopLevelDecls.clear();
1569 TopLevelDeclsInPreamble.clear();
1570 PreambleDiagnostics.clear();
1572 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1573 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1577 // Create a file manager object to provide access to and cache the filesystem.
1578 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1580 // Create the source manager.
1581 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1582 Clang->getFileManager()));
1584 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1585 Clang->addDependencyCollector(PreambleDepCollector);
1587 std::unique_ptr<PrecompilePreambleAction> Act;
1588 Act.reset(new PrecompilePreambleAction(*this));
1589 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1590 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1592 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1593 PreprocessorOpts.RemappedFileBuffers.pop_back();
1599 // Transfer any diagnostics generated when parsing the preamble into the set
1600 // of preamble diagnostics.
1601 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1602 E = stored_diag_end();
1604 PreambleDiagnostics.push_back(
1605 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1607 Act->EndSourceFile();
1609 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1611 if (!Act->hasEmittedPreamblePCH()) {
1612 // The preamble PCH failed (e.g. there was a module loading fatal error),
1613 // so no precompiled header was generated. Forget that we even tried.
1614 // FIXME: Should we leave a note for ourselves to try again?
1615 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1617 TopLevelDeclsInPreamble.clear();
1618 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1619 PreprocessorOpts.RemappedFileBuffers.pop_back();
1623 // Keep track of the preamble we precompiled.
1624 setPreambleFile(this, FrontendOpts.OutputFile);
1625 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1627 // Keep track of all of the files that the source manager knows about,
1628 // so we can verify whether they have changed or not.
1629 FilesInPreamble.clear();
1630 SourceManager &SourceMgr = Clang->getSourceManager();
1631 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1632 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1633 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1635 if (time_t ModTime = File->getModificationTime()) {
1636 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1637 File->getSize(), ModTime);
1639 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1640 FilesInPreamble[File->getName()] =
1641 PreambleFileHash::createForMemoryBuffer(Buffer);
1645 PreambleRebuildCounter = 1;
1646 PreprocessorOpts.RemappedFileBuffers.pop_back();
1648 // If the hash of top-level entities differs from the hash of the top-level
1649 // entities the last time we rebuilt the preamble, clear out the completion
1651 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1652 CompletionCacheTopLevelHashValue = 0;
1653 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1656 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1660 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1661 std::vector<Decl *> Resolved;
1662 Resolved.reserve(TopLevelDeclsInPreamble.size());
1663 ExternalASTSource &Source = *getASTContext().getExternalSource();
1664 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1665 // Resolve the declaration ID to an actual declaration, possibly
1666 // deserializing the declaration in the process.
1667 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1668 Resolved.push_back(D);
1670 TopLevelDeclsInPreamble.clear();
1671 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1674 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1675 // Steal the created target, context, and preprocessor if they have been
1677 assert(CI.hasInvocation() && "missing invocation");
1678 LangOpts = CI.getInvocation().LangOpts;
1679 TheSema = CI.takeSema();
1680 Consumer = CI.takeASTConsumer();
1681 if (CI.hasASTContext())
1682 Ctx = &CI.getASTContext();
1683 if (CI.hasPreprocessor())
1684 PP = CI.getPreprocessorPtr();
1685 CI.setSourceManager(nullptr);
1686 CI.setFileManager(nullptr);
1688 Target = &CI.getTarget();
1689 Reader = CI.getModuleManager();
1690 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1693 StringRef ASTUnit::getMainFileName() const {
1694 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1695 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1697 return Input.getFile();
1699 return Input.getBuffer()->getBufferIdentifier();
1703 if (const FileEntry *
1704 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1705 return FE->getName();
1711 StringRef ASTUnit::getASTFileName() const {
1712 if (!isMainFileAST())
1715 serialization::ModuleFile &
1716 Mod = Reader->getModuleManager().getPrimaryModule();
1717 return Mod.FileName;
1720 std::unique_ptr<ASTUnit>
1721 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1722 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1723 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1724 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1725 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1726 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1727 createVFSFromCompilerInvocation(*CI, *Diags);
1730 AST->Diagnostics = Diags;
1731 AST->FileSystemOpts = CI->getFileSystemOpts();
1732 AST->Invocation = std::move(CI);
1733 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1734 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1735 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1736 UserFilesAreVolatile);
1737 AST->PCMCache = new MemoryBufferCache;
1742 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1743 std::shared_ptr<CompilerInvocation> CI,
1744 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1745 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1746 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1747 bool OnlyLocalDecls, bool CaptureDiagnostics,
1748 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1749 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1750 std::unique_ptr<ASTUnit> *ErrAST) {
1751 assert(CI && "A CompilerInvocation is required");
1753 std::unique_ptr<ASTUnit> OwnAST;
1754 ASTUnit *AST = Unit;
1756 // Create the AST unit.
1757 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1763 if (!ResourceFilesPath.empty()) {
1764 // Override the resources path.
1765 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1767 AST->OnlyLocalDecls = OnlyLocalDecls;
1768 AST->CaptureDiagnostics = CaptureDiagnostics;
1769 if (PrecompilePreambleAfterNParses > 0)
1770 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1771 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1772 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1773 AST->IncludeBriefCommentsInCodeCompletion
1774 = IncludeBriefCommentsInCodeCompletion;
1776 // Recover resources if we crash before exiting this method.
1777 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1778 ASTUnitCleanup(OwnAST.get());
1779 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1780 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1781 DiagCleanup(Diags.get());
1783 // We'll manage file buffers ourselves.
1784 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1785 CI->getFrontendOpts().DisableFree = false;
1786 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1788 // Create the compiler instance to use for building the AST.
1789 std::unique_ptr<CompilerInstance> Clang(
1790 new CompilerInstance(std::move(PCHContainerOps)));
1792 // Recover resources if we crash before exiting this method.
1793 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1794 CICleanup(Clang.get());
1796 Clang->setInvocation(std::move(CI));
1797 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1799 // Set up diagnostics, capturing any diagnostics that would
1800 // otherwise be dropped.
1801 Clang->setDiagnostics(&AST->getDiagnostics());
1803 // Create the target instance.
1804 Clang->setTarget(TargetInfo::CreateTargetInfo(
1805 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1806 if (!Clang->hasTarget())
1809 // Inform the target of the language options.
1811 // FIXME: We shouldn't need to do this, the target should be immutable once
1812 // created. This complexity should be lifted elsewhere.
1813 Clang->getTarget().adjust(Clang->getLangOpts());
1815 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1816 "Invocation must have exactly one source file!");
1817 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1818 InputKind::Source &&
1819 "FIXME: AST inputs not yet supported here!");
1820 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1821 InputKind::LLVM_IR &&
1822 "IR inputs not support here!");
1824 // Configure the various subsystems.
1825 AST->TheSema.reset();
1828 AST->Reader = nullptr;
1830 // Create a file manager object to provide access to and cache the filesystem.
1831 Clang->setFileManager(&AST->getFileManager());
1833 // Create the source manager.
1834 Clang->setSourceManager(&AST->getSourceManager());
1836 FrontendAction *Act = Action;
1838 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1840 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1841 Act = TrackerAct.get();
1844 // Recover resources if we crash before exiting this method.
1845 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1846 ActCleanup(TrackerAct.get());
1848 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1849 AST->transferASTDataFromCompilerInstance(*Clang);
1850 if (OwnAST && ErrAST)
1851 ErrAST->swap(OwnAST);
1856 if (Persistent && !TrackerAct) {
1857 Clang->getPreprocessor().addPPCallbacks(
1858 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1859 AST->getCurrentTopLevelHashValue()));
1860 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1861 if (Clang->hasASTConsumer())
1862 Consumers.push_back(Clang->takeASTConsumer());
1863 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1864 *AST, AST->getCurrentTopLevelHashValue()));
1865 Clang->setASTConsumer(
1866 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1868 if (!Act->Execute()) {
1869 AST->transferASTDataFromCompilerInstance(*Clang);
1870 if (OwnAST && ErrAST)
1871 ErrAST->swap(OwnAST);
1876 // Steal the created target, context, and preprocessor.
1877 AST->transferASTDataFromCompilerInstance(*Clang);
1879 Act->EndSourceFile();
1882 return OwnAST.release();
1887 bool ASTUnit::LoadFromCompilerInvocation(
1888 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1889 unsigned PrecompilePreambleAfterNParses) {
1893 // We'll manage file buffers ourselves.
1894 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1895 Invocation->getFrontendOpts().DisableFree = false;
1896 getDiagnostics().Reset();
1897 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1899 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1900 if (PrecompilePreambleAfterNParses > 0) {
1901 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1902 OverrideMainBuffer =
1903 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1904 getDiagnostics().Reset();
1905 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1908 SimpleTimer ParsingTimer(WantTiming);
1909 ParsingTimer.setOutput("Parsing " + getMainFileName());
1911 // Recover resources if we crash before exiting this method.
1912 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1913 MemBufferCleanup(OverrideMainBuffer.get());
1915 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1918 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1919 std::shared_ptr<CompilerInvocation> CI,
1920 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1921 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1922 bool OnlyLocalDecls, bool CaptureDiagnostics,
1923 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1924 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1925 bool UserFilesAreVolatile) {
1926 // Create the AST unit.
1927 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1928 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1929 AST->Diagnostics = Diags;
1930 AST->OnlyLocalDecls = OnlyLocalDecls;
1931 AST->CaptureDiagnostics = CaptureDiagnostics;
1932 AST->TUKind = TUKind;
1933 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1934 AST->IncludeBriefCommentsInCodeCompletion
1935 = IncludeBriefCommentsInCodeCompletion;
1936 AST->Invocation = std::move(CI);
1937 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1938 AST->FileMgr = FileMgr;
1939 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1941 // Recover resources if we crash before exiting this method.
1942 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1943 ASTUnitCleanup(AST.get());
1944 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1945 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1946 DiagCleanup(Diags.get());
1948 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1949 PrecompilePreambleAfterNParses))
1954 ASTUnit *ASTUnit::LoadFromCommandLine(
1955 const char **ArgBegin, const char **ArgEnd,
1956 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1957 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1958 bool OnlyLocalDecls, bool CaptureDiagnostics,
1959 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1960 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1961 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1962 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1963 bool UserFilesAreVolatile, bool ForSerialization,
1964 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
1965 assert(Diags.get() && "no DiagnosticsEngine was provided");
1967 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1969 std::shared_ptr<CompilerInvocation> CI;
1973 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1976 CI = clang::createInvocationFromCommandLine(
1977 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1982 // Override any files that need remapping
1983 for (const auto &RemappedFile : RemappedFiles) {
1984 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1985 RemappedFile.second);
1987 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1988 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1989 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1991 // Override the resources path.
1992 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1994 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1997 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1999 // Create the AST unit.
2000 std::unique_ptr<ASTUnit> AST;
2001 AST.reset(new ASTUnit(false));
2002 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
2003 AST->Diagnostics = Diags;
2004 AST->FileSystemOpts = CI->getFileSystemOpts();
2005 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2006 createVFSFromCompilerInvocation(*CI, *Diags);
2009 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
2010 AST->PCMCache = new MemoryBufferCache;
2011 AST->OnlyLocalDecls = OnlyLocalDecls;
2012 AST->CaptureDiagnostics = CaptureDiagnostics;
2013 AST->TUKind = TUKind;
2014 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
2015 AST->IncludeBriefCommentsInCodeCompletion
2016 = IncludeBriefCommentsInCodeCompletion;
2017 AST->UserFilesAreVolatile = UserFilesAreVolatile;
2018 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
2019 AST->StoredDiagnostics.swap(StoredDiagnostics);
2020 AST->Invocation = CI;
2021 if (ForSerialization)
2022 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2023 // Zero out now to ease cleanup during crash recovery.
2027 // Recover resources if we crash before exiting this method.
2028 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2029 ASTUnitCleanup(AST.get());
2031 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2032 PrecompilePreambleAfterNParses)) {
2033 // Some error occurred, if caller wants to examine diagnostics, pass it the
2036 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2042 return AST.release();
2045 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2046 ArrayRef<RemappedFile> RemappedFiles) {
2050 clearFileLevelDecls();
2052 SimpleTimer ParsingTimer(WantTiming);
2053 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2056 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2057 for (const auto &RB : PPOpts.RemappedFileBuffers)
2060 Invocation->getPreprocessorOpts().clearRemappedFiles();
2061 for (const auto &RemappedFile : RemappedFiles) {
2062 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2063 RemappedFile.second);
2066 // If we have a preamble file lying around, or if we might try to
2067 // build a precompiled preamble, do so now.
2068 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2069 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2070 OverrideMainBuffer =
2071 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2073 // Clear out the diagnostics state.
2075 getDiagnostics().Reset();
2076 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2077 if (OverrideMainBuffer)
2078 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2080 // Parse the sources
2082 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2084 // If we're caching global code-completion results, and the top-level
2085 // declarations have changed, clear out the code-completion cache.
2086 if (!Result && ShouldCacheCodeCompletionResults &&
2087 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2088 CacheCodeCompletionResults();
2090 // We now need to clear out the completion info related to this translation
2091 // unit; it'll be recreated if necessary.
2097 //----------------------------------------------------------------------------//
2099 //----------------------------------------------------------------------------//
2102 /// \brief Code completion consumer that combines the cached code-completion
2103 /// results from an ASTUnit with the code-completion results provided to it,
2104 /// then passes the result on to
2105 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2106 uint64_t NormalContexts;
2108 CodeCompleteConsumer &Next;
2111 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2112 const CodeCompleteOptions &CodeCompleteOpts)
2113 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2114 AST(AST), Next(Next)
2116 // Compute the set of contexts in which we will look when we don't have
2117 // any information about the specific context.
2119 = (1LL << CodeCompletionContext::CCC_TopLevel)
2120 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2121 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2122 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2123 | (1LL << CodeCompletionContext::CCC_Statement)
2124 | (1LL << CodeCompletionContext::CCC_Expression)
2125 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2126 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2127 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2128 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2129 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2130 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2131 | (1LL << CodeCompletionContext::CCC_Recovery);
2133 if (AST.getASTContext().getLangOpts().CPlusPlus)
2134 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2135 | (1LL << CodeCompletionContext::CCC_UnionTag)
2136 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2139 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2140 CodeCompletionResult *Results,
2141 unsigned NumResults) override;
2143 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2144 OverloadCandidate *Candidates,
2145 unsigned NumCandidates) override {
2146 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2149 CodeCompletionAllocator &getAllocator() override {
2150 return Next.getAllocator();
2153 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2154 return Next.getCodeCompletionTUInfo();
2157 } // anonymous namespace
2159 /// \brief Helper function that computes which global names are hidden by the
2160 /// local code-completion results.
2161 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2162 CodeCompletionResult *Results,
2163 unsigned NumResults,
2165 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2166 bool OnlyTagNames = false;
2167 switch (Context.getKind()) {
2168 case CodeCompletionContext::CCC_Recovery:
2169 case CodeCompletionContext::CCC_TopLevel:
2170 case CodeCompletionContext::CCC_ObjCInterface:
2171 case CodeCompletionContext::CCC_ObjCImplementation:
2172 case CodeCompletionContext::CCC_ObjCIvarList:
2173 case CodeCompletionContext::CCC_ClassStructUnion:
2174 case CodeCompletionContext::CCC_Statement:
2175 case CodeCompletionContext::CCC_Expression:
2176 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2177 case CodeCompletionContext::CCC_DotMemberAccess:
2178 case CodeCompletionContext::CCC_ArrowMemberAccess:
2179 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2180 case CodeCompletionContext::CCC_Namespace:
2181 case CodeCompletionContext::CCC_Type:
2182 case CodeCompletionContext::CCC_Name:
2183 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2184 case CodeCompletionContext::CCC_ParenthesizedExpression:
2185 case CodeCompletionContext::CCC_ObjCInterfaceName:
2188 case CodeCompletionContext::CCC_EnumTag:
2189 case CodeCompletionContext::CCC_UnionTag:
2190 case CodeCompletionContext::CCC_ClassOrStructTag:
2191 OnlyTagNames = true;
2194 case CodeCompletionContext::CCC_ObjCProtocolName:
2195 case CodeCompletionContext::CCC_MacroName:
2196 case CodeCompletionContext::CCC_MacroNameUse:
2197 case CodeCompletionContext::CCC_PreprocessorExpression:
2198 case CodeCompletionContext::CCC_PreprocessorDirective:
2199 case CodeCompletionContext::CCC_NaturalLanguage:
2200 case CodeCompletionContext::CCC_SelectorName:
2201 case CodeCompletionContext::CCC_TypeQualifiers:
2202 case CodeCompletionContext::CCC_Other:
2203 case CodeCompletionContext::CCC_OtherWithMacros:
2204 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2205 case CodeCompletionContext::CCC_ObjCClassMessage:
2206 case CodeCompletionContext::CCC_ObjCCategoryName:
2207 // We're looking for nothing, or we're looking for names that cannot
2212 typedef CodeCompletionResult Result;
2213 for (unsigned I = 0; I != NumResults; ++I) {
2214 if (Results[I].Kind != Result::RK_Declaration)
2218 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2220 bool Hiding = false;
2222 Hiding = (IDNS & Decl::IDNS_Tag);
2224 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2225 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2226 Decl::IDNS_NonMemberOperator);
2227 if (Ctx.getLangOpts().CPlusPlus)
2228 HiddenIDNS |= Decl::IDNS_Tag;
2229 Hiding = (IDNS & HiddenIDNS);
2235 DeclarationName Name = Results[I].Declaration->getDeclName();
2236 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2237 HiddenNames.insert(Identifier->getName());
2239 HiddenNames.insert(Name.getAsString());
2243 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2244 CodeCompletionContext Context,
2245 CodeCompletionResult *Results,
2246 unsigned NumResults) {
2247 // Merge the results we were given with the results we cached.
2248 bool AddedResult = false;
2249 uint64_t InContexts =
2250 Context.getKind() == CodeCompletionContext::CCC_Recovery
2251 ? NormalContexts : (1LL << Context.getKind());
2252 // Contains the set of names that are hidden by "local" completion results.
2253 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2254 typedef CodeCompletionResult Result;
2255 SmallVector<Result, 8> AllResults;
2256 for (ASTUnit::cached_completion_iterator
2257 C = AST.cached_completion_begin(),
2258 CEnd = AST.cached_completion_end();
2260 // If the context we are in matches any of the contexts we are
2261 // interested in, we'll add this result.
2262 if ((C->ShowInContexts & InContexts) == 0)
2265 // If we haven't added any results previously, do so now.
2267 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2269 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2273 // Determine whether this global completion result is hidden by a local
2274 // completion result. If so, skip it.
2275 if (C->Kind != CXCursor_MacroDefinition &&
2276 HiddenNames.count(C->Completion->getTypedText()))
2279 // Adjust priority based on similar type classes.
2280 unsigned Priority = C->Priority;
2281 CodeCompletionString *Completion = C->Completion;
2282 if (!Context.getPreferredType().isNull()) {
2283 if (C->Kind == CXCursor_MacroDefinition) {
2284 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2286 Context.getPreferredType()->isAnyPointerType());
2287 } else if (C->Type) {
2288 CanQualType Expected
2289 = S.Context.getCanonicalType(
2290 Context.getPreferredType().getUnqualifiedType());
2291 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2292 if (ExpectedSTC == C->TypeClass) {
2293 // We know this type is similar; check for an exact match.
2294 llvm::StringMap<unsigned> &CachedCompletionTypes
2295 = AST.getCachedCompletionTypes();
2296 llvm::StringMap<unsigned>::iterator Pos
2297 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2298 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2299 Priority /= CCF_ExactTypeMatch;
2301 Priority /= CCF_SimilarTypeMatch;
2306 // Adjust the completion string, if required.
2307 if (C->Kind == CXCursor_MacroDefinition &&
2308 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2309 // Create a new code-completion string that just contains the
2310 // macro name, without its arguments.
2311 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2312 CCP_CodePattern, C->Availability);
2313 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2314 Priority = CCP_CodePattern;
2315 Completion = Builder.TakeString();
2318 AllResults.push_back(Result(Completion, Priority, C->Kind,
2322 // If we did not add any cached completion results, just forward the
2323 // results we were given to the next consumer.
2325 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2329 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2333 void ASTUnit::CodeComplete(
2334 StringRef File, unsigned Line, unsigned Column,
2335 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2336 bool IncludeCodePatterns, bool IncludeBriefComments,
2337 CodeCompleteConsumer &Consumer,
2338 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2339 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2340 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2341 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2345 SimpleTimer CompletionTimer(WantTiming);
2346 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2347 Twine(Line) + ":" + Twine(Column));
2349 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2351 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2352 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2353 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2355 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2356 CachedCompletionResults.empty();
2357 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2358 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2359 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2361 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2363 FrontendOpts.CodeCompletionAt.FileName = File;
2364 FrontendOpts.CodeCompletionAt.Line = Line;
2365 FrontendOpts.CodeCompletionAt.Column = Column;
2367 // Set the language options appropriately.
2368 LangOpts = *CCInvocation->getLangOpts();
2370 // Spell-checking and warnings are wasteful during code-completion.
2371 LangOpts.SpellChecking = false;
2372 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2374 std::unique_ptr<CompilerInstance> Clang(
2375 new CompilerInstance(PCHContainerOps));
2377 // Recover resources if we crash before exiting this method.
2378 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2379 CICleanup(Clang.get());
2381 auto &Inv = *CCInvocation;
2382 Clang->setInvocation(std::move(CCInvocation));
2383 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2385 // Set up diagnostics, capturing any diagnostics produced.
2386 Clang->setDiagnostics(&Diag);
2387 CaptureDroppedDiagnostics Capture(true,
2388 Clang->getDiagnostics(),
2390 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2392 // Create the target instance.
2393 Clang->setTarget(TargetInfo::CreateTargetInfo(
2394 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2395 if (!Clang->hasTarget()) {
2396 Clang->setInvocation(nullptr);
2400 // Inform the target of the language options.
2402 // FIXME: We shouldn't need to do this, the target should be immutable once
2403 // created. This complexity should be lifted elsewhere.
2404 Clang->getTarget().adjust(Clang->getLangOpts());
2406 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2407 "Invocation must have exactly one source file!");
2408 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2409 InputKind::Source &&
2410 "FIXME: AST inputs not yet supported here!");
2411 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2412 InputKind::LLVM_IR &&
2413 "IR inputs not support here!");
2415 // Use the source and file managers that we were given.
2416 Clang->setFileManager(&FileMgr);
2417 Clang->setSourceManager(&SourceMgr);
2420 PreprocessorOpts.clearRemappedFiles();
2421 PreprocessorOpts.RetainRemappedFileBuffers = true;
2422 for (const auto &RemappedFile : RemappedFiles) {
2423 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2424 OwnedBuffers.push_back(RemappedFile.second);
2427 // Use the code completion consumer we were given, but adding any cached
2428 // code-completion results.
2429 AugmentedCodeCompleteConsumer *AugmentedConsumer
2430 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2431 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2433 // If we have a precompiled preamble, try to use it. We only allow
2434 // the use of the precompiled preamble if we're if the completion
2435 // point is within the main file, after the end of the precompiled
2437 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2438 if (!getPreambleFile(this).empty()) {
2439 std::string CompleteFilePath(File);
2440 llvm::sys::fs::UniqueID CompleteFileID;
2442 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2443 std::string MainPath(OriginalSourceFile);
2444 llvm::sys::fs::UniqueID MainID;
2445 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2446 if (CompleteFileID == MainID && Line > 1)
2447 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2448 PCHContainerOps, Inv, false, Line - 1);
2453 // If the main file has been overridden due to the use of a preamble,
2454 // make that override happen and introduce the preamble.
2455 if (OverrideMainBuffer) {
2456 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2457 OverrideMainBuffer.get());
2458 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2459 PreprocessorOpts.PrecompiledPreambleBytes.second
2460 = PreambleEndsAtStartOfLine;
2461 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2462 PreprocessorOpts.DisablePCHValidation = true;
2464 OwnedBuffers.push_back(OverrideMainBuffer.release());
2466 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2467 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2470 // Disable the preprocessing record if modules are not enabled.
2471 if (!Clang->getLangOpts().Modules)
2472 PreprocessorOpts.DetailedRecord = false;
2474 std::unique_ptr<SyntaxOnlyAction> Act;
2475 Act.reset(new SyntaxOnlyAction);
2476 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2478 Act->EndSourceFile();
2482 bool ASTUnit::Save(StringRef File) {
2483 if (HadModuleLoaderFatalFailure)
2486 // Write to a temporary file and later rename it to the actual file, to avoid
2487 // possible race conditions.
2488 SmallString<128> TempPath;
2490 TempPath += "-%%%%%%%%";
2492 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2495 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2496 // unconditionally create a stat cache when we parse the file?
2497 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2501 if (Out.has_error()) {
2506 if (llvm::sys::fs::rename(TempPath, File)) {
2507 llvm::sys::fs::remove(TempPath);
2514 static bool serializeUnit(ASTWriter &Writer,
2515 SmallVectorImpl<char> &Buffer,
2519 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2521 // Write the generated bitstream to "Out".
2522 if (!Buffer.empty())
2523 OS.write(Buffer.data(), Buffer.size());
2528 bool ASTUnit::serialize(raw_ostream &OS) {
2529 // For serialization we are lenient if the errors were only warn-as-error kind.
2530 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2533 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2534 getSema(), hasErrors, OS);
2536 SmallString<128> Buffer;
2537 llvm::BitstreamWriter Stream(Buffer);
2538 MemoryBufferCache PCMCache;
2539 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2540 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2543 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2545 void ASTUnit::TranslateStoredDiagnostics(
2546 FileManager &FileMgr,
2547 SourceManager &SrcMgr,
2548 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2549 SmallVectorImpl<StoredDiagnostic> &Out) {
2550 // Map the standalone diagnostic into the new source manager. We also need to
2551 // remap all the locations to the new view. This includes the diag location,
2552 // any associated source ranges, and the source ranges of associated fix-its.
2553 // FIXME: There should be a cleaner way to do this.
2555 SmallVector<StoredDiagnostic, 4> Result;
2556 Result.reserve(Diags.size());
2557 const FileEntry *PreviousFE = nullptr;
2559 for (const StandaloneDiagnostic &SD : Diags) {
2560 // Rebuild the StoredDiagnostic.
2561 if (SD.Filename.empty())
2563 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2566 if (FE != PreviousFE) {
2567 FID = SrcMgr.translateFile(FE);
2570 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2571 if (FileLoc.isInvalid())
2573 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2574 FullSourceLoc Loc(L, SrcMgr);
2576 SmallVector<CharSourceRange, 4> Ranges;
2577 Ranges.reserve(SD.Ranges.size());
2578 for (const auto &Range : SD.Ranges) {
2579 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2580 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2581 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2584 SmallVector<FixItHint, 2> FixIts;
2585 FixIts.reserve(SD.FixIts.size());
2586 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2587 FixIts.push_back(FixItHint());
2588 FixItHint &FH = FixIts.back();
2589 FH.CodeToInsert = FixIt.CodeToInsert;
2590 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2591 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2592 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2595 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2596 SD.Message, Loc, Ranges, FixIts));
2601 void ASTUnit::addFileLevelDecl(Decl *D) {
2604 // We only care about local declarations.
2605 if (D->isFromASTFile())
2608 SourceManager &SM = *SourceMgr;
2609 SourceLocation Loc = D->getLocation();
2610 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2613 // We only keep track of the file-level declarations of each file.
2614 if (!D->getLexicalDeclContext()->isFileContext())
2617 SourceLocation FileLoc = SM.getFileLoc(Loc);
2618 assert(SM.isLocalSourceLocation(FileLoc));
2621 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2622 if (FID.isInvalid())
2625 LocDeclsTy *&Decls = FileDecls[FID];
2627 Decls = new LocDeclsTy();
2629 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2631 if (Decls->empty() || Decls->back().first <= Offset) {
2632 Decls->push_back(LocDecl);
2636 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2637 LocDecl, llvm::less_first());
2639 Decls->insert(I, LocDecl);
2642 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2643 SmallVectorImpl<Decl *> &Decls) {
2644 if (File.isInvalid())
2647 if (SourceMgr->isLoadedFileID(File)) {
2648 assert(Ctx->getExternalSource() && "No external source!");
2649 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2653 FileDeclsTy::iterator I = FileDecls.find(File);
2654 if (I == FileDecls.end())
2657 LocDeclsTy &LocDecls = *I->second;
2658 if (LocDecls.empty())
2661 LocDeclsTy::iterator BeginIt =
2662 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2663 std::make_pair(Offset, (Decl *)nullptr),
2664 llvm::less_first());
2665 if (BeginIt != LocDecls.begin())
2668 // If we are pointing at a top-level decl inside an objc container, we need
2669 // to backtrack until we find it otherwise we will fail to report that the
2670 // region overlaps with an objc container.
2671 while (BeginIt != LocDecls.begin() &&
2672 BeginIt->second->isTopLevelDeclInObjCContainer())
2675 LocDeclsTy::iterator EndIt = std::upper_bound(
2676 LocDecls.begin(), LocDecls.end(),
2677 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2678 if (EndIt != LocDecls.end())
2681 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2682 Decls.push_back(DIt->second);
2685 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2686 unsigned Line, unsigned Col) const {
2687 const SourceManager &SM = getSourceManager();
2688 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2689 return SM.getMacroArgExpandedLocation(Loc);
2692 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2693 unsigned Offset) const {
2694 const SourceManager &SM = getSourceManager();
2695 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2696 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2699 /// \brief If \arg Loc is a loaded location from the preamble, returns
2700 /// the corresponding local location of the main file, otherwise it returns
2702 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2705 PreambleID = SourceMgr->getPreambleFileID();
2707 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2711 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2712 SourceLocation FileLoc
2713 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2714 return FileLoc.getLocWithOffset(Offs);
2720 /// \brief If \arg Loc is a local location of the main file but inside the
2721 /// preamble chunk, returns the corresponding loaded location from the
2722 /// preamble, otherwise it returns \arg Loc.
2723 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2726 PreambleID = SourceMgr->getPreambleFileID();
2728 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2732 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2733 Offs < Preamble.size()) {
2734 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2735 return FileLoc.getLocWithOffset(Offs);
2741 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2744 FID = SourceMgr->getPreambleFileID();
2746 if (Loc.isInvalid() || FID.isInvalid())
2749 return SourceMgr->isInFileID(Loc, FID);
2752 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2755 FID = SourceMgr->getMainFileID();
2757 if (Loc.isInvalid() || FID.isInvalid())
2760 return SourceMgr->isInFileID(Loc, FID);
2763 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2766 FID = SourceMgr->getPreambleFileID();
2768 if (FID.isInvalid())
2769 return SourceLocation();
2771 return SourceMgr->getLocForEndOfFile(FID);
2774 SourceLocation ASTUnit::getStartOfMainFileID() {
2777 FID = SourceMgr->getMainFileID();
2779 if (FID.isInvalid())
2780 return SourceLocation();
2782 return SourceMgr->getLocForStartOfFile(FID);
2785 llvm::iterator_range<PreprocessingRecord::iterator>
2786 ASTUnit::getLocalPreprocessingEntities() const {
2787 if (isMainFileAST()) {
2788 serialization::ModuleFile &
2789 Mod = Reader->getModuleManager().getPrimaryModule();
2790 return Reader->getModulePreprocessedEntities(Mod);
2793 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2794 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2796 return llvm::make_range(PreprocessingRecord::iterator(),
2797 PreprocessingRecord::iterator());
2800 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2801 if (isMainFileAST()) {
2802 serialization::ModuleFile &
2803 Mod = Reader->getModuleManager().getPrimaryModule();
2804 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2805 if (!Fn(context, D))
2812 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2813 TLEnd = top_level_end();
2814 TL != TLEnd; ++TL) {
2815 if (!Fn(context, *TL))
2822 const FileEntry *ASTUnit::getPCHFile() {
2826 serialization::ModuleFile *Mod = nullptr;
2827 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2829 case serialization::MK_ImplicitModule:
2830 case serialization::MK_ExplicitModule:
2831 case serialization::MK_PrebuiltModule:
2832 return true; // skip dependencies.
2833 case serialization::MK_PCH:
2835 return true; // found it.
2836 case serialization::MK_Preamble:
2837 return false; // look in dependencies.
2838 case serialization::MK_MainFile:
2839 return false; // look in dependencies.
2850 bool ASTUnit::isModuleFile() {
2851 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2854 void ASTUnit::PreambleData::countLines() const {
2859 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2861 if (Buffer.back() != '\n')
2866 ASTUnit::ConcurrencyState::ConcurrencyState() {
2867 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2870 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2871 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2874 void ASTUnit::ConcurrencyState::start() {
2875 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2876 assert(acquired && "Concurrent access to ASTUnit!");
2879 void ASTUnit::ConcurrencyState::finish() {
2880 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2885 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2886 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2887 void ASTUnit::ConcurrencyState::start() {}
2888 void ASTUnit::ConcurrencyState::finish() {}