1 //===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit Implementation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeOrdering.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Basic/TargetOptions.h"
23 #include "clang/Basic/VirtualFileSystem.h"
24 #include "clang/Frontend/CompilerInstance.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/FrontendOptions.h"
28 #include "clang/Frontend/MultiplexConsumer.h"
29 #include "clang/Frontend/Utils.h"
30 #include "clang/Lex/HeaderSearch.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Sema/Sema.h"
34 #include "clang/Serialization/ASTReader.h"
35 #include "clang/Serialization/ASTWriter.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringSet.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
50 using namespace clang;
52 using llvm::TimeRecord;
61 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
63 Start = TimeRecord::getCurrentTime();
66 void setOutput(const Twine &Output) {
68 this->Output = Output.str();
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
86 /// \brief Temporary files that should be removed when the ASTUnit is
88 SmallVector<std::string, 4> TemporaryFiles;
90 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
96 /// \brief Erase temporary files and the preamble file.
101 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
106 static void cleanupOnDiskMapAtExit();
108 typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
110 static OnDiskDataMap &getOnDiskDataMap() {
111 static OnDiskDataMap M;
112 static bool hasRegisteredAtExit = false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit = true;
115 atexit(cleanupOnDiskMapAtExit);
120 static void cleanupOnDiskMapAtExit() {
121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
123 for (const auto &I : getOnDiskDataMap()) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
130 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
131 // We require the mutex since we are modifying the structure of the
133 llvm::MutexGuard Guard(getOnDiskMutex());
134 OnDiskDataMap &M = getOnDiskDataMap();
137 D = llvm::make_unique<OnDiskData>();
141 static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
145 static void removeOnDiskEntry(const ASTUnit *AU) {
146 // We require the mutex since we are modifying the structure of the
148 llvm::MutexGuard Guard(getOnDiskMutex());
149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
152 I->second->Cleanup();
157 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
158 getOnDiskData(AU).PreambleFile = preambleFile;
161 static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
165 void OnDiskData::CleanTemporaryFiles() {
166 for (StringRef File : TemporaryFiles)
167 llvm::sys::fs::remove(File);
168 TemporaryFiles.clear();
171 void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
173 llvm::sys::fs::remove(PreambleFile);
174 PreambleFile.clear();
178 void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
183 struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
191 void ASTUnit::clearFileLevelDecls() {
192 llvm::DeleteContainerSeconds(FileDecls);
195 void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
199 void ASTUnit::addTemporaryFile(StringRef TempFile) {
200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
203 /// \brief After failing to build a precompiled preamble (due to
204 /// errors in the source that occurs in the preamble), the number of
205 /// reparses during which we'll skip even trying to precompile the
207 const unsigned DefaultPreambleRebuildInterval = 5;
209 /// \brief Tracks the number of ASTUnit objects that are currently active.
211 /// Used for debugging purposes only.
212 static std::atomic<unsigned> ActiveASTUnitObjects;
214 ASTUnit::ASTUnit(bool _MainFileIsAST)
215 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
216 OnlyLocalDecls(false), CaptureDiagnostics(false),
217 MainFileIsAST(_MainFileIsAST),
218 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
219 OwnsRemappedFileBuffers(true),
220 NumStoredDiagnosticsFromDriver(0),
221 PreambleRebuildCounter(0),
222 NumWarningsInPreamble(0),
223 ShouldCacheCodeCompletionResults(false),
224 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
225 CompletionCacheTopLevelHashValue(0),
226 PreambleTopLevelHashValue(0),
227 CurrentTopLevelHashValue(0),
228 UnsafeToFree(false) {
229 if (getenv("LIBCLANG_OBJTRACKING"))
230 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
233 ASTUnit::~ASTUnit() {
234 // If we loaded from an AST file, balance out the BeginSourceFile call.
235 if (MainFileIsAST && getDiagnostics().getClient()) {
236 getDiagnostics().getClient()->EndSourceFile();
239 clearFileLevelDecls();
241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
248 if (Invocation.get() && OwnsRemappedFileBuffers) {
249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
250 for (const auto &RB : PPOpts.RemappedFileBuffers)
254 ClearCachedCompletionResults();
256 if (getenv("LIBCLANG_OBJTRACKING"))
257 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
260 void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
262 /// \brief Determine the set of code-completion contexts in which this
263 /// declaration should be shown.
264 static unsigned getDeclShowContexts(const NamedDecl *ND,
265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
269 if (isa<UsingShadowDecl>(ND))
270 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
274 uint64_t Contexts = 0;
275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
277 // Types can appear in these contexts.
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
279 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
280 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
281 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
282 | (1LL << CodeCompletionContext::CCC_Statement)
283 | (1LL << CodeCompletionContext::CCC_Type)
284 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
290 // In Objective-C, message sends can send interfaces. In Objective-C++,
291 // all types are available due to functional casts.
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
295 // In Objective-C, you can only be a subclass of another Objective-C class
296 if (isa<ObjCInterfaceDecl>(ND))
297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
303 // Part of the nested-name-specifier in C++0x.
304 if (LangOpts.CPlusPlus11)
305 IsNestedNameSpecifier = true;
306 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
307 if (Record->isUnion())
308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
312 if (LangOpts.CPlusPlus)
313 IsNestedNameSpecifier = true;
314 } else if (isa<ClassTemplateDecl>(ND))
315 IsNestedNameSpecifier = true;
316 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
317 // Values can appear in these contexts.
318 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
319 | (1LL << CodeCompletionContext::CCC_Expression)
320 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
321 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
322 } else if (isa<ObjCProtocolDecl>(ND)) {
323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
324 } else if (isa<ObjCCategoryDecl>(ND)) {
325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
329 // Part of the nested-name-specifier.
330 IsNestedNameSpecifier = true;
336 void ASTUnit::CacheCodeCompletionResults() {
340 SimpleTimer Timer(WantTiming);
341 Timer.setOutput("Cache global code completions for " + getMainFileName());
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
346 // Gather the set of global code completions.
347 typedef CodeCompletionResult Result;
348 SmallVector<Result, 8> Results;
349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
350 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
354 // Translate global code completions into cached completions.
355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
357 for (Result &R : Results) {
359 case Result::RK_Declaration: {
360 bool IsNestedNameSpecifier = false;
361 CachedCodeCompletionResult CachedResult;
362 CachedResult.Completion = R.CreateCodeCompletionString(
363 *TheSema, *CachedCompletionAllocator, CCTUInfo,
364 IncludeBriefCommentsInCodeCompletion);
365 CachedResult.ShowInContexts = getDeclShowContexts(
366 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
367 CachedResult.Priority = R.Priority;
368 CachedResult.Kind = R.CursorKind;
369 CachedResult.Availability = R.Availability;
371 // Keep track of the type of this completion in an ASTContext-agnostic
373 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
374 if (UsageType.isNull()) {
375 CachedResult.TypeClass = STC_Void;
376 CachedResult.Type = 0;
378 CanQualType CanUsageType
379 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
380 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
382 // Determine whether we have already seen this type. If so, we save
383 // ourselves the work of formatting the type string by using the
384 // temporary, CanQualType-based hash table to find the associated value.
385 unsigned &TypeValue = CompletionTypes[CanUsageType];
386 if (TypeValue == 0) {
387 TypeValue = CompletionTypes.size();
388 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
392 CachedResult.Type = TypeValue;
395 CachedCompletionResults.push_back(CachedResult);
397 /// Handle nested-name-specifiers in C++.
398 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
399 !R.StartsNestedNameSpecifier) {
400 // The contexts in which a nested-name-specifier can appear in C++.
402 = (1LL << CodeCompletionContext::CCC_TopLevel)
403 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
404 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
405 | (1LL << CodeCompletionContext::CCC_Statement)
406 | (1LL << CodeCompletionContext::CCC_Expression)
407 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
408 | (1LL << CodeCompletionContext::CCC_EnumTag)
409 | (1LL << CodeCompletionContext::CCC_UnionTag)
410 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
411 | (1LL << CodeCompletionContext::CCC_Type)
412 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
413 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
415 if (isa<NamespaceDecl>(R.Declaration) ||
416 isa<NamespaceAliasDecl>(R.Declaration))
417 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
419 if (unsigned RemainingContexts
420 = NNSContexts & ~CachedResult.ShowInContexts) {
421 // If there any contexts where this completion can be a
422 // nested-name-specifier but isn't already an option, create a
423 // nested-name-specifier completion.
424 R.StartsNestedNameSpecifier = true;
425 CachedResult.Completion = R.CreateCodeCompletionString(
426 *TheSema, *CachedCompletionAllocator, CCTUInfo,
427 IncludeBriefCommentsInCodeCompletion);
428 CachedResult.ShowInContexts = RemainingContexts;
429 CachedResult.Priority = CCP_NestedNameSpecifier;
430 CachedResult.TypeClass = STC_Void;
431 CachedResult.Type = 0;
432 CachedCompletionResults.push_back(CachedResult);
438 case Result::RK_Keyword:
439 case Result::RK_Pattern:
440 // Ignore keywords and patterns; we don't care, since they are so
441 // easily regenerated.
444 case Result::RK_Macro: {
445 CachedCodeCompletionResult CachedResult;
446 CachedResult.Completion = R.CreateCodeCompletionString(
447 *TheSema, *CachedCompletionAllocator, CCTUInfo,
448 IncludeBriefCommentsInCodeCompletion);
449 CachedResult.ShowInContexts
450 = (1LL << CodeCompletionContext::CCC_TopLevel)
451 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
452 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
453 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
454 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
455 | (1LL << CodeCompletionContext::CCC_Statement)
456 | (1LL << CodeCompletionContext::CCC_Expression)
457 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
458 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
459 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
460 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
461 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
463 CachedResult.Priority = R.Priority;
464 CachedResult.Kind = R.CursorKind;
465 CachedResult.Availability = R.Availability;
466 CachedResult.TypeClass = STC_Void;
467 CachedResult.Type = 0;
468 CachedCompletionResults.push_back(CachedResult);
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
478 void ASTUnit::ClearCachedCompletionResults() {
479 CachedCompletionResults.clear();
480 CachedCompletionTypes.clear();
481 CachedCompletionAllocator = nullptr;
486 /// \brief Gathers information from ASTReader that will be used to initialize
488 class ASTInfoCollector : public ASTReaderListener {
491 LangOptions &LangOpt;
492 std::shared_ptr<TargetOptions> &TargetOpts;
493 IntrusiveRefCntPtr<TargetInfo> &Target;
496 bool InitializedLanguage;
498 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
499 std::shared_ptr<TargetOptions> &TargetOpts,
500 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
501 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
502 Target(Target), Counter(Counter), InitializedLanguage(false) {}
504 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
505 bool AllowCompatibleDifferences) override {
506 if (InitializedLanguage)
510 InitializedLanguage = true;
516 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
517 bool AllowCompatibleDifferences) override {
518 // If we've already initialized the target, don't do it again.
522 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
524 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
530 void ReadCounter(const serialization::ModuleFile &M,
531 unsigned Value) override {
537 if (!Target || !InitializedLanguage)
540 // Inform the target of the language options.
542 // FIXME: We shouldn't need to do this, the target should be immutable once
543 // created. This complexity should be lifted elsewhere.
544 Target->adjust(LangOpt);
546 // Initialize the preprocessor.
547 PP.Initialize(*Target);
549 // Initialize the ASTContext
550 Context.InitBuiltinTypes(*Target);
552 // We didn't have access to the comment options when the ASTContext was
553 // constructed, so register them now.
554 Context.getCommentCommandTraits().registerCommentOptions(
555 LangOpt.CommentOpts);
559 /// \brief Diagnostic consumer that saves each diagnostic it is given.
560 class StoredDiagnosticConsumer : public DiagnosticConsumer {
561 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
562 SourceManager *SourceMgr;
565 explicit StoredDiagnosticConsumer(
566 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
567 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
569 void BeginSourceFile(const LangOptions &LangOpts,
570 const Preprocessor *PP = nullptr) override {
572 SourceMgr = &PP->getSourceManager();
575 void HandleDiagnostic(DiagnosticsEngine::Level Level,
576 const Diagnostic &Info) override;
579 /// \brief RAII object that optionally captures diagnostics, if
580 /// there is no diagnostic client to capture them already.
581 class CaptureDroppedDiagnostics {
582 DiagnosticsEngine &Diags;
583 StoredDiagnosticConsumer Client;
584 DiagnosticConsumer *PreviousClient;
585 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
588 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
590 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
592 if (RequestCapture || Diags.getClient() == nullptr) {
593 OwningPreviousClient = Diags.takeClient();
594 PreviousClient = Diags.getClient();
595 Diags.setClient(&Client, false);
599 ~CaptureDroppedDiagnostics() {
600 if (Diags.getClient() == &Client)
601 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
605 } // anonymous namespace
607 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
608 const Diagnostic &Info) {
609 // Default implementation (Warnings/errors count).
610 DiagnosticConsumer::HandleDiagnostic(Level, Info);
612 // Only record the diagnostic if it's part of the source manager we know
613 // about. This effectively drops diagnostics from modules we're building.
614 // FIXME: In the long run, ee don't want to drop source managers from modules.
615 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
616 StoredDiags.emplace_back(Level, Info);
619 ASTMutationListener *ASTUnit::getASTMutationListener() {
621 return &WriterData->Writer;
625 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
627 return &WriterData->Writer;
631 std::unique_ptr<llvm::MemoryBuffer>
632 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
634 auto Buffer = FileMgr->getBufferForFile(Filename);
636 return std::move(*Buffer);
638 *ErrorStr = Buffer.getError().message();
642 /// \brief Configure the diagnostics object for use with ASTUnit.
643 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
644 ASTUnit &AST, bool CaptureDiagnostics) {
645 assert(Diags.get() && "no DiagnosticsEngine was provided");
646 if (CaptureDiagnostics)
647 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
650 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
651 const std::string &Filename,
652 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
653 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
654 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
655 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
656 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
657 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
659 // Recover resources if we crash before exiting this method.
660 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
661 ASTUnitCleanup(AST.get());
662 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
663 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
664 DiagCleanup(Diags.get());
666 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
668 AST->OnlyLocalDecls = OnlyLocalDecls;
669 AST->CaptureDiagnostics = CaptureDiagnostics;
670 AST->Diagnostics = Diags;
671 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
672 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
673 AST->UserFilesAreVolatile = UserFilesAreVolatile;
674 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
675 AST->getFileManager(),
676 UserFilesAreVolatile);
677 AST->HSOpts = new HeaderSearchOptions();
679 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
680 AST->getSourceManager(),
681 AST->getDiagnostics(),
682 AST->ASTFileLangOpts,
683 /*Target=*/nullptr));
685 PreprocessorOptions *PPOpts = new PreprocessorOptions();
687 for (const auto &RemappedFile : RemappedFiles)
688 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
690 // Gather Info for preprocessor construction later on.
692 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
696 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
697 AST->getSourceManager(), HeaderInfo, *AST,
698 /*IILookup=*/nullptr,
699 /*OwnsHeaderSearch=*/false);
700 Preprocessor &PP = *AST->PP;
702 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
703 PP.getIdentifierTable(), PP.getSelectorTable(),
704 PP.getBuiltinInfo());
705 ASTContext &Context = *AST->Ctx;
707 bool disableValid = false;
708 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
710 AST->Reader = new ASTReader(PP, Context, *PCHContainerOps,
712 /*DisableValidation=*/disableValid,
713 AllowPCHWithCompilerErrors);
715 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
716 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
719 // Attach the AST reader to the AST context as an external AST
720 // source, so that declarations will be deserialized from the
721 // AST file as needed.
722 // We need the external source to be set up before we read the AST, because
723 // eagerly-deserialized declarations may use it.
724 Context.setExternalSource(AST->Reader);
726 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
727 SourceLocation(), ASTReader::ARR_None)) {
728 case ASTReader::Success:
731 case ASTReader::Failure:
732 case ASTReader::Missing:
733 case ASTReader::OutOfDate:
734 case ASTReader::VersionMismatch:
735 case ASTReader::ConfigurationMismatch:
736 case ASTReader::HadErrors:
737 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
741 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
743 PP.setCounterValue(Counter);
745 // Create an AST consumer, even though it isn't used.
746 AST->Consumer.reset(new ASTConsumer);
748 // Create a semantic analysis object and tell the AST reader about it.
749 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
750 AST->TheSema->Initialize();
751 AST->Reader->InitializeSema(*AST->TheSema);
753 // Tell the diagnostic client that we have started a source file.
754 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
761 /// \brief Preprocessor callback class that updates a hash value with the names
762 /// of all macros that have been defined by the translation unit.
763 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
767 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
769 void MacroDefined(const Token &MacroNameTok,
770 const MacroDirective *MD) override {
771 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
775 /// \brief Add the given declaration to the hash of all top-level entities.
776 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
780 DeclContext *DC = D->getDeclContext();
784 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
787 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
788 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
789 // For an unscoped enum include the enumerators in the hash since they
790 // enter the top-level namespace.
791 if (!EnumD->isScoped()) {
792 for (const auto *EI : EnumD->enumerators()) {
793 if (EI->getIdentifier())
794 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
799 if (ND->getIdentifier())
800 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
801 else if (DeclarationName Name = ND->getDeclName()) {
802 std::string NameStr = Name.getAsString();
803 Hash = llvm::HashString(NameStr, Hash);
808 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
809 if (Module *Mod = ImportD->getImportedModule()) {
810 std::string ModName = Mod->getFullModuleName();
811 Hash = llvm::HashString(ModName, Hash);
817 class TopLevelDeclTrackerConsumer : public ASTConsumer {
822 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
823 : Unit(_Unit), Hash(Hash) {
827 void handleTopLevelDecl(Decl *D) {
831 // FIXME: Currently ObjC method declarations are incorrectly being
832 // reported as top-level declarations, even though their DeclContext
833 // is the containing ObjC @interface/@implementation. This is a
834 // fundamental problem in the parser right now.
835 if (isa<ObjCMethodDecl>(D))
838 AddTopLevelDeclarationToHash(D, Hash);
839 Unit.addTopLevelDecl(D);
841 handleFileLevelDecl(D);
844 void handleFileLevelDecl(Decl *D) {
845 Unit.addFileLevelDecl(D);
846 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
847 for (auto *I : NSD->decls())
848 handleFileLevelDecl(I);
852 bool HandleTopLevelDecl(DeclGroupRef D) override {
853 for (Decl *TopLevelDecl : D)
854 handleTopLevelDecl(TopLevelDecl);
858 // We're not interested in "interesting" decls.
859 void HandleInterestingDecl(DeclGroupRef) override {}
861 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
862 for (Decl *TopLevelDecl : D)
863 handleTopLevelDecl(TopLevelDecl);
866 ASTMutationListener *GetASTMutationListener() override {
867 return Unit.getASTMutationListener();
870 ASTDeserializationListener *GetASTDeserializationListener() override {
871 return Unit.getDeserializationListener();
875 class TopLevelDeclTrackerAction : public ASTFrontendAction {
879 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
880 StringRef InFile) override {
881 CI.getPreprocessor().addPPCallbacks(
882 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
883 Unit.getCurrentTopLevelHashValue()));
884 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
885 Unit, Unit.getCurrentTopLevelHashValue());
889 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
891 bool hasCodeCompletionSupport() const override { return false; }
892 TranslationUnitKind getTranslationUnitKind() override {
893 return Unit.getTranslationUnitKind();
897 class PrecompilePreambleAction : public ASTFrontendAction {
899 bool HasEmittedPreamblePCH;
902 explicit PrecompilePreambleAction(ASTUnit &Unit)
903 : Unit(Unit), HasEmittedPreamblePCH(false) {}
905 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
906 StringRef InFile) override;
907 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
908 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
909 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
911 bool hasCodeCompletionSupport() const override { return false; }
912 bool hasASTFileSupport() const override { return false; }
913 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
916 class PrecompilePreambleConsumer : public PCHGenerator {
919 std::vector<Decl *> TopLevelDecls;
920 PrecompilePreambleAction *Action;
924 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
925 const Preprocessor &PP, StringRef isysroot,
927 : PCHGenerator(PP, "", nullptr, isysroot, std::make_shared<PCHBuffer>(),
928 /*AllowASTWithErrors=*/true),
929 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
934 bool HandleTopLevelDecl(DeclGroupRef DG) override {
936 // FIXME: Currently ObjC method declarations are incorrectly being
937 // reported as top-level declarations, even though their DeclContext
938 // is the containing ObjC @interface/@implementation. This is a
939 // fundamental problem in the parser right now.
940 if (isa<ObjCMethodDecl>(D))
942 AddTopLevelDeclarationToHash(D, Hash);
943 TopLevelDecls.push_back(D);
948 void HandleTranslationUnit(ASTContext &Ctx) override {
949 PCHGenerator::HandleTranslationUnit(Ctx);
950 if (hasEmittedPCH()) {
951 // Write the generated bitstream to "Out".
953 // Make sure it hits disk now.
956 llvm::SmallVector<char, 0> Empty;
957 getPCH() = std::move(Empty);
959 // Translate the top-level declarations we captured during
960 // parsing into declaration IDs in the precompiled
961 // preamble. This will allow us to deserialize those top-level
962 // declarations when requested.
963 for (Decl *D : TopLevelDecls) {
964 // Invalid top-level decls may not have been serialized.
965 if (D->isInvalidDecl())
967 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
970 Action->setHasEmittedPreamblePCH();
977 std::unique_ptr<ASTConsumer>
978 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
981 std::string OutputFile;
982 raw_ostream *OS = GeneratePCHAction::ComputeASTConsumerArguments(
983 CI, InFile, Sysroot, OutputFile);
987 if (!CI.getFrontendOpts().RelocatablePCH)
990 CI.getPreprocessor().addPPCallbacks(
991 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
992 Unit.getCurrentTopLevelHashValue()));
993 return llvm::make_unique<PrecompilePreambleConsumer>(
994 Unit, this, CI.getPreprocessor(), Sysroot, OS);
997 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
998 return StoredDiag.getLocation().isValid();
1002 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1003 // Get rid of stored diagnostics except the ones from the driver which do not
1004 // have a source location.
1006 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1010 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1012 SourceManager &SM) {
1013 // The stored diagnostic has the old source manager in it; update
1014 // the locations to refer into the new source manager. Since we've
1015 // been careful to make sure that the source manager's state
1016 // before and after are identical, so that we can reuse the source
1018 for (StoredDiagnostic &SD : StoredDiagnostics) {
1019 if (SD.getLocation().isValid()) {
1020 FullSourceLoc Loc(SD.getLocation(), SM);
1021 SD.setLocation(Loc);
1026 /// Parse the source file into a translation unit using the given compiler
1027 /// invocation, replacing the current translation unit.
1029 /// \returns True if a failure occurred that causes the ASTUnit not to
1030 /// contain any translation-unit information, false otherwise.
1031 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1032 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1033 SavedMainFileBuffer.reset();
1038 // Create the compiler instance to use for building the AST.
1039 std::unique_ptr<CompilerInstance> Clang(
1040 new CompilerInstance(PCHContainerOps));
1042 // Recover resources if we crash before exiting this method.
1043 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1044 CICleanup(Clang.get());
1046 IntrusiveRefCntPtr<CompilerInvocation>
1047 CCInvocation(new CompilerInvocation(*Invocation));
1049 Clang->setInvocation(CCInvocation.get());
1050 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1052 // Set up diagnostics, capturing any diagnostics that would
1053 // otherwise be dropped.
1054 Clang->setDiagnostics(&getDiagnostics());
1056 // Create the target instance.
1057 Clang->setTarget(TargetInfo::CreateTargetInfo(
1058 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1059 if (!Clang->hasTarget())
1062 // Inform the target of the language options.
1064 // FIXME: We shouldn't need to do this, the target should be immutable once
1065 // created. This complexity should be lifted elsewhere.
1066 Clang->getTarget().adjust(Clang->getLangOpts());
1068 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1069 "Invocation must have exactly one source file!");
1070 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1071 "FIXME: AST inputs not yet supported here!");
1072 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1073 "IR inputs not support here!");
1075 // Configure the various subsystems.
1076 LangOpts = Clang->getInvocation().LangOpts;
1077 FileSystemOpts = Clang->getFileSystemOpts();
1078 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1079 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1082 FileMgr = new FileManager(FileSystemOpts, VFS);
1083 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1084 UserFilesAreVolatile);
1090 // Clear out old caches and data.
1091 TopLevelDecls.clear();
1092 clearFileLevelDecls();
1093 CleanTemporaryFiles();
1095 if (!OverrideMainBuffer) {
1096 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1097 TopLevelDeclsInPreamble.clear();
1100 // Create a file manager object to provide access to and cache the filesystem.
1101 Clang->setFileManager(&getFileManager());
1103 // Create the source manager.
1104 Clang->setSourceManager(&getSourceManager());
1106 // If the main file has been overridden due to the use of a preamble,
1107 // make that override happen and introduce the preamble.
1108 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1109 if (OverrideMainBuffer) {
1110 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1111 OverrideMainBuffer.get());
1112 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1113 PreprocessorOpts.PrecompiledPreambleBytes.second
1114 = PreambleEndsAtStartOfLine;
1115 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1116 PreprocessorOpts.DisablePCHValidation = true;
1118 // The stored diagnostic has the old source manager in it; update
1119 // the locations to refer into the new source manager. Since we've
1120 // been careful to make sure that the source manager's state
1121 // before and after are identical, so that we can reuse the source
1123 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1125 // Keep track of the override buffer;
1126 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1129 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1130 new TopLevelDeclTrackerAction(*this));
1132 // Recover resources if we crash before exiting this method.
1133 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1134 ActCleanup(Act.get());
1136 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1139 if (SavedMainFileBuffer) {
1140 std::string ModName = getPreambleFile(this);
1141 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1142 PreambleDiagnostics, StoredDiagnostics);
1145 if (!Act->Execute())
1148 transferASTDataFromCompilerInstance(*Clang);
1150 Act->EndSourceFile();
1152 FailedParseDiagnostics.clear();
1157 // Remove the overridden buffer we used for the preamble.
1158 SavedMainFileBuffer = nullptr;
1160 // Keep the ownership of the data in the ASTUnit because the client may
1161 // want to see the diagnostics.
1162 transferASTDataFromCompilerInstance(*Clang);
1163 FailedParseDiagnostics.swap(StoredDiagnostics);
1164 StoredDiagnostics.clear();
1165 NumStoredDiagnosticsFromDriver = 0;
1169 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1170 static std::string GetPreamblePCHPath() {
1171 // FIXME: This is a hack so that we can override the preamble file during
1172 // crash-recovery testing, which is the only case where the preamble files
1173 // are not necessarily cleaned up.
1174 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1178 SmallString<128> Path;
1179 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1184 /// \brief Compute the preamble for the main file, providing the source buffer
1185 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1186 /// that describes the preamble.
1187 ASTUnit::ComputedPreamble
1188 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1189 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1190 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1192 // Try to determine if the main file has been remapped, either from the
1193 // command line (to another file) or directly through the compiler invocation
1194 // (to a memory buffer).
1195 llvm::MemoryBuffer *Buffer = nullptr;
1196 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1197 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1198 llvm::sys::fs::UniqueID MainFileID;
1199 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1200 // Check whether there is a file-file remapping of the main file
1201 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1202 std::string MPath(RF.first);
1203 llvm::sys::fs::UniqueID MID;
1204 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1205 if (MainFileID == MID) {
1206 // We found a remapping. Try to load the resulting, remapped source.
1207 BufferOwner = getBufferForFile(RF.second);
1209 return ComputedPreamble(nullptr, nullptr, 0, true);
1214 // Check whether there is a file-buffer remapping. It supercedes the
1215 // file-file remapping.
1216 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1217 std::string MPath(RB.first);
1218 llvm::sys::fs::UniqueID MID;
1219 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1220 if (MainFileID == MID) {
1221 // We found a remapping.
1222 BufferOwner.reset();
1223 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1229 // If the main source file was not remapped, load it now.
1230 if (!Buffer && !BufferOwner) {
1231 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1233 return ComputedPreamble(nullptr, nullptr, 0, true);
1237 Buffer = BufferOwner.get();
1238 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1239 *Invocation.getLangOpts(), MaxLines);
1240 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1244 ASTUnit::PreambleFileHash
1245 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1246 PreambleFileHash Result;
1248 Result.ModTime = ModTime;
1249 memset(Result.MD5, 0, sizeof(Result.MD5));
1253 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1254 const llvm::MemoryBuffer *Buffer) {
1255 PreambleFileHash Result;
1256 Result.Size = Buffer->getBufferSize();
1260 MD5Ctx.update(Buffer->getBuffer().data());
1261 MD5Ctx.final(Result.MD5);
1267 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1268 const ASTUnit::PreambleFileHash &RHS) {
1269 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1270 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1272 } // namespace clang
1274 static std::pair<unsigned, unsigned>
1275 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1276 const LangOptions &LangOpts) {
1277 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1278 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1279 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1280 return std::make_pair(Offset, EndOffset);
1283 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1284 const LangOptions &LangOpts,
1285 const FixItHint &InFix) {
1286 ASTUnit::StandaloneFixIt OutFix;
1287 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1288 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1290 OutFix.CodeToInsert = InFix.CodeToInsert;
1291 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1295 static ASTUnit::StandaloneDiagnostic
1296 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1297 const StoredDiagnostic &InDiag) {
1298 ASTUnit::StandaloneDiagnostic OutDiag;
1299 OutDiag.ID = InDiag.getID();
1300 OutDiag.Level = InDiag.getLevel();
1301 OutDiag.Message = InDiag.getMessage();
1302 OutDiag.LocOffset = 0;
1303 if (InDiag.getLocation().isInvalid())
1305 const SourceManager &SM = InDiag.getLocation().getManager();
1306 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1307 OutDiag.Filename = SM.getFilename(FileLoc);
1308 if (OutDiag.Filename.empty())
1310 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1311 for (const CharSourceRange &Range : InDiag.getRanges())
1312 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1313 for (const FixItHint &FixIt : InDiag.getFixIts())
1314 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1319 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1320 /// the source file.
1322 /// This routine will compute the preamble of the main source file. If a
1323 /// non-trivial preamble is found, it will precompile that preamble into a
1324 /// precompiled header so that the precompiled preamble can be used to reduce
1325 /// reparsing time. If a precompiled preamble has already been constructed,
1326 /// this routine will determine if it is still valid and, if so, avoid
1327 /// rebuilding the precompiled preamble.
1329 /// \param AllowRebuild When true (the default), this routine is
1330 /// allowed to rebuild the precompiled preamble if it is found to be
1333 /// \param MaxLines When non-zero, the maximum number of lines that
1334 /// can occur within the preamble.
1336 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1337 /// buffer that should be used in place of the main file when doing so.
1338 /// Otherwise, returns a NULL pointer.
1339 std::unique_ptr<llvm::MemoryBuffer>
1340 ASTUnit::getMainBufferWithPrecompiledPreamble(
1341 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1342 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1343 unsigned MaxLines) {
1345 IntrusiveRefCntPtr<CompilerInvocation>
1346 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1347 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1348 PreprocessorOptions &PreprocessorOpts
1349 = PreambleInvocation->getPreprocessorOpts();
1351 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1353 if (!NewPreamble.Size) {
1354 // We couldn't find a preamble in the main source. Clear out the current
1355 // preamble, if we have one. It's obviously no good any more.
1357 erasePreambleFile(this);
1359 // The next time we actually see a preamble, precompile it.
1360 PreambleRebuildCounter = 1;
1364 if (!Preamble.empty()) {
1365 // We've previously computed a preamble. Check whether we have the same
1366 // preamble now that we did before, and that there's enough space in
1367 // the main-file buffer within the precompiled preamble to fit the
1369 if (Preamble.size() == NewPreamble.Size &&
1370 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1371 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1372 NewPreamble.Size) == 0) {
1373 // The preamble has not changed. We may be able to re-use the precompiled
1376 // Check that none of the files used by the preamble have changed.
1377 bool AnyFileChanged = false;
1379 // First, make a record of those files that have been overridden via
1380 // remapping or unsaved_files.
1381 llvm::StringMap<PreambleFileHash> OverriddenFiles;
1382 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1387 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1388 // If we can't stat the file we're remapping to, assume that something
1389 // horrible happened.
1390 AnyFileChanged = true;
1394 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
1395 Status.getSize(), Status.getLastModificationTime().toEpochTime());
1398 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1401 OverriddenFiles[RB.first] =
1402 PreambleFileHash::createForMemoryBuffer(RB.second);
1405 // Check whether anything has changed.
1406 for (llvm::StringMap<PreambleFileHash>::iterator
1407 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1408 !AnyFileChanged && F != FEnd;
1410 llvm::StringMap<PreambleFileHash>::iterator Overridden
1411 = OverriddenFiles.find(F->first());
1412 if (Overridden != OverriddenFiles.end()) {
1413 // This file was remapped; check whether the newly-mapped file
1414 // matches up with the previous mapping.
1415 if (Overridden->second != F->second)
1416 AnyFileChanged = true;
1420 // The file was not remapped; check whether it has changed on disk.
1422 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1423 // If we can't stat the file, assume that something horrible happened.
1424 AnyFileChanged = true;
1425 } else if (Status.getSize() != uint64_t(F->second.Size) ||
1426 Status.getLastModificationTime().toEpochTime() !=
1427 uint64_t(F->second.ModTime))
1428 AnyFileChanged = true;
1431 if (!AnyFileChanged) {
1432 // Okay! We can re-use the precompiled preamble.
1434 // Set the state of the diagnostic object to mimic its state
1435 // after parsing the preamble.
1436 getDiagnostics().Reset();
1437 ProcessWarningOptions(getDiagnostics(),
1438 PreambleInvocation->getDiagnosticOpts());
1439 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1441 return llvm::MemoryBuffer::getMemBufferCopy(
1442 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1446 // If we aren't allowed to rebuild the precompiled preamble, just
1451 // We can't reuse the previously-computed preamble. Build a new one.
1453 PreambleDiagnostics.clear();
1454 erasePreambleFile(this);
1455 PreambleRebuildCounter = 1;
1456 } else if (!AllowRebuild) {
1457 // We aren't allowed to rebuild the precompiled preamble; just
1462 // If the preamble rebuild counter > 1, it's because we previously
1463 // failed to build a preamble and we're not yet ready to try
1464 // again. Decrement the counter and return a failure.
1465 if (PreambleRebuildCounter > 1) {
1466 --PreambleRebuildCounter;
1470 // Create a temporary file for the precompiled preamble. In rare
1471 // circumstances, this can fail.
1472 std::string PreamblePCHPath = GetPreamblePCHPath();
1473 if (PreamblePCHPath.empty()) {
1474 // Try again next time.
1475 PreambleRebuildCounter = 1;
1479 // We did not previously compute a preamble, or it can't be reused anyway.
1480 SimpleTimer PreambleTimer(WantTiming);
1481 PreambleTimer.setOutput("Precompiling preamble");
1483 // Save the preamble text for later; we'll need to compare against it for
1484 // subsequent reparses.
1485 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1486 Preamble.assign(FileMgr->getFile(MainFilename),
1487 NewPreamble.Buffer->getBufferStart(),
1488 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1489 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1491 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1492 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1494 // Remap the main source file to the preamble buffer.
1495 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1496 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1498 // Tell the compiler invocation to generate a temporary precompiled header.
1499 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1500 // FIXME: Generate the precompiled header into memory?
1501 FrontendOpts.OutputFile = PreamblePCHPath;
1502 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1503 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1505 // Create the compiler instance to use for building the precompiled preamble.
1506 std::unique_ptr<CompilerInstance> Clang(
1507 new CompilerInstance(PCHContainerOps));
1509 // Recover resources if we crash before exiting this method.
1510 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1511 CICleanup(Clang.get());
1513 Clang->setInvocation(&*PreambleInvocation);
1514 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1516 // Set up diagnostics, capturing all of the diagnostics produced.
1517 Clang->setDiagnostics(&getDiagnostics());
1519 // Create the target instance.
1520 Clang->setTarget(TargetInfo::CreateTargetInfo(
1521 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1522 if (!Clang->hasTarget()) {
1523 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1525 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1526 PreprocessorOpts.RemappedFileBuffers.pop_back();
1530 // Inform the target of the language options.
1532 // FIXME: We shouldn't need to do this, the target should be immutable once
1533 // created. This complexity should be lifted elsewhere.
1534 Clang->getTarget().adjust(Clang->getLangOpts());
1536 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1537 "Invocation must have exactly one source file!");
1538 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1539 "FIXME: AST inputs not yet supported here!");
1540 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1541 "IR inputs not support here!");
1543 // Clear out old caches and data.
1544 getDiagnostics().Reset();
1545 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1546 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1547 TopLevelDecls.clear();
1548 TopLevelDeclsInPreamble.clear();
1549 PreambleDiagnostics.clear();
1551 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1552 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1556 // Create a file manager object to provide access to and cache the filesystem.
1557 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1559 // Create the source manager.
1560 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1561 Clang->getFileManager()));
1563 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1564 Clang->addDependencyCollector(PreambleDepCollector);
1566 std::unique_ptr<PrecompilePreambleAction> Act;
1567 Act.reset(new PrecompilePreambleAction(*this));
1568 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1569 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1571 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1572 PreprocessorOpts.RemappedFileBuffers.pop_back();
1578 // Transfer any diagnostics generated when parsing the preamble into the set
1579 // of preamble diagnostics.
1580 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1581 E = stored_diag_end();
1583 PreambleDiagnostics.push_back(
1584 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1586 Act->EndSourceFile();
1588 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1590 if (!Act->hasEmittedPreamblePCH()) {
1591 // The preamble PCH failed (e.g. there was a module loading fatal error),
1592 // so no precompiled header was generated. Forget that we even tried.
1593 // FIXME: Should we leave a note for ourselves to try again?
1594 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1596 TopLevelDeclsInPreamble.clear();
1597 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1598 PreprocessorOpts.RemappedFileBuffers.pop_back();
1602 // Keep track of the preamble we precompiled.
1603 setPreambleFile(this, FrontendOpts.OutputFile);
1604 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1606 // Keep track of all of the files that the source manager knows about,
1607 // so we can verify whether they have changed or not.
1608 FilesInPreamble.clear();
1609 SourceManager &SourceMgr = Clang->getSourceManager();
1610 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1611 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1612 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1614 if (time_t ModTime = File->getModificationTime()) {
1615 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1616 File->getSize(), ModTime);
1618 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1619 FilesInPreamble[File->getName()] =
1620 PreambleFileHash::createForMemoryBuffer(Buffer);
1624 PreambleRebuildCounter = 1;
1625 PreprocessorOpts.RemappedFileBuffers.pop_back();
1627 // If the hash of top-level entities differs from the hash of the top-level
1628 // entities the last time we rebuilt the preamble, clear out the completion
1630 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1631 CompletionCacheTopLevelHashValue = 0;
1632 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1635 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1639 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1640 std::vector<Decl *> Resolved;
1641 Resolved.reserve(TopLevelDeclsInPreamble.size());
1642 ExternalASTSource &Source = *getASTContext().getExternalSource();
1643 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1644 // Resolve the declaration ID to an actual declaration, possibly
1645 // deserializing the declaration in the process.
1646 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1647 Resolved.push_back(D);
1649 TopLevelDeclsInPreamble.clear();
1650 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1653 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1654 // Steal the created target, context, and preprocessor if they have been
1656 assert(CI.hasInvocation() && "missing invocation");
1657 LangOpts = CI.getInvocation().LangOpts;
1658 TheSema = CI.takeSema();
1659 Consumer = CI.takeASTConsumer();
1660 if (CI.hasASTContext())
1661 Ctx = &CI.getASTContext();
1662 if (CI.hasPreprocessor())
1663 PP = &CI.getPreprocessor();
1664 CI.setSourceManager(nullptr);
1665 CI.setFileManager(nullptr);
1667 Target = &CI.getTarget();
1668 Reader = CI.getModuleManager();
1669 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1672 StringRef ASTUnit::getMainFileName() const {
1673 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1674 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1676 return Input.getFile();
1678 return Input.getBuffer()->getBufferIdentifier();
1682 if (const FileEntry *
1683 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1684 return FE->getName();
1690 StringRef ASTUnit::getASTFileName() const {
1691 if (!isMainFileAST())
1694 serialization::ModuleFile &
1695 Mod = Reader->getModuleManager().getPrimaryModule();
1696 return Mod.FileName;
1699 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1700 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1701 bool CaptureDiagnostics,
1702 bool UserFilesAreVolatile) {
1703 std::unique_ptr<ASTUnit> AST;
1704 AST.reset(new ASTUnit(false));
1705 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1706 AST->Diagnostics = Diags;
1707 AST->Invocation = CI;
1708 AST->FileSystemOpts = CI->getFileSystemOpts();
1709 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1710 createVFSFromCompilerInvocation(*CI, *Diags);
1713 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1714 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1715 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1716 UserFilesAreVolatile);
1718 return AST.release();
1721 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1722 CompilerInvocation *CI,
1723 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1724 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, ASTFrontendAction *Action,
1725 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1726 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1727 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1728 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1729 assert(CI && "A CompilerInvocation is required");
1731 std::unique_ptr<ASTUnit> OwnAST;
1732 ASTUnit *AST = Unit;
1734 // Create the AST unit.
1735 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1741 if (!ResourceFilesPath.empty()) {
1742 // Override the resources path.
1743 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1745 AST->OnlyLocalDecls = OnlyLocalDecls;
1746 AST->CaptureDiagnostics = CaptureDiagnostics;
1747 if (PrecompilePreamble)
1748 AST->PreambleRebuildCounter = 2;
1749 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1750 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1751 AST->IncludeBriefCommentsInCodeCompletion
1752 = IncludeBriefCommentsInCodeCompletion;
1754 // Recover resources if we crash before exiting this method.
1755 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1756 ASTUnitCleanup(OwnAST.get());
1757 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1758 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1759 DiagCleanup(Diags.get());
1761 // We'll manage file buffers ourselves.
1762 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1763 CI->getFrontendOpts().DisableFree = false;
1764 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1766 // Create the compiler instance to use for building the AST.
1767 std::unique_ptr<CompilerInstance> Clang(
1768 new CompilerInstance(PCHContainerOps));
1770 // Recover resources if we crash before exiting this method.
1771 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1772 CICleanup(Clang.get());
1774 Clang->setInvocation(CI);
1775 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1777 // Set up diagnostics, capturing any diagnostics that would
1778 // otherwise be dropped.
1779 Clang->setDiagnostics(&AST->getDiagnostics());
1781 // Create the target instance.
1782 Clang->setTarget(TargetInfo::CreateTargetInfo(
1783 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1784 if (!Clang->hasTarget())
1787 // Inform the target of the language options.
1789 // FIXME: We shouldn't need to do this, the target should be immutable once
1790 // created. This complexity should be lifted elsewhere.
1791 Clang->getTarget().adjust(Clang->getLangOpts());
1793 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1794 "Invocation must have exactly one source file!");
1795 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1796 "FIXME: AST inputs not yet supported here!");
1797 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1798 "IR inputs not supported here!");
1800 // Configure the various subsystems.
1801 AST->TheSema.reset();
1804 AST->Reader = nullptr;
1806 // Create a file manager object to provide access to and cache the filesystem.
1807 Clang->setFileManager(&AST->getFileManager());
1809 // Create the source manager.
1810 Clang->setSourceManager(&AST->getSourceManager());
1812 ASTFrontendAction *Act = Action;
1814 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1816 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1817 Act = TrackerAct.get();
1820 // Recover resources if we crash before exiting this method.
1821 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1822 ActCleanup(TrackerAct.get());
1824 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1825 AST->transferASTDataFromCompilerInstance(*Clang);
1826 if (OwnAST && ErrAST)
1827 ErrAST->swap(OwnAST);
1832 if (Persistent && !TrackerAct) {
1833 Clang->getPreprocessor().addPPCallbacks(
1834 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1835 AST->getCurrentTopLevelHashValue()));
1836 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1837 if (Clang->hasASTConsumer())
1838 Consumers.push_back(Clang->takeASTConsumer());
1839 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1840 *AST, AST->getCurrentTopLevelHashValue()));
1841 Clang->setASTConsumer(
1842 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1844 if (!Act->Execute()) {
1845 AST->transferASTDataFromCompilerInstance(*Clang);
1846 if (OwnAST && ErrAST)
1847 ErrAST->swap(OwnAST);
1852 // Steal the created target, context, and preprocessor.
1853 AST->transferASTDataFromCompilerInstance(*Clang);
1855 Act->EndSourceFile();
1858 return OwnAST.release();
1863 bool ASTUnit::LoadFromCompilerInvocation(
1864 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1865 bool PrecompilePreamble) {
1869 // We'll manage file buffers ourselves.
1870 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1871 Invocation->getFrontendOpts().DisableFree = false;
1872 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1874 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1875 if (PrecompilePreamble) {
1876 PreambleRebuildCounter = 2;
1877 OverrideMainBuffer =
1878 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1881 SimpleTimer ParsingTimer(WantTiming);
1882 ParsingTimer.setOutput("Parsing " + getMainFileName());
1884 // Recover resources if we crash before exiting this method.
1885 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1886 MemBufferCleanup(OverrideMainBuffer.get());
1888 return Parse(PCHContainerOps, std::move(OverrideMainBuffer));
1891 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1892 CompilerInvocation *CI,
1893 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1894 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool OnlyLocalDecls,
1895 bool CaptureDiagnostics, bool PrecompilePreamble,
1896 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1897 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
1898 // Create the AST unit.
1899 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1900 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1901 AST->Diagnostics = Diags;
1902 AST->OnlyLocalDecls = OnlyLocalDecls;
1903 AST->CaptureDiagnostics = CaptureDiagnostics;
1904 AST->TUKind = TUKind;
1905 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1906 AST->IncludeBriefCommentsInCodeCompletion
1907 = IncludeBriefCommentsInCodeCompletion;
1908 AST->Invocation = CI;
1909 AST->FileSystemOpts = CI->getFileSystemOpts();
1910 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1911 createVFSFromCompilerInvocation(*CI, *Diags);
1914 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1915 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1917 // Recover resources if we crash before exiting this method.
1918 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1919 ASTUnitCleanup(AST.get());
1920 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1921 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1922 DiagCleanup(Diags.get());
1924 if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble))
1929 ASTUnit *ASTUnit::LoadFromCommandLine(
1930 const char **ArgBegin, const char **ArgEnd,
1931 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1932 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1933 bool OnlyLocalDecls, bool CaptureDiagnostics,
1934 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1935 bool PrecompilePreamble, TranslationUnitKind TUKind,
1936 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1937 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1938 bool UserFilesAreVolatile, bool ForSerialization,
1939 std::unique_ptr<ASTUnit> *ErrAST) {
1940 assert(Diags.get() && "no DiagnosticsEngine was provided");
1942 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1944 IntrusiveRefCntPtr<CompilerInvocation> CI;
1948 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1951 CI = clang::createInvocationFromCommandLine(
1952 llvm::makeArrayRef(ArgBegin, ArgEnd),
1958 // Override any files that need remapping
1959 for (const auto &RemappedFile : RemappedFiles) {
1960 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1961 RemappedFile.second);
1963 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1964 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1965 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1967 // Override the resources path.
1968 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1970 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1972 // Create the AST unit.
1973 std::unique_ptr<ASTUnit> AST;
1974 AST.reset(new ASTUnit(false));
1975 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1976 AST->Diagnostics = Diags;
1977 AST->FileSystemOpts = CI->getFileSystemOpts();
1978 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1979 createVFSFromCompilerInvocation(*CI, *Diags);
1982 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1983 AST->OnlyLocalDecls = OnlyLocalDecls;
1984 AST->CaptureDiagnostics = CaptureDiagnostics;
1985 AST->TUKind = TUKind;
1986 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1987 AST->IncludeBriefCommentsInCodeCompletion
1988 = IncludeBriefCommentsInCodeCompletion;
1989 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1990 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1991 AST->StoredDiagnostics.swap(StoredDiagnostics);
1992 AST->Invocation = CI;
1993 if (ForSerialization)
1994 AST->WriterData.reset(new ASTWriterData());
1995 // Zero out now to ease cleanup during crash recovery.
1999 // Recover resources if we crash before exiting this method.
2000 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2001 ASTUnitCleanup(AST.get());
2003 if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble)) {
2004 // Some error occurred, if caller wants to examine diagnostics, pass it the
2007 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2013 return AST.release();
2016 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2017 ArrayRef<RemappedFile> RemappedFiles) {
2021 clearFileLevelDecls();
2023 SimpleTimer ParsingTimer(WantTiming);
2024 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2027 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2028 for (const auto &RB : PPOpts.RemappedFileBuffers)
2031 Invocation->getPreprocessorOpts().clearRemappedFiles();
2032 for (const auto &RemappedFile : RemappedFiles) {
2033 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2034 RemappedFile.second);
2037 // If we have a preamble file lying around, or if we might try to
2038 // build a precompiled preamble, do so now.
2039 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2040 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2041 OverrideMainBuffer =
2042 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2044 // Clear out the diagnostics state.
2045 getDiagnostics().Reset();
2046 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2047 if (OverrideMainBuffer)
2048 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2050 // Parse the sources
2051 bool Result = Parse(PCHContainerOps, std::move(OverrideMainBuffer));
2053 // If we're caching global code-completion results, and the top-level
2054 // declarations have changed, clear out the code-completion cache.
2055 if (!Result && ShouldCacheCodeCompletionResults &&
2056 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2057 CacheCodeCompletionResults();
2059 // We now need to clear out the completion info related to this translation
2060 // unit; it'll be recreated if necessary.
2066 //----------------------------------------------------------------------------//
2068 //----------------------------------------------------------------------------//
2071 /// \brief Code completion consumer that combines the cached code-completion
2072 /// results from an ASTUnit with the code-completion results provided to it,
2073 /// then passes the result on to
2074 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2075 uint64_t NormalContexts;
2077 CodeCompleteConsumer &Next;
2080 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2081 const CodeCompleteOptions &CodeCompleteOpts)
2082 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2083 AST(AST), Next(Next)
2085 // Compute the set of contexts in which we will look when we don't have
2086 // any information about the specific context.
2088 = (1LL << CodeCompletionContext::CCC_TopLevel)
2089 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2090 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2091 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2092 | (1LL << CodeCompletionContext::CCC_Statement)
2093 | (1LL << CodeCompletionContext::CCC_Expression)
2094 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2095 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2096 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2097 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2098 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2099 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2100 | (1LL << CodeCompletionContext::CCC_Recovery);
2102 if (AST.getASTContext().getLangOpts().CPlusPlus)
2103 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2104 | (1LL << CodeCompletionContext::CCC_UnionTag)
2105 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2108 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2109 CodeCompletionResult *Results,
2110 unsigned NumResults) override;
2112 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2113 OverloadCandidate *Candidates,
2114 unsigned NumCandidates) override {
2115 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2118 CodeCompletionAllocator &getAllocator() override {
2119 return Next.getAllocator();
2122 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2123 return Next.getCodeCompletionTUInfo();
2128 /// \brief Helper function that computes which global names are hidden by the
2129 /// local code-completion results.
2130 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2131 CodeCompletionResult *Results,
2132 unsigned NumResults,
2134 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2135 bool OnlyTagNames = false;
2136 switch (Context.getKind()) {
2137 case CodeCompletionContext::CCC_Recovery:
2138 case CodeCompletionContext::CCC_TopLevel:
2139 case CodeCompletionContext::CCC_ObjCInterface:
2140 case CodeCompletionContext::CCC_ObjCImplementation:
2141 case CodeCompletionContext::CCC_ObjCIvarList:
2142 case CodeCompletionContext::CCC_ClassStructUnion:
2143 case CodeCompletionContext::CCC_Statement:
2144 case CodeCompletionContext::CCC_Expression:
2145 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2146 case CodeCompletionContext::CCC_DotMemberAccess:
2147 case CodeCompletionContext::CCC_ArrowMemberAccess:
2148 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2149 case CodeCompletionContext::CCC_Namespace:
2150 case CodeCompletionContext::CCC_Type:
2151 case CodeCompletionContext::CCC_Name:
2152 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2153 case CodeCompletionContext::CCC_ParenthesizedExpression:
2154 case CodeCompletionContext::CCC_ObjCInterfaceName:
2157 case CodeCompletionContext::CCC_EnumTag:
2158 case CodeCompletionContext::CCC_UnionTag:
2159 case CodeCompletionContext::CCC_ClassOrStructTag:
2160 OnlyTagNames = true;
2163 case CodeCompletionContext::CCC_ObjCProtocolName:
2164 case CodeCompletionContext::CCC_MacroName:
2165 case CodeCompletionContext::CCC_MacroNameUse:
2166 case CodeCompletionContext::CCC_PreprocessorExpression:
2167 case CodeCompletionContext::CCC_PreprocessorDirective:
2168 case CodeCompletionContext::CCC_NaturalLanguage:
2169 case CodeCompletionContext::CCC_SelectorName:
2170 case CodeCompletionContext::CCC_TypeQualifiers:
2171 case CodeCompletionContext::CCC_Other:
2172 case CodeCompletionContext::CCC_OtherWithMacros:
2173 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2174 case CodeCompletionContext::CCC_ObjCClassMessage:
2175 case CodeCompletionContext::CCC_ObjCCategoryName:
2176 // We're looking for nothing, or we're looking for names that cannot
2181 typedef CodeCompletionResult Result;
2182 for (unsigned I = 0; I != NumResults; ++I) {
2183 if (Results[I].Kind != Result::RK_Declaration)
2187 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2189 bool Hiding = false;
2191 Hiding = (IDNS & Decl::IDNS_Tag);
2193 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2194 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2195 Decl::IDNS_NonMemberOperator);
2196 if (Ctx.getLangOpts().CPlusPlus)
2197 HiddenIDNS |= Decl::IDNS_Tag;
2198 Hiding = (IDNS & HiddenIDNS);
2204 DeclarationName Name = Results[I].Declaration->getDeclName();
2205 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2206 HiddenNames.insert(Identifier->getName());
2208 HiddenNames.insert(Name.getAsString());
2213 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2214 CodeCompletionContext Context,
2215 CodeCompletionResult *Results,
2216 unsigned NumResults) {
2217 // Merge the results we were given with the results we cached.
2218 bool AddedResult = false;
2219 uint64_t InContexts =
2220 Context.getKind() == CodeCompletionContext::CCC_Recovery
2221 ? NormalContexts : (1LL << Context.getKind());
2222 // Contains the set of names that are hidden by "local" completion results.
2223 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2224 typedef CodeCompletionResult Result;
2225 SmallVector<Result, 8> AllResults;
2226 for (ASTUnit::cached_completion_iterator
2227 C = AST.cached_completion_begin(),
2228 CEnd = AST.cached_completion_end();
2230 // If the context we are in matches any of the contexts we are
2231 // interested in, we'll add this result.
2232 if ((C->ShowInContexts & InContexts) == 0)
2235 // If we haven't added any results previously, do so now.
2237 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2239 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2243 // Determine whether this global completion result is hidden by a local
2244 // completion result. If so, skip it.
2245 if (C->Kind != CXCursor_MacroDefinition &&
2246 HiddenNames.count(C->Completion->getTypedText()))
2249 // Adjust priority based on similar type classes.
2250 unsigned Priority = C->Priority;
2251 CodeCompletionString *Completion = C->Completion;
2252 if (!Context.getPreferredType().isNull()) {
2253 if (C->Kind == CXCursor_MacroDefinition) {
2254 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2256 Context.getPreferredType()->isAnyPointerType());
2257 } else if (C->Type) {
2258 CanQualType Expected
2259 = S.Context.getCanonicalType(
2260 Context.getPreferredType().getUnqualifiedType());
2261 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2262 if (ExpectedSTC == C->TypeClass) {
2263 // We know this type is similar; check for an exact match.
2264 llvm::StringMap<unsigned> &CachedCompletionTypes
2265 = AST.getCachedCompletionTypes();
2266 llvm::StringMap<unsigned>::iterator Pos
2267 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2268 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2269 Priority /= CCF_ExactTypeMatch;
2271 Priority /= CCF_SimilarTypeMatch;
2276 // Adjust the completion string, if required.
2277 if (C->Kind == CXCursor_MacroDefinition &&
2278 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2279 // Create a new code-completion string that just contains the
2280 // macro name, without its arguments.
2281 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2282 CCP_CodePattern, C->Availability);
2283 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2284 Priority = CCP_CodePattern;
2285 Completion = Builder.TakeString();
2288 AllResults.push_back(Result(Completion, Priority, C->Kind,
2292 // If we did not add any cached completion results, just forward the
2293 // results we were given to the next consumer.
2295 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2299 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2303 void ASTUnit::CodeComplete(
2304 StringRef File, unsigned Line, unsigned Column,
2305 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2306 bool IncludeCodePatterns, bool IncludeBriefComments,
2307 CodeCompleteConsumer &Consumer,
2308 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2309 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2310 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2311 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2315 SimpleTimer CompletionTimer(WantTiming);
2316 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2317 Twine(Line) + ":" + Twine(Column));
2319 IntrusiveRefCntPtr<CompilerInvocation>
2320 CCInvocation(new CompilerInvocation(*Invocation));
2322 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2323 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2324 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2326 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2327 CachedCompletionResults.empty();
2328 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2329 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2330 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2332 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2334 FrontendOpts.CodeCompletionAt.FileName = File;
2335 FrontendOpts.CodeCompletionAt.Line = Line;
2336 FrontendOpts.CodeCompletionAt.Column = Column;
2338 // Set the language options appropriately.
2339 LangOpts = *CCInvocation->getLangOpts();
2341 // Spell-checking and warnings are wasteful during code-completion.
2342 LangOpts.SpellChecking = false;
2343 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2345 std::unique_ptr<CompilerInstance> Clang(
2346 new CompilerInstance(PCHContainerOps));
2348 // Recover resources if we crash before exiting this method.
2349 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2350 CICleanup(Clang.get());
2352 Clang->setInvocation(&*CCInvocation);
2353 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2355 // Set up diagnostics, capturing any diagnostics produced.
2356 Clang->setDiagnostics(&Diag);
2357 CaptureDroppedDiagnostics Capture(true,
2358 Clang->getDiagnostics(),
2360 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2362 // Create the target instance.
2363 Clang->setTarget(TargetInfo::CreateTargetInfo(
2364 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2365 if (!Clang->hasTarget()) {
2366 Clang->setInvocation(nullptr);
2370 // Inform the target of the language options.
2372 // FIXME: We shouldn't need to do this, the target should be immutable once
2373 // created. This complexity should be lifted elsewhere.
2374 Clang->getTarget().adjust(Clang->getLangOpts());
2376 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2377 "Invocation must have exactly one source file!");
2378 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2379 "FIXME: AST inputs not yet supported here!");
2380 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2381 "IR inputs not support here!");
2384 // Use the source and file managers that we were given.
2385 Clang->setFileManager(&FileMgr);
2386 Clang->setSourceManager(&SourceMgr);
2389 PreprocessorOpts.clearRemappedFiles();
2390 PreprocessorOpts.RetainRemappedFileBuffers = true;
2391 for (const auto &RemappedFile : RemappedFiles) {
2392 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2393 OwnedBuffers.push_back(RemappedFile.second);
2396 // Use the code completion consumer we were given, but adding any cached
2397 // code-completion results.
2398 AugmentedCodeCompleteConsumer *AugmentedConsumer
2399 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2400 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2402 // If we have a precompiled preamble, try to use it. We only allow
2403 // the use of the precompiled preamble if we're if the completion
2404 // point is within the main file, after the end of the precompiled
2406 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2407 if (!getPreambleFile(this).empty()) {
2408 std::string CompleteFilePath(File);
2409 llvm::sys::fs::UniqueID CompleteFileID;
2411 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2412 std::string MainPath(OriginalSourceFile);
2413 llvm::sys::fs::UniqueID MainID;
2414 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2415 if (CompleteFileID == MainID && Line > 1)
2416 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2417 PCHContainerOps, *CCInvocation, false, Line - 1);
2422 // If the main file has been overridden due to the use of a preamble,
2423 // make that override happen and introduce the preamble.
2424 if (OverrideMainBuffer) {
2425 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2426 OverrideMainBuffer.get());
2427 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2428 PreprocessorOpts.PrecompiledPreambleBytes.second
2429 = PreambleEndsAtStartOfLine;
2430 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2431 PreprocessorOpts.DisablePCHValidation = true;
2433 OwnedBuffers.push_back(OverrideMainBuffer.release());
2435 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2436 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2439 // Disable the preprocessing record if modules are not enabled.
2440 if (!Clang->getLangOpts().Modules)
2441 PreprocessorOpts.DetailedRecord = false;
2443 std::unique_ptr<SyntaxOnlyAction> Act;
2444 Act.reset(new SyntaxOnlyAction);
2445 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2447 Act->EndSourceFile();
2451 bool ASTUnit::Save(StringRef File) {
2452 if (HadModuleLoaderFatalFailure)
2455 // Write to a temporary file and later rename it to the actual file, to avoid
2456 // possible race conditions.
2457 SmallString<128> TempPath;
2459 TempPath += "-%%%%%%%%";
2461 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2464 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2465 // unconditionally create a stat cache when we parse the file?
2466 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2470 if (Out.has_error()) {
2475 if (llvm::sys::fs::rename(TempPath, File)) {
2476 llvm::sys::fs::remove(TempPath);
2483 static bool serializeUnit(ASTWriter &Writer,
2484 SmallVectorImpl<char> &Buffer,
2488 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2490 // Write the generated bitstream to "Out".
2491 if (!Buffer.empty())
2492 OS.write(Buffer.data(), Buffer.size());
2497 bool ASTUnit::serialize(raw_ostream &OS) {
2498 bool hasErrors = getDiagnostics().hasErrorOccurred();
2501 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2502 getSema(), hasErrors, OS);
2504 SmallString<128> Buffer;
2505 llvm::BitstreamWriter Stream(Buffer);
2506 ASTWriter Writer(Stream);
2507 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2510 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2512 void ASTUnit::TranslateStoredDiagnostics(
2513 FileManager &FileMgr,
2514 SourceManager &SrcMgr,
2515 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2516 SmallVectorImpl<StoredDiagnostic> &Out) {
2517 // Map the standalone diagnostic into the new source manager. We also need to
2518 // remap all the locations to the new view. This includes the diag location,
2519 // any associated source ranges, and the source ranges of associated fix-its.
2520 // FIXME: There should be a cleaner way to do this.
2522 SmallVector<StoredDiagnostic, 4> Result;
2523 Result.reserve(Diags.size());
2524 for (const StandaloneDiagnostic &SD : Diags) {
2525 // Rebuild the StoredDiagnostic.
2526 if (SD.Filename.empty())
2528 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2531 FileID FID = SrcMgr.translateFile(FE);
2532 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2533 if (FileLoc.isInvalid())
2535 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2536 FullSourceLoc Loc(L, SrcMgr);
2538 SmallVector<CharSourceRange, 4> Ranges;
2539 Ranges.reserve(SD.Ranges.size());
2540 for (const auto &Range : SD.Ranges) {
2541 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2542 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2543 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2546 SmallVector<FixItHint, 2> FixIts;
2547 FixIts.reserve(SD.FixIts.size());
2548 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2549 FixIts.push_back(FixItHint());
2550 FixItHint &FH = FixIts.back();
2551 FH.CodeToInsert = FixIt.CodeToInsert;
2552 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2553 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2554 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2557 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2558 SD.Message, Loc, Ranges, FixIts));
2563 void ASTUnit::addFileLevelDecl(Decl *D) {
2566 // We only care about local declarations.
2567 if (D->isFromASTFile())
2570 SourceManager &SM = *SourceMgr;
2571 SourceLocation Loc = D->getLocation();
2572 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2575 // We only keep track of the file-level declarations of each file.
2576 if (!D->getLexicalDeclContext()->isFileContext())
2579 SourceLocation FileLoc = SM.getFileLoc(Loc);
2580 assert(SM.isLocalSourceLocation(FileLoc));
2583 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2584 if (FID.isInvalid())
2587 LocDeclsTy *&Decls = FileDecls[FID];
2589 Decls = new LocDeclsTy();
2591 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2593 if (Decls->empty() || Decls->back().first <= Offset) {
2594 Decls->push_back(LocDecl);
2598 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2599 LocDecl, llvm::less_first());
2601 Decls->insert(I, LocDecl);
2604 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2605 SmallVectorImpl<Decl *> &Decls) {
2606 if (File.isInvalid())
2609 if (SourceMgr->isLoadedFileID(File)) {
2610 assert(Ctx->getExternalSource() && "No external source!");
2611 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2615 FileDeclsTy::iterator I = FileDecls.find(File);
2616 if (I == FileDecls.end())
2619 LocDeclsTy &LocDecls = *I->second;
2620 if (LocDecls.empty())
2623 LocDeclsTy::iterator BeginIt =
2624 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2625 std::make_pair(Offset, (Decl *)nullptr),
2626 llvm::less_first());
2627 if (BeginIt != LocDecls.begin())
2630 // If we are pointing at a top-level decl inside an objc container, we need
2631 // to backtrack until we find it otherwise we will fail to report that the
2632 // region overlaps with an objc container.
2633 while (BeginIt != LocDecls.begin() &&
2634 BeginIt->second->isTopLevelDeclInObjCContainer())
2637 LocDeclsTy::iterator EndIt = std::upper_bound(
2638 LocDecls.begin(), LocDecls.end(),
2639 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2640 if (EndIt != LocDecls.end())
2643 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2644 Decls.push_back(DIt->second);
2647 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2648 unsigned Line, unsigned Col) const {
2649 const SourceManager &SM = getSourceManager();
2650 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2651 return SM.getMacroArgExpandedLocation(Loc);
2654 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2655 unsigned Offset) const {
2656 const SourceManager &SM = getSourceManager();
2657 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2658 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2661 /// \brief If \arg Loc is a loaded location from the preamble, returns
2662 /// the corresponding local location of the main file, otherwise it returns
2664 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2667 PreambleID = SourceMgr->getPreambleFileID();
2669 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2673 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2674 SourceLocation FileLoc
2675 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2676 return FileLoc.getLocWithOffset(Offs);
2682 /// \brief If \arg Loc is a local location of the main file but inside the
2683 /// preamble chunk, returns the corresponding loaded location from the
2684 /// preamble, otherwise it returns \arg Loc.
2685 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2688 PreambleID = SourceMgr->getPreambleFileID();
2690 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2694 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2695 Offs < Preamble.size()) {
2696 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2697 return FileLoc.getLocWithOffset(Offs);
2703 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2706 FID = SourceMgr->getPreambleFileID();
2708 if (Loc.isInvalid() || FID.isInvalid())
2711 return SourceMgr->isInFileID(Loc, FID);
2714 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2717 FID = SourceMgr->getMainFileID();
2719 if (Loc.isInvalid() || FID.isInvalid())
2722 return SourceMgr->isInFileID(Loc, FID);
2725 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2728 FID = SourceMgr->getPreambleFileID();
2730 if (FID.isInvalid())
2731 return SourceLocation();
2733 return SourceMgr->getLocForEndOfFile(FID);
2736 SourceLocation ASTUnit::getStartOfMainFileID() {
2739 FID = SourceMgr->getMainFileID();
2741 if (FID.isInvalid())
2742 return SourceLocation();
2744 return SourceMgr->getLocForStartOfFile(FID);
2747 llvm::iterator_range<PreprocessingRecord::iterator>
2748 ASTUnit::getLocalPreprocessingEntities() const {
2749 if (isMainFileAST()) {
2750 serialization::ModuleFile &
2751 Mod = Reader->getModuleManager().getPrimaryModule();
2752 return Reader->getModulePreprocessedEntities(Mod);
2755 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2756 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2758 return llvm::make_range(PreprocessingRecord::iterator(),
2759 PreprocessingRecord::iterator());
2762 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2763 if (isMainFileAST()) {
2764 serialization::ModuleFile &
2765 Mod = Reader->getModuleManager().getPrimaryModule();
2766 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2767 if (!Fn(context, D))
2774 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2775 TLEnd = top_level_end();
2776 TL != TLEnd; ++TL) {
2777 if (!Fn(context, *TL))
2785 struct PCHLocatorInfo {
2786 serialization::ModuleFile *Mod;
2787 PCHLocatorInfo() : Mod(nullptr) {}
2791 static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2792 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2794 case serialization::MK_ImplicitModule:
2795 case serialization::MK_ExplicitModule:
2796 return true; // skip dependencies.
2797 case serialization::MK_PCH:
2799 return true; // found it.
2800 case serialization::MK_Preamble:
2801 return false; // look in dependencies.
2802 case serialization::MK_MainFile:
2803 return false; // look in dependencies.
2809 const FileEntry *ASTUnit::getPCHFile() {
2813 PCHLocatorInfo Info;
2814 Reader->getModuleManager().visit(PCHLocator, &Info);
2816 return Info.Mod->File;
2821 bool ASTUnit::isModuleFile() {
2822 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2825 void ASTUnit::PreambleData::countLines() const {
2830 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2832 if (Buffer.back() != '\n')
2837 ASTUnit::ConcurrencyState::ConcurrencyState() {
2838 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2841 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2842 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2845 void ASTUnit::ConcurrencyState::start() {
2846 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2847 assert(acquired && "Concurrent access to ASTUnit!");
2850 void ASTUnit::ConcurrencyState::finish() {
2851 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2856 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
2857 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2858 void ASTUnit::ConcurrencyState::start() {}
2859 void ASTUnit::ConcurrencyState::finish() {}