1 //===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit Implementation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeOrdering.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/MemoryBufferCache.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Basic/VirtualFileSystem.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/FrontendActions.h"
27 #include "clang/Frontend/FrontendDiagnostic.h"
28 #include "clang/Frontend/FrontendOptions.h"
29 #include "clang/Frontend/MultiplexConsumer.h"
30 #include "clang/Frontend/Utils.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Serialization/ASTReader.h"
36 #include "clang/Serialization/ASTWriter.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringSet.h"
40 #include "llvm/Support/CrashRecoveryContext.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Mutex.h"
44 #include "llvm/Support/MutexGuard.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
53 using llvm::TimeRecord;
62 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
64 Start = TimeRecord::getCurrentTime();
67 void setOutput(const Twine &Output) {
69 this->Output = Output.str();
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
87 /// \brief Erase the preamble file.
88 void CleanPreambleFile();
90 /// \brief Erase temporary files and the preamble file.
95 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
96 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
100 static void cleanupOnDiskMapAtExit();
102 typedef llvm::DenseMap<const ASTUnit *,
103 std::unique_ptr<OnDiskData>> OnDiskDataMap;
104 static OnDiskDataMap &getOnDiskDataMap() {
105 static OnDiskDataMap M;
106 static bool hasRegisteredAtExit = false;
107 if (!hasRegisteredAtExit) {
108 hasRegisteredAtExit = true;
109 atexit(cleanupOnDiskMapAtExit);
114 static void cleanupOnDiskMapAtExit() {
115 // Use the mutex because there can be an alive thread destroying an ASTUnit.
116 llvm::MutexGuard Guard(getOnDiskMutex());
117 for (const auto &I : getOnDiskDataMap()) {
118 // We don't worry about freeing the memory associated with OnDiskDataMap.
119 // All we care about is erasing stale files.
124 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
125 // We require the mutex since we are modifying the structure of the
127 llvm::MutexGuard Guard(getOnDiskMutex());
128 OnDiskDataMap &M = getOnDiskDataMap();
131 D = llvm::make_unique<OnDiskData>();
135 static void erasePreambleFile(const ASTUnit *AU) {
136 getOnDiskData(AU).CleanPreambleFile();
139 static void removeOnDiskEntry(const ASTUnit *AU) {
140 // We require the mutex since we are modifying the structure of the
142 llvm::MutexGuard Guard(getOnDiskMutex());
143 OnDiskDataMap &M = getOnDiskDataMap();
144 OnDiskDataMap::iterator I = M.find(AU);
146 I->second->Cleanup();
151 static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
152 getOnDiskData(AU).PreambleFile = preambleFile;
155 static const std::string &getPreambleFile(const ASTUnit *AU) {
156 return getOnDiskData(AU).PreambleFile;
159 void OnDiskData::CleanPreambleFile() {
160 if (!PreambleFile.empty()) {
161 llvm::sys::fs::remove(PreambleFile);
162 PreambleFile.clear();
166 void OnDiskData::Cleanup() {
170 struct ASTUnit::ASTWriterData {
171 SmallString<128> Buffer;
172 llvm::BitstreamWriter Stream;
175 ASTWriterData(MemoryBufferCache &PCMCache)
176 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
179 void ASTUnit::clearFileLevelDecls() {
180 llvm::DeleteContainerSeconds(FileDecls);
183 /// \brief After failing to build a precompiled preamble (due to
184 /// errors in the source that occurs in the preamble), the number of
185 /// reparses during which we'll skip even trying to precompile the
187 const unsigned DefaultPreambleRebuildInterval = 5;
189 /// \brief Tracks the number of ASTUnit objects that are currently active.
191 /// Used for debugging purposes only.
192 static std::atomic<unsigned> ActiveASTUnitObjects;
194 ASTUnit::ASTUnit(bool _MainFileIsAST)
195 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
196 OnlyLocalDecls(false), CaptureDiagnostics(false),
197 MainFileIsAST(_MainFileIsAST),
198 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
199 OwnsRemappedFileBuffers(true),
200 NumStoredDiagnosticsFromDriver(0),
201 PreambleRebuildCounter(0),
202 NumWarningsInPreamble(0),
203 ShouldCacheCodeCompletionResults(false),
204 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
205 CompletionCacheTopLevelHashValue(0),
206 PreambleTopLevelHashValue(0),
207 CurrentTopLevelHashValue(0),
208 UnsafeToFree(false) {
209 if (getenv("LIBCLANG_OBJTRACKING"))
210 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
213 ASTUnit::~ASTUnit() {
214 // If we loaded from an AST file, balance out the BeginSourceFile call.
215 if (MainFileIsAST && getDiagnostics().getClient()) {
216 getDiagnostics().getClient()->EndSourceFile();
219 clearFileLevelDecls();
221 // Clean up the temporary files and the preamble file.
222 removeOnDiskEntry(this);
224 // Free the buffers associated with remapped files. We are required to
225 // perform this operation here because we explicitly request that the
226 // compiler instance *not* free these buffers for each invocation of the
228 if (Invocation && OwnsRemappedFileBuffers) {
229 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
230 for (const auto &RB : PPOpts.RemappedFileBuffers)
234 ClearCachedCompletionResults();
236 if (getenv("LIBCLANG_OBJTRACKING"))
237 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
240 void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
241 this->PP = std::move(PP);
244 /// \brief Determine the set of code-completion contexts in which this
245 /// declaration should be shown.
246 static unsigned getDeclShowContexts(const NamedDecl *ND,
247 const LangOptions &LangOpts,
248 bool &IsNestedNameSpecifier) {
249 IsNestedNameSpecifier = false;
251 if (isa<UsingShadowDecl>(ND))
252 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
256 uint64_t Contexts = 0;
257 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
258 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
259 // Types can appear in these contexts.
260 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
261 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
262 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
263 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
264 | (1LL << CodeCompletionContext::CCC_Statement)
265 | (1LL << CodeCompletionContext::CCC_Type)
266 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
268 // In C++, types can appear in expressions contexts (for functional casts).
269 if (LangOpts.CPlusPlus)
270 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
272 // In Objective-C, message sends can send interfaces. In Objective-C++,
273 // all types are available due to functional casts.
274 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
275 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
277 // In Objective-C, you can only be a subclass of another Objective-C class
278 if (isa<ObjCInterfaceDecl>(ND))
279 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
281 // Deal with tag names.
282 if (isa<EnumDecl>(ND)) {
283 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
285 // Part of the nested-name-specifier in C++0x.
286 if (LangOpts.CPlusPlus11)
287 IsNestedNameSpecifier = true;
288 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
289 if (Record->isUnion())
290 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
292 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
294 if (LangOpts.CPlusPlus)
295 IsNestedNameSpecifier = true;
296 } else if (isa<ClassTemplateDecl>(ND))
297 IsNestedNameSpecifier = true;
298 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
299 // Values can appear in these contexts.
300 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
301 | (1LL << CodeCompletionContext::CCC_Expression)
302 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
303 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
304 } else if (isa<ObjCProtocolDecl>(ND)) {
305 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
306 } else if (isa<ObjCCategoryDecl>(ND)) {
307 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
308 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
309 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
311 // Part of the nested-name-specifier.
312 IsNestedNameSpecifier = true;
318 void ASTUnit::CacheCodeCompletionResults() {
322 SimpleTimer Timer(WantTiming);
323 Timer.setOutput("Cache global code completions for " + getMainFileName());
325 // Clear out the previous results.
326 ClearCachedCompletionResults();
328 // Gather the set of global code completions.
329 typedef CodeCompletionResult Result;
330 SmallVector<Result, 8> Results;
331 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
332 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
333 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
336 // Translate global code completions into cached completions.
337 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
338 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
340 for (Result &R : Results) {
342 case Result::RK_Declaration: {
343 bool IsNestedNameSpecifier = false;
344 CachedCodeCompletionResult CachedResult;
345 CachedResult.Completion = R.CreateCodeCompletionString(
346 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
347 IncludeBriefCommentsInCodeCompletion);
348 CachedResult.ShowInContexts = getDeclShowContexts(
349 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
350 CachedResult.Priority = R.Priority;
351 CachedResult.Kind = R.CursorKind;
352 CachedResult.Availability = R.Availability;
354 // Keep track of the type of this completion in an ASTContext-agnostic
356 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
357 if (UsageType.isNull()) {
358 CachedResult.TypeClass = STC_Void;
359 CachedResult.Type = 0;
361 CanQualType CanUsageType
362 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
363 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
365 // Determine whether we have already seen this type. If so, we save
366 // ourselves the work of formatting the type string by using the
367 // temporary, CanQualType-based hash table to find the associated value.
368 unsigned &TypeValue = CompletionTypes[CanUsageType];
369 if (TypeValue == 0) {
370 TypeValue = CompletionTypes.size();
371 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
375 CachedResult.Type = TypeValue;
378 CachedCompletionResults.push_back(CachedResult);
380 /// Handle nested-name-specifiers in C++.
381 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
382 !R.StartsNestedNameSpecifier) {
383 // The contexts in which a nested-name-specifier can appear in C++.
385 = (1LL << CodeCompletionContext::CCC_TopLevel)
386 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
387 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
388 | (1LL << CodeCompletionContext::CCC_Statement)
389 | (1LL << CodeCompletionContext::CCC_Expression)
390 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
391 | (1LL << CodeCompletionContext::CCC_EnumTag)
392 | (1LL << CodeCompletionContext::CCC_UnionTag)
393 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
394 | (1LL << CodeCompletionContext::CCC_Type)
395 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
396 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
398 if (isa<NamespaceDecl>(R.Declaration) ||
399 isa<NamespaceAliasDecl>(R.Declaration))
400 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
402 if (unsigned RemainingContexts
403 = NNSContexts & ~CachedResult.ShowInContexts) {
404 // If there any contexts where this completion can be a
405 // nested-name-specifier but isn't already an option, create a
406 // nested-name-specifier completion.
407 R.StartsNestedNameSpecifier = true;
408 CachedResult.Completion = R.CreateCodeCompletionString(
409 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
410 IncludeBriefCommentsInCodeCompletion);
411 CachedResult.ShowInContexts = RemainingContexts;
412 CachedResult.Priority = CCP_NestedNameSpecifier;
413 CachedResult.TypeClass = STC_Void;
414 CachedResult.Type = 0;
415 CachedCompletionResults.push_back(CachedResult);
421 case Result::RK_Keyword:
422 case Result::RK_Pattern:
423 // Ignore keywords and patterns; we don't care, since they are so
424 // easily regenerated.
427 case Result::RK_Macro: {
428 CachedCodeCompletionResult CachedResult;
429 CachedResult.Completion = R.CreateCodeCompletionString(
430 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
431 IncludeBriefCommentsInCodeCompletion);
432 CachedResult.ShowInContexts
433 = (1LL << CodeCompletionContext::CCC_TopLevel)
434 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
435 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
436 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
437 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
438 | (1LL << CodeCompletionContext::CCC_Statement)
439 | (1LL << CodeCompletionContext::CCC_Expression)
440 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
441 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
442 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
443 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
444 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
446 CachedResult.Priority = R.Priority;
447 CachedResult.Kind = R.CursorKind;
448 CachedResult.Availability = R.Availability;
449 CachedResult.TypeClass = STC_Void;
450 CachedResult.Type = 0;
451 CachedCompletionResults.push_back(CachedResult);
457 // Save the current top-level hash value.
458 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
461 void ASTUnit::ClearCachedCompletionResults() {
462 CachedCompletionResults.clear();
463 CachedCompletionTypes.clear();
464 CachedCompletionAllocator = nullptr;
469 /// \brief Gathers information from ASTReader that will be used to initialize
471 class ASTInfoCollector : public ASTReaderListener {
474 LangOptions &LangOpt;
475 std::shared_ptr<TargetOptions> &TargetOpts;
476 IntrusiveRefCntPtr<TargetInfo> &Target;
479 bool InitializedLanguage;
481 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
482 std::shared_ptr<TargetOptions> &TargetOpts,
483 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
484 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
485 Target(Target), Counter(Counter), InitializedLanguage(false) {}
487 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
488 bool AllowCompatibleDifferences) override {
489 if (InitializedLanguage)
493 InitializedLanguage = true;
499 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
500 bool AllowCompatibleDifferences) override {
501 // If we've already initialized the target, don't do it again.
505 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
507 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
513 void ReadCounter(const serialization::ModuleFile &M,
514 unsigned Value) override {
520 if (!Target || !InitializedLanguage)
523 // Inform the target of the language options.
525 // FIXME: We shouldn't need to do this, the target should be immutable once
526 // created. This complexity should be lifted elsewhere.
527 Target->adjust(LangOpt);
529 // Initialize the preprocessor.
530 PP.Initialize(*Target);
532 // Initialize the ASTContext
533 Context.InitBuiltinTypes(*Target);
535 // We didn't have access to the comment options when the ASTContext was
536 // constructed, so register them now.
537 Context.getCommentCommandTraits().registerCommentOptions(
538 LangOpt.CommentOpts);
542 /// \brief Diagnostic consumer that saves each diagnostic it is given.
543 class StoredDiagnosticConsumer : public DiagnosticConsumer {
544 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
545 SourceManager *SourceMgr;
548 explicit StoredDiagnosticConsumer(
549 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
550 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
552 void BeginSourceFile(const LangOptions &LangOpts,
553 const Preprocessor *PP = nullptr) override {
555 SourceMgr = &PP->getSourceManager();
558 void HandleDiagnostic(DiagnosticsEngine::Level Level,
559 const Diagnostic &Info) override;
562 /// \brief RAII object that optionally captures diagnostics, if
563 /// there is no diagnostic client to capture them already.
564 class CaptureDroppedDiagnostics {
565 DiagnosticsEngine &Diags;
566 StoredDiagnosticConsumer Client;
567 DiagnosticConsumer *PreviousClient;
568 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
571 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
572 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
573 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
575 if (RequestCapture || Diags.getClient() == nullptr) {
576 OwningPreviousClient = Diags.takeClient();
577 PreviousClient = Diags.getClient();
578 Diags.setClient(&Client, false);
582 ~CaptureDroppedDiagnostics() {
583 if (Diags.getClient() == &Client)
584 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
588 } // anonymous namespace
590 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
591 const Diagnostic &Info) {
592 // Default implementation (Warnings/errors count).
593 DiagnosticConsumer::HandleDiagnostic(Level, Info);
595 // Only record the diagnostic if it's part of the source manager we know
596 // about. This effectively drops diagnostics from modules we're building.
597 // FIXME: In the long run, ee don't want to drop source managers from modules.
598 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
599 StoredDiags.emplace_back(Level, Info);
602 IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
606 ASTMutationListener *ASTUnit::getASTMutationListener() {
608 return &WriterData->Writer;
612 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
614 return &WriterData->Writer;
618 std::unique_ptr<llvm::MemoryBuffer>
619 ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
621 auto Buffer = FileMgr->getBufferForFile(Filename);
623 return std::move(*Buffer);
625 *ErrorStr = Buffer.getError().message();
629 /// \brief Configure the diagnostics object for use with ASTUnit.
630 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
631 ASTUnit &AST, bool CaptureDiagnostics) {
632 assert(Diags.get() && "no DiagnosticsEngine was provided");
633 if (CaptureDiagnostics)
634 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
637 std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
638 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
639 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
640 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
641 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
642 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
643 bool UserFilesAreVolatile) {
644 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
646 // Recover resources if we crash before exiting this method.
647 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
648 ASTUnitCleanup(AST.get());
649 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
650 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
651 DiagCleanup(Diags.get());
653 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
655 AST->OnlyLocalDecls = OnlyLocalDecls;
656 AST->CaptureDiagnostics = CaptureDiagnostics;
657 AST->Diagnostics = Diags;
658 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
659 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
660 AST->UserFilesAreVolatile = UserFilesAreVolatile;
661 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
662 AST->getFileManager(),
663 UserFilesAreVolatile);
664 AST->PCMCache = new MemoryBufferCache;
665 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
666 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
667 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
668 AST->getSourceManager(),
669 AST->getDiagnostics(),
670 AST->ASTFileLangOpts,
671 /*Target=*/nullptr));
673 auto PPOpts = std::make_shared<PreprocessorOptions>();
675 for (const auto &RemappedFile : RemappedFiles)
676 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
678 // Gather Info for preprocessor construction later on.
680 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
683 AST->PP = std::make_shared<Preprocessor>(
684 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
685 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
686 /*IILookup=*/nullptr,
687 /*OwnsHeaderSearch=*/false);
688 Preprocessor &PP = *AST->PP;
690 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
691 PP.getIdentifierTable(), PP.getSelectorTable(),
692 PP.getBuiltinInfo());
693 ASTContext &Context = *AST->Ctx;
695 bool disableValid = false;
696 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
698 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
700 /*DisableValidation=*/disableValid,
701 AllowPCHWithCompilerErrors);
703 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
704 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
707 // Attach the AST reader to the AST context as an external AST
708 // source, so that declarations will be deserialized from the
709 // AST file as needed.
710 // We need the external source to be set up before we read the AST, because
711 // eagerly-deserialized declarations may use it.
712 Context.setExternalSource(AST->Reader);
714 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
715 SourceLocation(), ASTReader::ARR_None)) {
716 case ASTReader::Success:
719 case ASTReader::Failure:
720 case ASTReader::Missing:
721 case ASTReader::OutOfDate:
722 case ASTReader::VersionMismatch:
723 case ASTReader::ConfigurationMismatch:
724 case ASTReader::HadErrors:
725 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
729 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
731 PP.setCounterValue(Counter);
733 // Create an AST consumer, even though it isn't used.
734 AST->Consumer.reset(new ASTConsumer);
736 // Create a semantic analysis object and tell the AST reader about it.
737 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
738 AST->TheSema->Initialize();
739 AST->Reader->InitializeSema(*AST->TheSema);
741 // Tell the diagnostic client that we have started a source file.
742 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
749 /// \brief Preprocessor callback class that updates a hash value with the names
750 /// of all macros that have been defined by the translation unit.
751 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
755 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
757 void MacroDefined(const Token &MacroNameTok,
758 const MacroDirective *MD) override {
759 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
763 /// \brief Add the given declaration to the hash of all top-level entities.
764 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
768 DeclContext *DC = D->getDeclContext();
772 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
775 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
776 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
777 // For an unscoped enum include the enumerators in the hash since they
778 // enter the top-level namespace.
779 if (!EnumD->isScoped()) {
780 for (const auto *EI : EnumD->enumerators()) {
781 if (EI->getIdentifier())
782 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
787 if (ND->getIdentifier())
788 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
789 else if (DeclarationName Name = ND->getDeclName()) {
790 std::string NameStr = Name.getAsString();
791 Hash = llvm::HashString(NameStr, Hash);
796 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
797 if (Module *Mod = ImportD->getImportedModule()) {
798 std::string ModName = Mod->getFullModuleName();
799 Hash = llvm::HashString(ModName, Hash);
805 class TopLevelDeclTrackerConsumer : public ASTConsumer {
810 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
811 : Unit(_Unit), Hash(Hash) {
815 void handleTopLevelDecl(Decl *D) {
819 // FIXME: Currently ObjC method declarations are incorrectly being
820 // reported as top-level declarations, even though their DeclContext
821 // is the containing ObjC @interface/@implementation. This is a
822 // fundamental problem in the parser right now.
823 if (isa<ObjCMethodDecl>(D))
826 AddTopLevelDeclarationToHash(D, Hash);
827 Unit.addTopLevelDecl(D);
829 handleFileLevelDecl(D);
832 void handleFileLevelDecl(Decl *D) {
833 Unit.addFileLevelDecl(D);
834 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
835 for (auto *I : NSD->decls())
836 handleFileLevelDecl(I);
840 bool HandleTopLevelDecl(DeclGroupRef D) override {
841 for (Decl *TopLevelDecl : D)
842 handleTopLevelDecl(TopLevelDecl);
846 // We're not interested in "interesting" decls.
847 void HandleInterestingDecl(DeclGroupRef) override {}
849 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
850 for (Decl *TopLevelDecl : D)
851 handleTopLevelDecl(TopLevelDecl);
854 ASTMutationListener *GetASTMutationListener() override {
855 return Unit.getASTMutationListener();
858 ASTDeserializationListener *GetASTDeserializationListener() override {
859 return Unit.getDeserializationListener();
863 class TopLevelDeclTrackerAction : public ASTFrontendAction {
867 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
868 StringRef InFile) override {
869 CI.getPreprocessor().addPPCallbacks(
870 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
871 Unit.getCurrentTopLevelHashValue()));
872 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
873 Unit, Unit.getCurrentTopLevelHashValue());
877 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
879 bool hasCodeCompletionSupport() const override { return false; }
880 TranslationUnitKind getTranslationUnitKind() override {
881 return Unit.getTranslationUnitKind();
885 class PrecompilePreambleAction : public ASTFrontendAction {
887 bool HasEmittedPreamblePCH;
890 explicit PrecompilePreambleAction(ASTUnit &Unit)
891 : Unit(Unit), HasEmittedPreamblePCH(false) {}
893 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
894 StringRef InFile) override;
895 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
896 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
897 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
899 bool hasCodeCompletionSupport() const override { return false; }
900 bool hasASTFileSupport() const override { return false; }
901 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
904 class PrecompilePreambleConsumer : public PCHGenerator {
907 std::vector<Decl *> TopLevelDecls;
908 PrecompilePreambleAction *Action;
909 std::unique_ptr<raw_ostream> Out;
912 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
913 const Preprocessor &PP, StringRef isysroot,
914 std::unique_ptr<raw_ostream> Out)
915 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
916 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
917 /*AllowASTWithErrors=*/true),
918 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
919 Out(std::move(Out)) {
923 bool HandleTopLevelDecl(DeclGroupRef DG) override {
925 // FIXME: Currently ObjC method declarations are incorrectly being
926 // reported as top-level declarations, even though their DeclContext
927 // is the containing ObjC @interface/@implementation. This is a
928 // fundamental problem in the parser right now.
929 if (isa<ObjCMethodDecl>(D))
931 AddTopLevelDeclarationToHash(D, Hash);
932 TopLevelDecls.push_back(D);
937 void HandleTranslationUnit(ASTContext &Ctx) override {
938 PCHGenerator::HandleTranslationUnit(Ctx);
939 if (hasEmittedPCH()) {
940 // Write the generated bitstream to "Out".
942 // Make sure it hits disk now.
945 llvm::SmallVector<char, 0> Empty;
946 getPCH() = std::move(Empty);
948 // Translate the top-level declarations we captured during
949 // parsing into declaration IDs in the precompiled
950 // preamble. This will allow us to deserialize those top-level
951 // declarations when requested.
952 for (Decl *D : TopLevelDecls) {
953 // Invalid top-level decls may not have been serialized.
954 if (D->isInvalidDecl())
956 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
959 Action->setHasEmittedPreamblePCH();
964 } // anonymous namespace
966 std::unique_ptr<ASTConsumer>
967 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
970 std::string OutputFile;
971 std::unique_ptr<raw_ostream> OS =
972 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
977 if (!CI.getFrontendOpts().RelocatablePCH)
980 CI.getPreprocessor().addPPCallbacks(
981 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
982 Unit.getCurrentTopLevelHashValue()));
983 return llvm::make_unique<PrecompilePreambleConsumer>(
984 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
987 static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
988 return StoredDiag.getLocation().isValid();
992 checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
993 // Get rid of stored diagnostics except the ones from the driver which do not
994 // have a source location.
996 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1000 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1002 SourceManager &SM) {
1003 // The stored diagnostic has the old source manager in it; update
1004 // the locations to refer into the new source manager. Since we've
1005 // been careful to make sure that the source manager's state
1006 // before and after are identical, so that we can reuse the source
1008 for (StoredDiagnostic &SD : StoredDiagnostics) {
1009 if (SD.getLocation().isValid()) {
1010 FullSourceLoc Loc(SD.getLocation(), SM);
1011 SD.setLocation(Loc);
1016 /// Parse the source file into a translation unit using the given compiler
1017 /// invocation, replacing the current translation unit.
1019 /// \returns True if a failure occurred that causes the ASTUnit not to
1020 /// contain any translation-unit information, false otherwise.
1021 bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1022 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1023 SavedMainFileBuffer.reset();
1028 // Create the compiler instance to use for building the AST.
1029 std::unique_ptr<CompilerInstance> Clang(
1030 new CompilerInstance(std::move(PCHContainerOps)));
1032 // Recover resources if we crash before exiting this method.
1033 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1034 CICleanup(Clang.get());
1036 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
1037 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1039 // Set up diagnostics, capturing any diagnostics that would
1040 // otherwise be dropped.
1041 Clang->setDiagnostics(&getDiagnostics());
1043 // Create the target instance.
1044 Clang->setTarget(TargetInfo::CreateTargetInfo(
1045 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1046 if (!Clang->hasTarget())
1049 // Inform the target of the language options.
1051 // FIXME: We shouldn't need to do this, the target should be immutable once
1052 // created. This complexity should be lifted elsewhere.
1053 Clang->getTarget().adjust(Clang->getLangOpts());
1055 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1056 "Invocation must have exactly one source file!");
1057 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1058 InputKind::Source &&
1059 "FIXME: AST inputs not yet supported here!");
1060 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1061 InputKind::LLVM_IR &&
1062 "IR inputs not support here!");
1064 // Configure the various subsystems.
1065 LangOpts = Clang->getInvocation().LangOpts;
1066 FileSystemOpts = Clang->getFileSystemOpts();
1068 Clang->createFileManager();
1069 FileMgr = &Clang->getFileManager();
1071 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1072 UserFilesAreVolatile);
1078 // Clear out old caches and data.
1079 TopLevelDecls.clear();
1080 clearFileLevelDecls();
1082 if (!OverrideMainBuffer) {
1083 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1084 TopLevelDeclsInPreamble.clear();
1087 // Create a file manager object to provide access to and cache the filesystem.
1088 Clang->setFileManager(&getFileManager());
1090 // Create the source manager.
1091 Clang->setSourceManager(&getSourceManager());
1093 // If the main file has been overridden due to the use of a preamble,
1094 // make that override happen and introduce the preamble.
1095 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1096 if (OverrideMainBuffer) {
1097 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1098 OverrideMainBuffer.get());
1099 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1100 PreprocessorOpts.PrecompiledPreambleBytes.second
1101 = PreambleEndsAtStartOfLine;
1102 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1103 PreprocessorOpts.DisablePCHValidation = true;
1105 // The stored diagnostic has the old source manager in it; update
1106 // the locations to refer into the new source manager. Since we've
1107 // been careful to make sure that the source manager's state
1108 // before and after are identical, so that we can reuse the source
1110 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1112 // Keep track of the override buffer;
1113 SavedMainFileBuffer = std::move(OverrideMainBuffer);
1116 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1117 new TopLevelDeclTrackerAction(*this));
1119 // Recover resources if we crash before exiting this method.
1120 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1121 ActCleanup(Act.get());
1123 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1126 if (SavedMainFileBuffer)
1127 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1128 PreambleDiagnostics, StoredDiagnostics);
1130 if (!Act->Execute())
1133 transferASTDataFromCompilerInstance(*Clang);
1135 Act->EndSourceFile();
1137 FailedParseDiagnostics.clear();
1142 // Remove the overridden buffer we used for the preamble.
1143 SavedMainFileBuffer = nullptr;
1145 // Keep the ownership of the data in the ASTUnit because the client may
1146 // want to see the diagnostics.
1147 transferASTDataFromCompilerInstance(*Clang);
1148 FailedParseDiagnostics.swap(StoredDiagnostics);
1149 StoredDiagnostics.clear();
1150 NumStoredDiagnosticsFromDriver = 0;
1154 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1155 static std::string GetPreamblePCHPath() {
1156 // FIXME: This is a hack so that we can override the preamble file during
1157 // crash-recovery testing, which is the only case where the preamble files
1158 // are not necessarily cleaned up.
1159 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1163 SmallString<128> Path;
1164 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
1169 /// \brief Compute the preamble for the main file, providing the source buffer
1170 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1171 /// that describes the preamble.
1172 ASTUnit::ComputedPreamble
1173 ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
1174 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1175 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1177 // Try to determine if the main file has been remapped, either from the
1178 // command line (to another file) or directly through the compiler invocation
1179 // (to a memory buffer).
1180 llvm::MemoryBuffer *Buffer = nullptr;
1181 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
1182 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1183 llvm::sys::fs::UniqueID MainFileID;
1184 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
1185 // Check whether there is a file-file remapping of the main file
1186 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1187 std::string MPath(RF.first);
1188 llvm::sys::fs::UniqueID MID;
1189 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1190 if (MainFileID == MID) {
1191 // We found a remapping. Try to load the resulting, remapped source.
1192 BufferOwner = getBufferForFile(RF.second);
1194 return ComputedPreamble(nullptr, nullptr, 0, true);
1199 // Check whether there is a file-buffer remapping. It supercedes the
1200 // file-file remapping.
1201 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1202 std::string MPath(RB.first);
1203 llvm::sys::fs::UniqueID MID;
1204 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
1205 if (MainFileID == MID) {
1206 // We found a remapping.
1207 BufferOwner.reset();
1208 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
1214 // If the main source file was not remapped, load it now.
1215 if (!Buffer && !BufferOwner) {
1216 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1218 return ComputedPreamble(nullptr, nullptr, 0, true);
1222 Buffer = BufferOwner.get();
1223 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1224 *Invocation.getLangOpts(), MaxLines);
1225 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1229 ASTUnit::PreambleFileHash
1230 ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1231 PreambleFileHash Result;
1233 Result.ModTime = ModTime;
1238 ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1239 const llvm::MemoryBuffer *Buffer) {
1240 PreambleFileHash Result;
1241 Result.Size = Buffer->getBufferSize();
1245 MD5Ctx.update(Buffer->getBuffer().data());
1246 MD5Ctx.final(Result.MD5);
1252 bool operator==(const ASTUnit::PreambleFileHash &LHS,
1253 const ASTUnit::PreambleFileHash &RHS) {
1254 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1257 } // namespace clang
1259 static std::pair<unsigned, unsigned>
1260 makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1261 const LangOptions &LangOpts) {
1262 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1263 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1264 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1265 return std::make_pair(Offset, EndOffset);
1268 static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1269 const LangOptions &LangOpts,
1270 const FixItHint &InFix) {
1271 ASTUnit::StandaloneFixIt OutFix;
1272 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1273 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1275 OutFix.CodeToInsert = InFix.CodeToInsert;
1276 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1280 static ASTUnit::StandaloneDiagnostic
1281 makeStandaloneDiagnostic(const LangOptions &LangOpts,
1282 const StoredDiagnostic &InDiag) {
1283 ASTUnit::StandaloneDiagnostic OutDiag;
1284 OutDiag.ID = InDiag.getID();
1285 OutDiag.Level = InDiag.getLevel();
1286 OutDiag.Message = InDiag.getMessage();
1287 OutDiag.LocOffset = 0;
1288 if (InDiag.getLocation().isInvalid())
1290 const SourceManager &SM = InDiag.getLocation().getManager();
1291 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1292 OutDiag.Filename = SM.getFilename(FileLoc);
1293 if (OutDiag.Filename.empty())
1295 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1296 for (const CharSourceRange &Range : InDiag.getRanges())
1297 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1298 for (const FixItHint &FixIt : InDiag.getFixIts())
1299 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1304 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1305 /// the source file.
1307 /// This routine will compute the preamble of the main source file. If a
1308 /// non-trivial preamble is found, it will precompile that preamble into a
1309 /// precompiled header so that the precompiled preamble can be used to reduce
1310 /// reparsing time. If a precompiled preamble has already been constructed,
1311 /// this routine will determine if it is still valid and, if so, avoid
1312 /// rebuilding the precompiled preamble.
1314 /// \param AllowRebuild When true (the default), this routine is
1315 /// allowed to rebuild the precompiled preamble if it is found to be
1318 /// \param MaxLines When non-zero, the maximum number of lines that
1319 /// can occur within the preamble.
1321 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1322 /// buffer that should be used in place of the main file when doing so.
1323 /// Otherwise, returns a NULL pointer.
1324 std::unique_ptr<llvm::MemoryBuffer>
1325 ASTUnit::getMainBufferWithPrecompiledPreamble(
1326 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1327 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1328 unsigned MaxLines) {
1330 auto PreambleInvocation =
1331 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
1332 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1333 PreprocessorOptions &PreprocessorOpts
1334 = PreambleInvocation->getPreprocessorOpts();
1336 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
1338 if (!NewPreamble.Size) {
1339 // We couldn't find a preamble in the main source. Clear out the current
1340 // preamble, if we have one. It's obviously no good any more.
1342 erasePreambleFile(this);
1344 // The next time we actually see a preamble, precompile it.
1345 PreambleRebuildCounter = 1;
1349 if (!Preamble.empty()) {
1350 // We've previously computed a preamble. Check whether we have the same
1351 // preamble now that we did before, and that there's enough space in
1352 // the main-file buffer within the precompiled preamble to fit the
1354 if (Preamble.size() == NewPreamble.Size &&
1355 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1356 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1357 NewPreamble.Size) == 0) {
1358 // The preamble has not changed. We may be able to re-use the precompiled
1361 // Check that none of the files used by the preamble have changed.
1362 bool AnyFileChanged = false;
1364 // First, make a record of those files that have been overridden via
1365 // remapping or unsaved_files.
1366 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
1367 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1372 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
1373 // If we can't stat the file we're remapping to, assume that something
1374 // horrible happened.
1375 AnyFileChanged = true;
1379 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
1381 llvm::sys::toTimeT(Status.getLastModificationTime()));
1384 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1389 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1390 AnyFileChanged = true;
1394 OverriddenFiles[Status.getUniqueID()] =
1395 PreambleFileHash::createForMemoryBuffer(RB.second);
1398 // Check whether anything has changed.
1399 for (llvm::StringMap<PreambleFileHash>::iterator
1400 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1401 !AnyFileChanged && F != FEnd;
1404 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1405 // If we can't stat the file, assume that something horrible happened.
1406 AnyFileChanged = true;
1410 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1411 = OverriddenFiles.find(Status.getUniqueID());
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.
1421 if (Status.getSize() != uint64_t(F->second.Size) ||
1422 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1424 AnyFileChanged = true;
1427 if (!AnyFileChanged) {
1428 // Okay! We can re-use the precompiled preamble.
1430 // Set the state of the diagnostic object to mimic its state
1431 // after parsing the preamble.
1432 getDiagnostics().Reset();
1433 ProcessWarningOptions(getDiagnostics(),
1434 PreambleInvocation->getDiagnosticOpts());
1435 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1437 return llvm::MemoryBuffer::getMemBufferCopy(
1438 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
1442 // If we aren't allowed to rebuild the precompiled preamble, just
1447 // We can't reuse the previously-computed preamble. Build a new one.
1449 PreambleDiagnostics.clear();
1450 erasePreambleFile(this);
1451 PreambleRebuildCounter = 1;
1452 } else if (!AllowRebuild) {
1453 // We aren't allowed to rebuild the precompiled preamble; just
1458 // If the preamble rebuild counter > 1, it's because we previously
1459 // failed to build a preamble and we're not yet ready to try
1460 // again. Decrement the counter and return a failure.
1461 if (PreambleRebuildCounter > 1) {
1462 --PreambleRebuildCounter;
1466 // Create a temporary file for the precompiled preamble. In rare
1467 // circumstances, this can fail.
1468 std::string PreamblePCHPath = GetPreamblePCHPath();
1469 if (PreamblePCHPath.empty()) {
1470 // Try again next time.
1471 PreambleRebuildCounter = 1;
1475 // We did not previously compute a preamble, or it can't be reused anyway.
1476 SimpleTimer PreambleTimer(WantTiming);
1477 PreambleTimer.setOutput("Precompiling preamble");
1479 // Save the preamble text for later; we'll need to compare against it for
1480 // subsequent reparses.
1481 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
1482 Preamble.assign(FileMgr->getFile(MainFilename),
1483 NewPreamble.Buffer->getBufferStart(),
1484 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1485 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
1487 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1488 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
1490 // Remap the main source file to the preamble buffer.
1491 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1492 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
1494 // Tell the compiler invocation to generate a temporary precompiled header.
1495 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1496 // FIXME: Generate the precompiled header into memory?
1497 FrontendOpts.OutputFile = PreamblePCHPath;
1498 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1499 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1501 // Create the compiler instance to use for building the precompiled preamble.
1502 std::unique_ptr<CompilerInstance> Clang(
1503 new CompilerInstance(std::move(PCHContainerOps)));
1505 // Recover resources if we crash before exiting this method.
1506 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1507 CICleanup(Clang.get());
1509 Clang->setInvocation(std::move(PreambleInvocation));
1510 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1512 // Set up diagnostics, capturing all of the diagnostics produced.
1513 Clang->setDiagnostics(&getDiagnostics());
1515 // Create the target instance.
1516 Clang->setTarget(TargetInfo::CreateTargetInfo(
1517 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1518 if (!Clang->hasTarget()) {
1519 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1521 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1522 PreprocessorOpts.RemappedFileBuffers.pop_back();
1526 // Inform the target of the language options.
1528 // FIXME: We shouldn't need to do this, the target should be immutable once
1529 // created. This complexity should be lifted elsewhere.
1530 Clang->getTarget().adjust(Clang->getLangOpts());
1532 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1533 "Invocation must have exactly one source file!");
1534 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1535 InputKind::Source &&
1536 "FIXME: AST inputs not yet supported here!");
1537 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1538 InputKind::LLVM_IR &&
1539 "IR inputs not support here!");
1541 // Clear out old caches and data.
1542 getDiagnostics().Reset();
1543 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1544 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1545 TopLevelDecls.clear();
1546 TopLevelDeclsInPreamble.clear();
1547 PreambleDiagnostics.clear();
1549 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1550 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1554 // Create a file manager object to provide access to and cache the filesystem.
1555 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
1557 // Create the source manager.
1558 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1559 Clang->getFileManager()));
1561 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1562 Clang->addDependencyCollector(PreambleDepCollector);
1564 std::unique_ptr<PrecompilePreambleAction> Act;
1565 Act.reset(new PrecompilePreambleAction(*this));
1566 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1567 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1569 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1570 PreprocessorOpts.RemappedFileBuffers.pop_back();
1576 // Transfer any diagnostics generated when parsing the preamble into the set
1577 // of preamble diagnostics.
1578 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1579 E = stored_diag_end();
1581 PreambleDiagnostics.push_back(
1582 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
1584 Act->EndSourceFile();
1586 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1588 if (!Act->hasEmittedPreamblePCH()) {
1589 // The preamble PCH failed (e.g. there was a module loading fatal error),
1590 // so no precompiled header was generated. Forget that we even tried.
1591 // FIXME: Should we leave a note for ourselves to try again?
1592 llvm::sys::fs::remove(FrontendOpts.OutputFile);
1594 TopLevelDeclsInPreamble.clear();
1595 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1596 PreprocessorOpts.RemappedFileBuffers.pop_back();
1600 // Keep track of the preamble we precompiled.
1601 setPreambleFile(this, FrontendOpts.OutputFile);
1602 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1604 // Keep track of all of the files that the source manager knows about,
1605 // so we can verify whether they have changed or not.
1606 FilesInPreamble.clear();
1607 SourceManager &SourceMgr = Clang->getSourceManager();
1608 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1609 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1610 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
1612 if (time_t ModTime = File->getModificationTime()) {
1613 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1614 File->getSize(), ModTime);
1616 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
1617 FilesInPreamble[File->getName()] =
1618 PreambleFileHash::createForMemoryBuffer(Buffer);
1622 PreambleRebuildCounter = 1;
1623 PreprocessorOpts.RemappedFileBuffers.pop_back();
1625 // If the hash of top-level entities differs from the hash of the top-level
1626 // entities the last time we rebuilt the preamble, clear out the completion
1628 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1629 CompletionCacheTopLevelHashValue = 0;
1630 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1633 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
1637 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1638 std::vector<Decl *> Resolved;
1639 Resolved.reserve(TopLevelDeclsInPreamble.size());
1640 ExternalASTSource &Source = *getASTContext().getExternalSource();
1641 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
1642 // Resolve the declaration ID to an actual declaration, possibly
1643 // deserializing the declaration in the process.
1644 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1645 Resolved.push_back(D);
1647 TopLevelDeclsInPreamble.clear();
1648 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1651 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1652 // Steal the created target, context, and preprocessor if they have been
1654 assert(CI.hasInvocation() && "missing invocation");
1655 LangOpts = CI.getInvocation().LangOpts;
1656 TheSema = CI.takeSema();
1657 Consumer = CI.takeASTConsumer();
1658 if (CI.hasASTContext())
1659 Ctx = &CI.getASTContext();
1660 if (CI.hasPreprocessor())
1661 PP = CI.getPreprocessorPtr();
1662 CI.setSourceManager(nullptr);
1663 CI.setFileManager(nullptr);
1665 Target = &CI.getTarget();
1666 Reader = CI.getModuleManager();
1667 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1670 StringRef ASTUnit::getMainFileName() const {
1671 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1672 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1674 return Input.getFile();
1676 return Input.getBuffer()->getBufferIdentifier();
1680 if (const FileEntry *
1681 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1682 return FE->getName();
1688 StringRef ASTUnit::getASTFileName() const {
1689 if (!isMainFileAST())
1692 serialization::ModuleFile &
1693 Mod = Reader->getModuleManager().getPrimaryModule();
1694 return Mod.FileName;
1697 std::unique_ptr<ASTUnit>
1698 ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1699 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1700 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1701 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1702 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1703 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1704 createVFSFromCompilerInvocation(*CI, *Diags);
1707 AST->Diagnostics = Diags;
1708 AST->FileSystemOpts = CI->getFileSystemOpts();
1709 AST->Invocation = std::move(CI);
1710 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1711 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1712 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1713 UserFilesAreVolatile);
1714 AST->PCMCache = new MemoryBufferCache;
1719 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1720 std::shared_ptr<CompilerInvocation> CI,
1721 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1722 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1723 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1724 bool OnlyLocalDecls, bool CaptureDiagnostics,
1725 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1726 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1727 std::unique_ptr<ASTUnit> *ErrAST) {
1728 assert(CI && "A CompilerInvocation is required");
1730 std::unique_ptr<ASTUnit> OwnAST;
1731 ASTUnit *AST = Unit;
1733 // Create the AST unit.
1734 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1740 if (!ResourceFilesPath.empty()) {
1741 // Override the resources path.
1742 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1744 AST->OnlyLocalDecls = OnlyLocalDecls;
1745 AST->CaptureDiagnostics = CaptureDiagnostics;
1746 if (PrecompilePreambleAfterNParses > 0)
1747 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1748 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1749 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1750 AST->IncludeBriefCommentsInCodeCompletion
1751 = IncludeBriefCommentsInCodeCompletion;
1753 // Recover resources if we crash before exiting this method.
1754 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1755 ASTUnitCleanup(OwnAST.get());
1756 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1757 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1758 DiagCleanup(Diags.get());
1760 // We'll manage file buffers ourselves.
1761 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1762 CI->getFrontendOpts().DisableFree = false;
1763 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1765 // Create the compiler instance to use for building the AST.
1766 std::unique_ptr<CompilerInstance> Clang(
1767 new CompilerInstance(std::move(PCHContainerOps)));
1769 // Recover resources if we crash before exiting this method.
1770 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1771 CICleanup(Clang.get());
1773 Clang->setInvocation(std::move(CI));
1774 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1776 // Set up diagnostics, capturing any diagnostics that would
1777 // otherwise be dropped.
1778 Clang->setDiagnostics(&AST->getDiagnostics());
1780 // Create the target instance.
1781 Clang->setTarget(TargetInfo::CreateTargetInfo(
1782 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
1783 if (!Clang->hasTarget())
1786 // Inform the target of the language options.
1788 // FIXME: We shouldn't need to do this, the target should be immutable once
1789 // created. This complexity should be lifted elsewhere.
1790 Clang->getTarget().adjust(Clang->getLangOpts());
1792 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1793 "Invocation must have exactly one source file!");
1794 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1795 InputKind::Source &&
1796 "FIXME: AST inputs not yet supported here!");
1797 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1798 InputKind::LLVM_IR &&
1799 "IR inputs not support here!");
1801 // Configure the various subsystems.
1802 AST->TheSema.reset();
1805 AST->Reader = nullptr;
1807 // Create a file manager object to provide access to and cache the filesystem.
1808 Clang->setFileManager(&AST->getFileManager());
1810 // Create the source manager.
1811 Clang->setSourceManager(&AST->getSourceManager());
1813 FrontendAction *Act = Action;
1815 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1817 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1818 Act = TrackerAct.get();
1821 // Recover resources if we crash before exiting this method.
1822 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1823 ActCleanup(TrackerAct.get());
1825 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1826 AST->transferASTDataFromCompilerInstance(*Clang);
1827 if (OwnAST && ErrAST)
1828 ErrAST->swap(OwnAST);
1833 if (Persistent && !TrackerAct) {
1834 Clang->getPreprocessor().addPPCallbacks(
1835 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1836 AST->getCurrentTopLevelHashValue()));
1837 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1838 if (Clang->hasASTConsumer())
1839 Consumers.push_back(Clang->takeASTConsumer());
1840 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1841 *AST, AST->getCurrentTopLevelHashValue()));
1842 Clang->setASTConsumer(
1843 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
1845 if (!Act->Execute()) {
1846 AST->transferASTDataFromCompilerInstance(*Clang);
1847 if (OwnAST && ErrAST)
1848 ErrAST->swap(OwnAST);
1853 // Steal the created target, context, and preprocessor.
1854 AST->transferASTDataFromCompilerInstance(*Clang);
1856 Act->EndSourceFile();
1859 return OwnAST.release();
1864 bool ASTUnit::LoadFromCompilerInvocation(
1865 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1866 unsigned PrecompilePreambleAfterNParses) {
1870 // We'll manage file buffers ourselves.
1871 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1872 Invocation->getFrontendOpts().DisableFree = false;
1873 getDiagnostics().Reset();
1874 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1876 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1877 if (PrecompilePreambleAfterNParses > 0) {
1878 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
1879 OverrideMainBuffer =
1880 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
1881 getDiagnostics().Reset();
1882 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1885 SimpleTimer ParsingTimer(WantTiming);
1886 ParsingTimer.setOutput("Parsing " + getMainFileName());
1888 // Recover resources if we crash before exiting this method.
1889 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1890 MemBufferCleanup(OverrideMainBuffer.get());
1892 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
1895 std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1896 std::shared_ptr<CompilerInvocation> CI,
1897 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1898 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1899 bool OnlyLocalDecls, bool CaptureDiagnostics,
1900 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1901 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1902 bool UserFilesAreVolatile) {
1903 // Create the AST unit.
1904 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1905 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1906 AST->Diagnostics = Diags;
1907 AST->OnlyLocalDecls = OnlyLocalDecls;
1908 AST->CaptureDiagnostics = CaptureDiagnostics;
1909 AST->TUKind = TUKind;
1910 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1911 AST->IncludeBriefCommentsInCodeCompletion
1912 = IncludeBriefCommentsInCodeCompletion;
1913 AST->Invocation = std::move(CI);
1914 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1915 AST->FileMgr = FileMgr;
1916 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1918 // Recover resources if we crash before exiting this method.
1919 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1920 ASTUnitCleanup(AST.get());
1921 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1922 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1923 DiagCleanup(Diags.get());
1925 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1926 PrecompilePreambleAfterNParses))
1931 ASTUnit *ASTUnit::LoadFromCommandLine(
1932 const char **ArgBegin, const char **ArgEnd,
1933 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1934 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1935 bool OnlyLocalDecls, bool CaptureDiagnostics,
1936 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1937 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1938 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1939 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1940 bool UserFilesAreVolatile, bool ForSerialization,
1941 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
1942 assert(Diags.get() && "no DiagnosticsEngine was provided");
1944 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1946 std::shared_ptr<CompilerInvocation> CI;
1950 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1953 CI = clang::createInvocationFromCommandLine(
1954 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
1959 // Override any files that need remapping
1960 for (const auto &RemappedFile : RemappedFiles) {
1961 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1962 RemappedFile.second);
1964 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1965 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1966 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1968 // Override the resources path.
1969 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1971 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1974 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1976 // Create the AST unit.
1977 std::unique_ptr<ASTUnit> AST;
1978 AST.reset(new ASTUnit(false));
1979 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1980 AST->Diagnostics = Diags;
1981 AST->FileSystemOpts = CI->getFileSystemOpts();
1982 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1983 createVFSFromCompilerInvocation(*CI, *Diags);
1986 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1987 AST->PCMCache = new MemoryBufferCache;
1988 AST->OnlyLocalDecls = OnlyLocalDecls;
1989 AST->CaptureDiagnostics = CaptureDiagnostics;
1990 AST->TUKind = TUKind;
1991 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1992 AST->IncludeBriefCommentsInCodeCompletion
1993 = IncludeBriefCommentsInCodeCompletion;
1994 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1995 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1996 AST->StoredDiagnostics.swap(StoredDiagnostics);
1997 AST->Invocation = CI;
1998 if (ForSerialization)
1999 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
2000 // Zero out now to ease cleanup during crash recovery.
2004 // Recover resources if we crash before exiting this method.
2005 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2006 ASTUnitCleanup(AST.get());
2008 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
2009 PrecompilePreambleAfterNParses)) {
2010 // Some error occurred, if caller wants to examine diagnostics, pass it the
2013 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2019 return AST.release();
2022 bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2023 ArrayRef<RemappedFile> RemappedFiles) {
2027 clearFileLevelDecls();
2029 SimpleTimer ParsingTimer(WantTiming);
2030 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2033 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2034 for (const auto &RB : PPOpts.RemappedFileBuffers)
2037 Invocation->getPreprocessorOpts().clearRemappedFiles();
2038 for (const auto &RemappedFile : RemappedFiles) {
2039 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2040 RemappedFile.second);
2043 // If we have a preamble file lying around, or if we might try to
2044 // build a precompiled preamble, do so now.
2045 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2046 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2047 OverrideMainBuffer =
2048 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2050 // Clear out the diagnostics state.
2052 getDiagnostics().Reset();
2053 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2054 if (OverrideMainBuffer)
2055 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2057 // Parse the sources
2059 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
2061 // If we're caching global code-completion results, and the top-level
2062 // declarations have changed, clear out the code-completion cache.
2063 if (!Result && ShouldCacheCodeCompletionResults &&
2064 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2065 CacheCodeCompletionResults();
2067 // We now need to clear out the completion info related to this translation
2068 // unit; it'll be recreated if necessary.
2074 //----------------------------------------------------------------------------//
2076 //----------------------------------------------------------------------------//
2079 /// \brief Code completion consumer that combines the cached code-completion
2080 /// results from an ASTUnit with the code-completion results provided to it,
2081 /// then passes the result on to
2082 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2083 uint64_t NormalContexts;
2085 CodeCompleteConsumer &Next;
2088 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2089 const CodeCompleteOptions &CodeCompleteOpts)
2090 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2091 AST(AST), Next(Next)
2093 // Compute the set of contexts in which we will look when we don't have
2094 // any information about the specific context.
2096 = (1LL << CodeCompletionContext::CCC_TopLevel)
2097 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2098 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2099 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2100 | (1LL << CodeCompletionContext::CCC_Statement)
2101 | (1LL << CodeCompletionContext::CCC_Expression)
2102 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2103 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2104 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2105 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2106 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2107 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2108 | (1LL << CodeCompletionContext::CCC_Recovery);
2110 if (AST.getASTContext().getLangOpts().CPlusPlus)
2111 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2112 | (1LL << CodeCompletionContext::CCC_UnionTag)
2113 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2116 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2117 CodeCompletionResult *Results,
2118 unsigned NumResults) override;
2120 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2121 OverloadCandidate *Candidates,
2122 unsigned NumCandidates) override {
2123 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2126 CodeCompletionAllocator &getAllocator() override {
2127 return Next.getAllocator();
2130 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
2131 return Next.getCodeCompletionTUInfo();
2134 } // anonymous namespace
2136 /// \brief Helper function that computes which global names are hidden by the
2137 /// local code-completion results.
2138 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2139 CodeCompletionResult *Results,
2140 unsigned NumResults,
2142 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2143 bool OnlyTagNames = false;
2144 switch (Context.getKind()) {
2145 case CodeCompletionContext::CCC_Recovery:
2146 case CodeCompletionContext::CCC_TopLevel:
2147 case CodeCompletionContext::CCC_ObjCInterface:
2148 case CodeCompletionContext::CCC_ObjCImplementation:
2149 case CodeCompletionContext::CCC_ObjCIvarList:
2150 case CodeCompletionContext::CCC_ClassStructUnion:
2151 case CodeCompletionContext::CCC_Statement:
2152 case CodeCompletionContext::CCC_Expression:
2153 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2154 case CodeCompletionContext::CCC_DotMemberAccess:
2155 case CodeCompletionContext::CCC_ArrowMemberAccess:
2156 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2157 case CodeCompletionContext::CCC_Namespace:
2158 case CodeCompletionContext::CCC_Type:
2159 case CodeCompletionContext::CCC_Name:
2160 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2161 case CodeCompletionContext::CCC_ParenthesizedExpression:
2162 case CodeCompletionContext::CCC_ObjCInterfaceName:
2165 case CodeCompletionContext::CCC_EnumTag:
2166 case CodeCompletionContext::CCC_UnionTag:
2167 case CodeCompletionContext::CCC_ClassOrStructTag:
2168 OnlyTagNames = true;
2171 case CodeCompletionContext::CCC_ObjCProtocolName:
2172 case CodeCompletionContext::CCC_MacroName:
2173 case CodeCompletionContext::CCC_MacroNameUse:
2174 case CodeCompletionContext::CCC_PreprocessorExpression:
2175 case CodeCompletionContext::CCC_PreprocessorDirective:
2176 case CodeCompletionContext::CCC_NaturalLanguage:
2177 case CodeCompletionContext::CCC_SelectorName:
2178 case CodeCompletionContext::CCC_TypeQualifiers:
2179 case CodeCompletionContext::CCC_Other:
2180 case CodeCompletionContext::CCC_OtherWithMacros:
2181 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2182 case CodeCompletionContext::CCC_ObjCClassMessage:
2183 case CodeCompletionContext::CCC_ObjCCategoryName:
2184 // We're looking for nothing, or we're looking for names that cannot
2189 typedef CodeCompletionResult Result;
2190 for (unsigned I = 0; I != NumResults; ++I) {
2191 if (Results[I].Kind != Result::RK_Declaration)
2195 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2197 bool Hiding = false;
2199 Hiding = (IDNS & Decl::IDNS_Tag);
2201 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2202 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2203 Decl::IDNS_NonMemberOperator);
2204 if (Ctx.getLangOpts().CPlusPlus)
2205 HiddenIDNS |= Decl::IDNS_Tag;
2206 Hiding = (IDNS & HiddenIDNS);
2212 DeclarationName Name = Results[I].Declaration->getDeclName();
2213 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2214 HiddenNames.insert(Identifier->getName());
2216 HiddenNames.insert(Name.getAsString());
2220 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2221 CodeCompletionContext Context,
2222 CodeCompletionResult *Results,
2223 unsigned NumResults) {
2224 // Merge the results we were given with the results we cached.
2225 bool AddedResult = false;
2226 uint64_t InContexts =
2227 Context.getKind() == CodeCompletionContext::CCC_Recovery
2228 ? NormalContexts : (1LL << Context.getKind());
2229 // Contains the set of names that are hidden by "local" completion results.
2230 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2231 typedef CodeCompletionResult Result;
2232 SmallVector<Result, 8> AllResults;
2233 for (ASTUnit::cached_completion_iterator
2234 C = AST.cached_completion_begin(),
2235 CEnd = AST.cached_completion_end();
2237 // If the context we are in matches any of the contexts we are
2238 // interested in, we'll add this result.
2239 if ((C->ShowInContexts & InContexts) == 0)
2242 // If we haven't added any results previously, do so now.
2244 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2246 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2250 // Determine whether this global completion result is hidden by a local
2251 // completion result. If so, skip it.
2252 if (C->Kind != CXCursor_MacroDefinition &&
2253 HiddenNames.count(C->Completion->getTypedText()))
2256 // Adjust priority based on similar type classes.
2257 unsigned Priority = C->Priority;
2258 CodeCompletionString *Completion = C->Completion;
2259 if (!Context.getPreferredType().isNull()) {
2260 if (C->Kind == CXCursor_MacroDefinition) {
2261 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2263 Context.getPreferredType()->isAnyPointerType());
2264 } else if (C->Type) {
2265 CanQualType Expected
2266 = S.Context.getCanonicalType(
2267 Context.getPreferredType().getUnqualifiedType());
2268 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2269 if (ExpectedSTC == C->TypeClass) {
2270 // We know this type is similar; check for an exact match.
2271 llvm::StringMap<unsigned> &CachedCompletionTypes
2272 = AST.getCachedCompletionTypes();
2273 llvm::StringMap<unsigned>::iterator Pos
2274 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2275 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2276 Priority /= CCF_ExactTypeMatch;
2278 Priority /= CCF_SimilarTypeMatch;
2283 // Adjust the completion string, if required.
2284 if (C->Kind == CXCursor_MacroDefinition &&
2285 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2286 // Create a new code-completion string that just contains the
2287 // macro name, without its arguments.
2288 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2289 CCP_CodePattern, C->Availability);
2290 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2291 Priority = CCP_CodePattern;
2292 Completion = Builder.TakeString();
2295 AllResults.push_back(Result(Completion, Priority, C->Kind,
2299 // If we did not add any cached completion results, just forward the
2300 // results we were given to the next consumer.
2302 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2306 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2310 void ASTUnit::CodeComplete(
2311 StringRef File, unsigned Line, unsigned Column,
2312 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2313 bool IncludeCodePatterns, bool IncludeBriefComments,
2314 CodeCompleteConsumer &Consumer,
2315 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2316 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2317 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2318 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2322 SimpleTimer CompletionTimer(WantTiming);
2323 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2324 Twine(Line) + ":" + Twine(Column));
2326 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2328 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2329 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2330 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2332 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2333 CachedCompletionResults.empty();
2334 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2335 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2336 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2338 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2340 FrontendOpts.CodeCompletionAt.FileName = File;
2341 FrontendOpts.CodeCompletionAt.Line = Line;
2342 FrontendOpts.CodeCompletionAt.Column = Column;
2344 // Set the language options appropriately.
2345 LangOpts = *CCInvocation->getLangOpts();
2347 // Spell-checking and warnings are wasteful during code-completion.
2348 LangOpts.SpellChecking = false;
2349 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2351 std::unique_ptr<CompilerInstance> Clang(
2352 new CompilerInstance(PCHContainerOps));
2354 // Recover resources if we crash before exiting this method.
2355 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2356 CICleanup(Clang.get());
2358 auto &Inv = *CCInvocation;
2359 Clang->setInvocation(std::move(CCInvocation));
2360 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2362 // Set up diagnostics, capturing any diagnostics produced.
2363 Clang->setDiagnostics(&Diag);
2364 CaptureDroppedDiagnostics Capture(true,
2365 Clang->getDiagnostics(),
2367 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2369 // Create the target instance.
2370 Clang->setTarget(TargetInfo::CreateTargetInfo(
2371 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
2372 if (!Clang->hasTarget()) {
2373 Clang->setInvocation(nullptr);
2377 // Inform the target of the language options.
2379 // FIXME: We shouldn't need to do this, the target should be immutable once
2380 // created. This complexity should be lifted elsewhere.
2381 Clang->getTarget().adjust(Clang->getLangOpts());
2383 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2384 "Invocation must have exactly one source file!");
2385 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2386 InputKind::Source &&
2387 "FIXME: AST inputs not yet supported here!");
2388 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2389 InputKind::LLVM_IR &&
2390 "IR inputs not support here!");
2392 // Use the source and file managers that we were given.
2393 Clang->setFileManager(&FileMgr);
2394 Clang->setSourceManager(&SourceMgr);
2397 PreprocessorOpts.clearRemappedFiles();
2398 PreprocessorOpts.RetainRemappedFileBuffers = true;
2399 for (const auto &RemappedFile : RemappedFiles) {
2400 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2401 OwnedBuffers.push_back(RemappedFile.second);
2404 // Use the code completion consumer we were given, but adding any cached
2405 // code-completion results.
2406 AugmentedCodeCompleteConsumer *AugmentedConsumer
2407 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2408 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2410 // If we have a precompiled preamble, try to use it. We only allow
2411 // the use of the precompiled preamble if we're if the completion
2412 // point is within the main file, after the end of the precompiled
2414 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2415 if (!getPreambleFile(this).empty()) {
2416 std::string CompleteFilePath(File);
2417 llvm::sys::fs::UniqueID CompleteFileID;
2419 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
2420 std::string MainPath(OriginalSourceFile);
2421 llvm::sys::fs::UniqueID MainID;
2422 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
2423 if (CompleteFileID == MainID && Line > 1)
2424 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2425 PCHContainerOps, Inv, false, Line - 1);
2430 // If the main file has been overridden due to the use of a preamble,
2431 // make that override happen and introduce the preamble.
2432 if (OverrideMainBuffer) {
2433 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2434 OverrideMainBuffer.get());
2435 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2436 PreprocessorOpts.PrecompiledPreambleBytes.second
2437 = PreambleEndsAtStartOfLine;
2438 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2439 PreprocessorOpts.DisablePCHValidation = true;
2441 OwnedBuffers.push_back(OverrideMainBuffer.release());
2443 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2444 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2447 // Disable the preprocessing record if modules are not enabled.
2448 if (!Clang->getLangOpts().Modules)
2449 PreprocessorOpts.DetailedRecord = false;
2451 std::unique_ptr<SyntaxOnlyAction> Act;
2452 Act.reset(new SyntaxOnlyAction);
2453 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2455 Act->EndSourceFile();
2459 bool ASTUnit::Save(StringRef File) {
2460 if (HadModuleLoaderFatalFailure)
2463 // Write to a temporary file and later rename it to the actual file, to avoid
2464 // possible race conditions.
2465 SmallString<128> TempPath;
2467 TempPath += "-%%%%%%%%";
2469 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
2472 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2473 // unconditionally create a stat cache when we parse the file?
2474 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2478 if (Out.has_error()) {
2483 if (llvm::sys::fs::rename(TempPath, File)) {
2484 llvm::sys::fs::remove(TempPath);
2491 static bool serializeUnit(ASTWriter &Writer,
2492 SmallVectorImpl<char> &Buffer,
2496 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2498 // Write the generated bitstream to "Out".
2499 if (!Buffer.empty())
2500 OS.write(Buffer.data(), Buffer.size());
2505 bool ASTUnit::serialize(raw_ostream &OS) {
2506 // For serialization we are lenient if the errors were only warn-as-error kind.
2507 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2510 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2511 getSema(), hasErrors, OS);
2513 SmallString<128> Buffer;
2514 llvm::BitstreamWriter Stream(Buffer);
2515 MemoryBufferCache PCMCache;
2516 ASTWriter Writer(Stream, Buffer, PCMCache, {});
2517 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2520 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2522 void ASTUnit::TranslateStoredDiagnostics(
2523 FileManager &FileMgr,
2524 SourceManager &SrcMgr,
2525 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2526 SmallVectorImpl<StoredDiagnostic> &Out) {
2527 // Map the standalone diagnostic into the new source manager. We also need to
2528 // remap all the locations to the new view. This includes the diag location,
2529 // any associated source ranges, and the source ranges of associated fix-its.
2530 // FIXME: There should be a cleaner way to do this.
2532 SmallVector<StoredDiagnostic, 4> Result;
2533 Result.reserve(Diags.size());
2534 const FileEntry *PreviousFE = nullptr;
2536 for (const StandaloneDiagnostic &SD : Diags) {
2537 // Rebuild the StoredDiagnostic.
2538 if (SD.Filename.empty())
2540 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2543 if (FE != PreviousFE) {
2544 FID = SrcMgr.translateFile(FE);
2547 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2548 if (FileLoc.isInvalid())
2550 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2551 FullSourceLoc Loc(L, SrcMgr);
2553 SmallVector<CharSourceRange, 4> Ranges;
2554 Ranges.reserve(SD.Ranges.size());
2555 for (const auto &Range : SD.Ranges) {
2556 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2557 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2558 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2561 SmallVector<FixItHint, 2> FixIts;
2562 FixIts.reserve(SD.FixIts.size());
2563 for (const StandaloneFixIt &FixIt : SD.FixIts) {
2564 FixIts.push_back(FixItHint());
2565 FixItHint &FH = FixIts.back();
2566 FH.CodeToInsert = FixIt.CodeToInsert;
2567 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2568 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2569 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2572 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2573 SD.Message, Loc, Ranges, FixIts));
2578 void ASTUnit::addFileLevelDecl(Decl *D) {
2581 // We only care about local declarations.
2582 if (D->isFromASTFile())
2585 SourceManager &SM = *SourceMgr;
2586 SourceLocation Loc = D->getLocation();
2587 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2590 // We only keep track of the file-level declarations of each file.
2591 if (!D->getLexicalDeclContext()->isFileContext())
2594 SourceLocation FileLoc = SM.getFileLoc(Loc);
2595 assert(SM.isLocalSourceLocation(FileLoc));
2598 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2599 if (FID.isInvalid())
2602 LocDeclsTy *&Decls = FileDecls[FID];
2604 Decls = new LocDeclsTy();
2606 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2608 if (Decls->empty() || Decls->back().first <= Offset) {
2609 Decls->push_back(LocDecl);
2613 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2614 LocDecl, llvm::less_first());
2616 Decls->insert(I, LocDecl);
2619 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2620 SmallVectorImpl<Decl *> &Decls) {
2621 if (File.isInvalid())
2624 if (SourceMgr->isLoadedFileID(File)) {
2625 assert(Ctx->getExternalSource() && "No external source!");
2626 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2630 FileDeclsTy::iterator I = FileDecls.find(File);
2631 if (I == FileDecls.end())
2634 LocDeclsTy &LocDecls = *I->second;
2635 if (LocDecls.empty())
2638 LocDeclsTy::iterator BeginIt =
2639 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2640 std::make_pair(Offset, (Decl *)nullptr),
2641 llvm::less_first());
2642 if (BeginIt != LocDecls.begin())
2645 // If we are pointing at a top-level decl inside an objc container, we need
2646 // to backtrack until we find it otherwise we will fail to report that the
2647 // region overlaps with an objc container.
2648 while (BeginIt != LocDecls.begin() &&
2649 BeginIt->second->isTopLevelDeclInObjCContainer())
2652 LocDeclsTy::iterator EndIt = std::upper_bound(
2653 LocDecls.begin(), LocDecls.end(),
2654 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
2655 if (EndIt != LocDecls.end())
2658 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2659 Decls.push_back(DIt->second);
2662 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2663 unsigned Line, unsigned Col) const {
2664 const SourceManager &SM = getSourceManager();
2665 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2666 return SM.getMacroArgExpandedLocation(Loc);
2669 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2670 unsigned Offset) const {
2671 const SourceManager &SM = getSourceManager();
2672 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2673 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2676 /// \brief If \arg Loc is a loaded location from the preamble, returns
2677 /// the corresponding local location of the main file, otherwise it returns
2679 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2682 PreambleID = SourceMgr->getPreambleFileID();
2684 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2688 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2689 SourceLocation FileLoc
2690 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2691 return FileLoc.getLocWithOffset(Offs);
2697 /// \brief If \arg Loc is a local location of the main file but inside the
2698 /// preamble chunk, returns the corresponding loaded location from the
2699 /// preamble, otherwise it returns \arg Loc.
2700 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2703 PreambleID = SourceMgr->getPreambleFileID();
2705 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2709 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2710 Offs < Preamble.size()) {
2711 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2712 return FileLoc.getLocWithOffset(Offs);
2718 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2721 FID = SourceMgr->getPreambleFileID();
2723 if (Loc.isInvalid() || FID.isInvalid())
2726 return SourceMgr->isInFileID(Loc, FID);
2729 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2732 FID = SourceMgr->getMainFileID();
2734 if (Loc.isInvalid() || FID.isInvalid())
2737 return SourceMgr->isInFileID(Loc, FID);
2740 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2743 FID = SourceMgr->getPreambleFileID();
2745 if (FID.isInvalid())
2746 return SourceLocation();
2748 return SourceMgr->getLocForEndOfFile(FID);
2751 SourceLocation ASTUnit::getStartOfMainFileID() {
2754 FID = SourceMgr->getMainFileID();
2756 if (FID.isInvalid())
2757 return SourceLocation();
2759 return SourceMgr->getLocForStartOfFile(FID);
2762 llvm::iterator_range<PreprocessingRecord::iterator>
2763 ASTUnit::getLocalPreprocessingEntities() const {
2764 if (isMainFileAST()) {
2765 serialization::ModuleFile &
2766 Mod = Reader->getModuleManager().getPrimaryModule();
2767 return Reader->getModulePreprocessedEntities(Mod);
2770 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2771 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2773 return llvm::make_range(PreprocessingRecord::iterator(),
2774 PreprocessingRecord::iterator());
2777 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2778 if (isMainFileAST()) {
2779 serialization::ModuleFile &
2780 Mod = Reader->getModuleManager().getPrimaryModule();
2781 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2782 if (!Fn(context, D))
2789 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2790 TLEnd = top_level_end();
2791 TL != TLEnd; ++TL) {
2792 if (!Fn(context, *TL))
2799 const FileEntry *ASTUnit::getPCHFile() {
2803 serialization::ModuleFile *Mod = nullptr;
2804 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2806 case serialization::MK_ImplicitModule:
2807 case serialization::MK_ExplicitModule:
2808 case serialization::MK_PrebuiltModule:
2809 return true; // skip dependencies.
2810 case serialization::MK_PCH:
2812 return true; // found it.
2813 case serialization::MK_Preamble:
2814 return false; // look in dependencies.
2815 case serialization::MK_MainFile:
2816 return false; // look in dependencies.
2827 bool ASTUnit::isModuleFile() {
2828 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
2831 void ASTUnit::PreambleData::countLines() const {
2836 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2838 if (Buffer.back() != '\n')
2843 ASTUnit::ConcurrencyState::ConcurrencyState() {
2844 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2847 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2848 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2851 void ASTUnit::ConcurrencyState::start() {
2852 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2853 assert(acquired && "Concurrent access to ASTUnit!");
2856 void ASTUnit::ConcurrencyState::finish() {
2857 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2862 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2863 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2864 void ASTUnit::ConcurrencyState::start() {}
2865 void ASTUnit::ConcurrencyState::finish() {}