1 //===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // ASTUnit Implementation.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Frontend/ASTUnit.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CommentCommandTraits.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclGroup.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/Type.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/Diagnostic.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/IdentifierTable.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/LangOptions.h"
33 #include "clang/Basic/LangStandard.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TargetOptions.h"
39 #include "clang/Frontend/CompilerInstance.h"
40 #include "clang/Frontend/CompilerInvocation.h"
41 #include "clang/Frontend/FrontendAction.h"
42 #include "clang/Frontend/FrontendActions.h"
43 #include "clang/Frontend/FrontendDiagnostic.h"
44 #include "clang/Frontend/FrontendOptions.h"
45 #include "clang/Frontend/MultiplexConsumer.h"
46 #include "clang/Frontend/PrecompiledPreamble.h"
47 #include "clang/Frontend/Utils.h"
48 #include "clang/Lex/HeaderSearch.h"
49 #include "clang/Lex/HeaderSearchOptions.h"
50 #include "clang/Lex/Lexer.h"
51 #include "clang/Lex/PPCallbacks.h"
52 #include "clang/Lex/PreprocessingRecord.h"
53 #include "clang/Lex/Preprocessor.h"
54 #include "clang/Lex/PreprocessorOptions.h"
55 #include "clang/Lex/Token.h"
56 #include "clang/Sema/CodeCompleteConsumer.h"
57 #include "clang/Sema/CodeCompleteOptions.h"
58 #include "clang/Sema/Sema.h"
59 #include "clang/Serialization/ASTBitCodes.h"
60 #include "clang/Serialization/ASTReader.h"
61 #include "clang/Serialization/ASTWriter.h"
62 #include "clang/Serialization/ContinuousRangeMap.h"
63 #include "clang/Serialization/InMemoryModuleCache.h"
64 #include "clang/Serialization/ModuleFile.h"
65 #include "clang/Serialization/PCHContainerOperations.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/IntrusiveRefCntPtr.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/ScopeExit.h"
73 #include "llvm/ADT/SmallString.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/StringMap.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSet.h"
78 #include "llvm/ADT/Twine.h"
79 #include "llvm/ADT/iterator_range.h"
80 #include "llvm/Bitstream/BitstreamWriter.h"
81 #include "llvm/Support/Allocator.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/CrashRecoveryContext.h"
84 #include "llvm/Support/DJB.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/ErrorOr.h"
87 #include "llvm/Support/FileSystem.h"
88 #include "llvm/Support/FileUtilities.h"
89 #include "llvm/Support/MemoryBuffer.h"
90 #include "llvm/Support/Timer.h"
91 #include "llvm/Support/VirtualFileSystem.h"
92 #include "llvm/Support/raw_ostream.h"
106 using namespace clang
;
108 using llvm::TimeRecord
;
118 explicit SimpleTimer(bool WantTiming
) : WantTiming(WantTiming
) {
120 Start
= TimeRecord::getCurrentTime();
125 TimeRecord Elapsed
= TimeRecord::getCurrentTime();
127 llvm::errs() << Output
<< ':';
128 Elapsed
.print(Elapsed
, llvm::errs());
129 llvm::errs() << '\n';
133 void setOutput(const Twine
&Output
) {
135 this->Output
= Output
.str();
142 static std::unique_ptr
<T
> valueOrNull(llvm::ErrorOr
<std::unique_ptr
<T
>> Val
) {
145 return std::move(*Val
);
149 static bool moveOnNoError(llvm::ErrorOr
<T
> Val
, T
&Output
) {
152 Output
= std::move(*Val
);
156 /// Get a source buffer for \p MainFilePath, handling all file-to-file
157 /// and file-to-buffer remappings inside \p Invocation.
158 static std::unique_ptr
<llvm::MemoryBuffer
>
159 getBufferForFileHandlingRemapping(const CompilerInvocation
&Invocation
,
160 llvm::vfs::FileSystem
*VFS
,
161 StringRef FilePath
, bool isVolatile
) {
162 const auto &PreprocessorOpts
= Invocation
.getPreprocessorOpts();
164 // Try to determine if the main file has been remapped, either from the
165 // command line (to another file) or directly through the compiler
166 // invocation (to a memory buffer).
167 llvm::MemoryBuffer
*Buffer
= nullptr;
168 std::unique_ptr
<llvm::MemoryBuffer
> BufferOwner
;
169 auto FileStatus
= VFS
->status(FilePath
);
171 llvm::sys::fs::UniqueID MainFileID
= FileStatus
->getUniqueID();
173 // Check whether there is a file-file remapping of the main file
174 for (const auto &RF
: PreprocessorOpts
.RemappedFiles
) {
175 std::string
MPath(RF
.first
);
176 auto MPathStatus
= VFS
->status(MPath
);
178 llvm::sys::fs::UniqueID MID
= MPathStatus
->getUniqueID();
179 if (MainFileID
== MID
) {
180 // We found a remapping. Try to load the resulting, remapped source.
181 BufferOwner
= valueOrNull(VFS
->getBufferForFile(RF
.second
, -1, true, isVolatile
));
188 // Check whether there is a file-buffer remapping. It supercedes the
189 // file-file remapping.
190 for (const auto &RB
: PreprocessorOpts
.RemappedFileBuffers
) {
191 std::string
MPath(RB
.first
);
192 auto MPathStatus
= VFS
->status(MPath
);
194 llvm::sys::fs::UniqueID MID
= MPathStatus
->getUniqueID();
195 if (MainFileID
== MID
) {
196 // We found a remapping.
198 Buffer
= const_cast<llvm::MemoryBuffer
*>(RB
.second
);
204 // If the main source file was not remapped, load it now.
205 if (!Buffer
&& !BufferOwner
) {
206 BufferOwner
= valueOrNull(VFS
->getBufferForFile(FilePath
, -1, true, isVolatile
));
215 return llvm::MemoryBuffer::getMemBufferCopy(Buffer
->getBuffer(), FilePath
);
218 struct ASTUnit::ASTWriterData
{
219 SmallString
<128> Buffer
;
220 llvm::BitstreamWriter Stream
;
223 ASTWriterData(InMemoryModuleCache
&ModuleCache
)
224 : Stream(Buffer
), Writer(Stream
, Buffer
, ModuleCache
, {}) {}
227 void ASTUnit::clearFileLevelDecls() {
231 /// After failing to build a precompiled preamble (due to
232 /// errors in the source that occurs in the preamble), the number of
233 /// reparses during which we'll skip even trying to precompile the
235 const unsigned DefaultPreambleRebuildInterval
= 5;
237 /// Tracks the number of ASTUnit objects that are currently active.
239 /// Used for debugging purposes only.
240 static std::atomic
<unsigned> ActiveASTUnitObjects
;
242 ASTUnit::ASTUnit(bool _MainFileIsAST
)
243 : MainFileIsAST(_MainFileIsAST
), WantTiming(getenv("LIBCLANG_TIMING")),
244 ShouldCacheCodeCompletionResults(false),
245 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
246 UnsafeToFree(false) {
247 if (getenv("LIBCLANG_OBJTRACKING"))
248 fprintf(stderr
, "+++ %u translation units\n", ++ActiveASTUnitObjects
);
251 ASTUnit::~ASTUnit() {
252 // If we loaded from an AST file, balance out the BeginSourceFile call.
253 if (MainFileIsAST
&& getDiagnostics().getClient()) {
254 getDiagnostics().getClient()->EndSourceFile();
257 clearFileLevelDecls();
259 // Free the buffers associated with remapped files. We are required to
260 // perform this operation here because we explicitly request that the
261 // compiler instance *not* free these buffers for each invocation of the
263 if (Invocation
&& OwnsRemappedFileBuffers
) {
264 PreprocessorOptions
&PPOpts
= Invocation
->getPreprocessorOpts();
265 for (const auto &RB
: PPOpts
.RemappedFileBuffers
)
269 ClearCachedCompletionResults();
271 if (getenv("LIBCLANG_OBJTRACKING"))
272 fprintf(stderr
, "--- %u translation units\n", --ActiveASTUnitObjects
);
275 void ASTUnit::setPreprocessor(std::shared_ptr
<Preprocessor
> PP
) {
276 this->PP
= std::move(PP
);
279 void ASTUnit::enableSourceFileDiagnostics() {
280 assert(getDiagnostics().getClient() && Ctx
&&
281 "Bad context for source file");
282 getDiagnostics().getClient()->BeginSourceFile(Ctx
->getLangOpts(), PP
.get());
285 /// Determine the set of code-completion contexts in which this
286 /// declaration should be shown.
287 static uint64_t getDeclShowContexts(const NamedDecl
*ND
,
288 const LangOptions
&LangOpts
,
289 bool &IsNestedNameSpecifier
) {
290 IsNestedNameSpecifier
= false;
292 if (isa
<UsingShadowDecl
>(ND
))
293 ND
= ND
->getUnderlyingDecl();
297 uint64_t Contexts
= 0;
298 if (isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
) ||
299 isa
<ClassTemplateDecl
>(ND
) || isa
<TemplateTemplateParmDecl
>(ND
) ||
300 isa
<TypeAliasTemplateDecl
>(ND
)) {
301 // Types can appear in these contexts.
302 if (LangOpts
.CPlusPlus
|| !isa
<TagDecl
>(ND
))
303 Contexts
|= (1LL << CodeCompletionContext::CCC_TopLevel
)
304 | (1LL << CodeCompletionContext::CCC_ObjCIvarList
)
305 | (1LL << CodeCompletionContext::CCC_ClassStructUnion
)
306 | (1LL << CodeCompletionContext::CCC_Statement
)
307 | (1LL << CodeCompletionContext::CCC_Type
)
308 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression
);
310 // In C++, types can appear in expressions contexts (for functional casts).
311 if (LangOpts
.CPlusPlus
)
312 Contexts
|= (1LL << CodeCompletionContext::CCC_Expression
);
314 // In Objective-C, message sends can send interfaces. In Objective-C++,
315 // all types are available due to functional casts.
316 if (LangOpts
.CPlusPlus
|| isa
<ObjCInterfaceDecl
>(ND
))
317 Contexts
|= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver
);
319 // In Objective-C, you can only be a subclass of another Objective-C class
320 if (const auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(ND
)) {
321 // Objective-C interfaces can be used in a class property expression.
322 if (ID
->getDefinition())
323 Contexts
|= (1LL << CodeCompletionContext::CCC_Expression
);
324 Contexts
|= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName
);
327 // Deal with tag names.
328 if (isa
<EnumDecl
>(ND
)) {
329 Contexts
|= (1LL << CodeCompletionContext::CCC_EnumTag
);
331 // Part of the nested-name-specifier in C++0x.
332 if (LangOpts
.CPlusPlus11
)
333 IsNestedNameSpecifier
= true;
334 } else if (const auto *Record
= dyn_cast
<RecordDecl
>(ND
)) {
335 if (Record
->isUnion())
336 Contexts
|= (1LL << CodeCompletionContext::CCC_UnionTag
);
338 Contexts
|= (1LL << CodeCompletionContext::CCC_ClassOrStructTag
);
340 if (LangOpts
.CPlusPlus
)
341 IsNestedNameSpecifier
= true;
342 } else if (isa
<ClassTemplateDecl
>(ND
))
343 IsNestedNameSpecifier
= true;
344 } else if (isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
)) {
345 // Values can appear in these contexts.
346 Contexts
= (1LL << CodeCompletionContext::CCC_Statement
)
347 | (1LL << CodeCompletionContext::CCC_Expression
)
348 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression
)
349 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver
);
350 } else if (isa
<ObjCProtocolDecl
>(ND
)) {
351 Contexts
= (1LL << CodeCompletionContext::CCC_ObjCProtocolName
);
352 } else if (isa
<ObjCCategoryDecl
>(ND
)) {
353 Contexts
= (1LL << CodeCompletionContext::CCC_ObjCCategoryName
);
354 } else if (isa
<NamespaceDecl
>(ND
) || isa
<NamespaceAliasDecl
>(ND
)) {
355 Contexts
= (1LL << CodeCompletionContext::CCC_Namespace
);
357 // Part of the nested-name-specifier.
358 IsNestedNameSpecifier
= true;
364 void ASTUnit::CacheCodeCompletionResults() {
368 SimpleTimer
Timer(WantTiming
);
369 Timer
.setOutput("Cache global code completions for " + getMainFileName());
371 // Clear out the previous results.
372 ClearCachedCompletionResults();
374 // Gather the set of global code completions.
375 using Result
= CodeCompletionResult
;
376 SmallVector
<Result
, 8> Results
;
377 CachedCompletionAllocator
= std::make_shared
<GlobalCodeCompletionAllocator
>();
378 CodeCompletionTUInfo
CCTUInfo(CachedCompletionAllocator
);
379 TheSema
->GatherGlobalCodeCompletions(*CachedCompletionAllocator
,
382 // Translate global code completions into cached completions.
383 llvm::DenseMap
<CanQualType
, unsigned> CompletionTypes
;
384 CodeCompletionContext
CCContext(CodeCompletionContext::CCC_TopLevel
);
386 for (auto &R
: Results
) {
388 case Result::RK_Declaration
: {
389 bool IsNestedNameSpecifier
= false;
390 CachedCodeCompletionResult CachedResult
;
391 CachedResult
.Completion
= R
.CreateCodeCompletionString(
392 *TheSema
, CCContext
, *CachedCompletionAllocator
, CCTUInfo
,
393 IncludeBriefCommentsInCodeCompletion
);
394 CachedResult
.ShowInContexts
= getDeclShowContexts(
395 R
.Declaration
, Ctx
->getLangOpts(), IsNestedNameSpecifier
);
396 CachedResult
.Priority
= R
.Priority
;
397 CachedResult
.Kind
= R
.CursorKind
;
398 CachedResult
.Availability
= R
.Availability
;
400 // Keep track of the type of this completion in an ASTContext-agnostic
402 QualType UsageType
= getDeclUsageType(*Ctx
, R
.Declaration
);
403 if (UsageType
.isNull()) {
404 CachedResult
.TypeClass
= STC_Void
;
405 CachedResult
.Type
= 0;
407 CanQualType CanUsageType
408 = Ctx
->getCanonicalType(UsageType
.getUnqualifiedType());
409 CachedResult
.TypeClass
= getSimplifiedTypeClass(CanUsageType
);
411 // Determine whether we have already seen this type. If so, we save
412 // ourselves the work of formatting the type string by using the
413 // temporary, CanQualType-based hash table to find the associated value.
414 unsigned &TypeValue
= CompletionTypes
[CanUsageType
];
415 if (TypeValue
== 0) {
416 TypeValue
= CompletionTypes
.size();
417 CachedCompletionTypes
[QualType(CanUsageType
).getAsString()]
421 CachedResult
.Type
= TypeValue
;
424 CachedCompletionResults
.push_back(CachedResult
);
426 /// Handle nested-name-specifiers in C++.
427 if (TheSema
->Context
.getLangOpts().CPlusPlus
&& IsNestedNameSpecifier
&&
428 !R
.StartsNestedNameSpecifier
) {
429 // The contexts in which a nested-name-specifier can appear in C++.
431 = (1LL << CodeCompletionContext::CCC_TopLevel
)
432 | (1LL << CodeCompletionContext::CCC_ObjCIvarList
)
433 | (1LL << CodeCompletionContext::CCC_ClassStructUnion
)
434 | (1LL << CodeCompletionContext::CCC_Statement
)
435 | (1LL << CodeCompletionContext::CCC_Expression
)
436 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver
)
437 | (1LL << CodeCompletionContext::CCC_EnumTag
)
438 | (1LL << CodeCompletionContext::CCC_UnionTag
)
439 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag
)
440 | (1LL << CodeCompletionContext::CCC_Type
)
441 | (1LL << CodeCompletionContext::CCC_SymbolOrNewName
)
442 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression
);
444 if (isa
<NamespaceDecl
>(R
.Declaration
) ||
445 isa
<NamespaceAliasDecl
>(R
.Declaration
))
446 NNSContexts
|= (1LL << CodeCompletionContext::CCC_Namespace
);
448 if (uint64_t RemainingContexts
449 = NNSContexts
& ~CachedResult
.ShowInContexts
) {
450 // If there any contexts where this completion can be a
451 // nested-name-specifier but isn't already an option, create a
452 // nested-name-specifier completion.
453 R
.StartsNestedNameSpecifier
= true;
454 CachedResult
.Completion
= R
.CreateCodeCompletionString(
455 *TheSema
, CCContext
, *CachedCompletionAllocator
, CCTUInfo
,
456 IncludeBriefCommentsInCodeCompletion
);
457 CachedResult
.ShowInContexts
= RemainingContexts
;
458 CachedResult
.Priority
= CCP_NestedNameSpecifier
;
459 CachedResult
.TypeClass
= STC_Void
;
460 CachedResult
.Type
= 0;
461 CachedCompletionResults
.push_back(CachedResult
);
467 case Result::RK_Keyword
:
468 case Result::RK_Pattern
:
469 // Ignore keywords and patterns; we don't care, since they are so
470 // easily regenerated.
473 case Result::RK_Macro
: {
474 CachedCodeCompletionResult CachedResult
;
475 CachedResult
.Completion
= R
.CreateCodeCompletionString(
476 *TheSema
, CCContext
, *CachedCompletionAllocator
, CCTUInfo
,
477 IncludeBriefCommentsInCodeCompletion
);
478 CachedResult
.ShowInContexts
479 = (1LL << CodeCompletionContext::CCC_TopLevel
)
480 | (1LL << CodeCompletionContext::CCC_ObjCInterface
)
481 | (1LL << CodeCompletionContext::CCC_ObjCImplementation
)
482 | (1LL << CodeCompletionContext::CCC_ObjCIvarList
)
483 | (1LL << CodeCompletionContext::CCC_ClassStructUnion
)
484 | (1LL << CodeCompletionContext::CCC_Statement
)
485 | (1LL << CodeCompletionContext::CCC_Expression
)
486 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver
)
487 | (1LL << CodeCompletionContext::CCC_MacroNameUse
)
488 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression
)
489 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression
)
490 | (1LL << CodeCompletionContext::CCC_OtherWithMacros
);
492 CachedResult
.Priority
= R
.Priority
;
493 CachedResult
.Kind
= R
.CursorKind
;
494 CachedResult
.Availability
= R
.Availability
;
495 CachedResult
.TypeClass
= STC_Void
;
496 CachedResult
.Type
= 0;
497 CachedCompletionResults
.push_back(CachedResult
);
503 // Save the current top-level hash value.
504 CompletionCacheTopLevelHashValue
= CurrentTopLevelHashValue
;
507 void ASTUnit::ClearCachedCompletionResults() {
508 CachedCompletionResults
.clear();
509 CachedCompletionTypes
.clear();
510 CachedCompletionAllocator
= nullptr;
515 /// Gathers information from ASTReader that will be used to initialize
517 class ASTInfoCollector
: public ASTReaderListener
{
520 HeaderSearchOptions
&HSOpts
;
521 PreprocessorOptions
&PPOpts
;
522 LangOptions
&LangOpt
;
523 std::shared_ptr
<TargetOptions
> &TargetOpts
;
524 IntrusiveRefCntPtr
<TargetInfo
> &Target
;
526 bool InitializedLanguage
= false;
529 ASTInfoCollector(Preprocessor
&PP
, ASTContext
*Context
,
530 HeaderSearchOptions
&HSOpts
, PreprocessorOptions
&PPOpts
,
531 LangOptions
&LangOpt
,
532 std::shared_ptr
<TargetOptions
> &TargetOpts
,
533 IntrusiveRefCntPtr
<TargetInfo
> &Target
, unsigned &Counter
)
534 : PP(PP
), Context(Context
), HSOpts(HSOpts
), PPOpts(PPOpts
),
535 LangOpt(LangOpt
), TargetOpts(TargetOpts
), Target(Target
),
538 bool ReadLanguageOptions(const LangOptions
&LangOpts
, bool Complain
,
539 bool AllowCompatibleDifferences
) override
{
540 if (InitializedLanguage
)
544 InitializedLanguage
= true;
550 bool ReadHeaderSearchOptions(const HeaderSearchOptions
&HSOpts
,
551 StringRef SpecificModuleCachePath
,
552 bool Complain
) override
{
553 this->HSOpts
= HSOpts
;
557 bool ReadPreprocessorOptions(const PreprocessorOptions
&PPOpts
, bool Complain
,
558 std::string
&SuggestedPredefines
) override
{
559 this->PPOpts
= PPOpts
;
563 bool ReadTargetOptions(const TargetOptions
&TargetOpts
, bool Complain
,
564 bool AllowCompatibleDifferences
) override
{
565 // If we've already initialized the target, don't do it again.
569 this->TargetOpts
= std::make_shared
<TargetOptions
>(TargetOpts
);
571 TargetInfo::CreateTargetInfo(PP
.getDiagnostics(), this->TargetOpts
);
577 void ReadCounter(const serialization::ModuleFile
&M
,
578 unsigned Value
) override
{
584 if (!Target
|| !InitializedLanguage
)
587 // Inform the target of the language options.
589 // FIXME: We shouldn't need to do this, the target should be immutable once
590 // created. This complexity should be lifted elsewhere.
591 Target
->adjust(PP
.getDiagnostics(), LangOpt
);
593 // Initialize the preprocessor.
594 PP
.Initialize(*Target
);
599 // Initialize the ASTContext
600 Context
->InitBuiltinTypes(*Target
);
602 // Adjust printing policy based on language options.
603 Context
->setPrintingPolicy(PrintingPolicy(LangOpt
));
605 // We didn't have access to the comment options when the ASTContext was
606 // constructed, so register them now.
607 Context
->getCommentCommandTraits().registerCommentOptions(
608 LangOpt
.CommentOpts
);
612 /// Diagnostic consumer that saves each diagnostic it is given.
613 class FilterAndStoreDiagnosticConsumer
: public DiagnosticConsumer
{
614 SmallVectorImpl
<StoredDiagnostic
> *StoredDiags
;
615 SmallVectorImpl
<ASTUnit::StandaloneDiagnostic
> *StandaloneDiags
;
616 bool CaptureNonErrorsFromIncludes
= true;
617 const LangOptions
*LangOpts
= nullptr;
618 SourceManager
*SourceMgr
= nullptr;
621 FilterAndStoreDiagnosticConsumer(
622 SmallVectorImpl
<StoredDiagnostic
> *StoredDiags
,
623 SmallVectorImpl
<ASTUnit::StandaloneDiagnostic
> *StandaloneDiags
,
624 bool CaptureNonErrorsFromIncludes
)
625 : StoredDiags(StoredDiags
), StandaloneDiags(StandaloneDiags
),
626 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes
) {
627 assert((StoredDiags
|| StandaloneDiags
) &&
628 "No output collections were passed to StoredDiagnosticConsumer.");
631 void BeginSourceFile(const LangOptions
&LangOpts
,
632 const Preprocessor
*PP
= nullptr) override
{
633 this->LangOpts
= &LangOpts
;
635 SourceMgr
= &PP
->getSourceManager();
638 void HandleDiagnostic(DiagnosticsEngine::Level Level
,
639 const Diagnostic
&Info
) override
;
642 /// RAII object that optionally captures and filters diagnostics, if
643 /// there is no diagnostic client to capture them already.
644 class CaptureDroppedDiagnostics
{
645 DiagnosticsEngine
&Diags
;
646 FilterAndStoreDiagnosticConsumer Client
;
647 DiagnosticConsumer
*PreviousClient
= nullptr;
648 std::unique_ptr
<DiagnosticConsumer
> OwningPreviousClient
;
651 CaptureDroppedDiagnostics(
652 CaptureDiagsKind CaptureDiagnostics
, DiagnosticsEngine
&Diags
,
653 SmallVectorImpl
<StoredDiagnostic
> *StoredDiags
,
654 SmallVectorImpl
<ASTUnit::StandaloneDiagnostic
> *StandaloneDiags
)
656 Client(StoredDiags
, StandaloneDiags
,
657 CaptureDiagnostics
!=
658 CaptureDiagsKind::AllWithoutNonErrorsFromIncludes
) {
659 if (CaptureDiagnostics
!= CaptureDiagsKind::None
||
660 Diags
.getClient() == nullptr) {
661 OwningPreviousClient
= Diags
.takeClient();
662 PreviousClient
= Diags
.getClient();
663 Diags
.setClient(&Client
, false);
667 ~CaptureDroppedDiagnostics() {
668 if (Diags
.getClient() == &Client
)
669 Diags
.setClient(PreviousClient
, !!OwningPreviousClient
.release());
675 static ASTUnit::StandaloneDiagnostic
676 makeStandaloneDiagnostic(const LangOptions
&LangOpts
,
677 const StoredDiagnostic
&InDiag
);
679 static bool isInMainFile(const clang::Diagnostic
&D
) {
680 if (!D
.hasSourceManager() || !D
.getLocation().isValid())
683 auto &M
= D
.getSourceManager();
684 return M
.isWrittenInMainFile(M
.getExpansionLoc(D
.getLocation()));
687 void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
688 DiagnosticsEngine::Level Level
, const Diagnostic
&Info
) {
689 // Default implementation (Warnings/errors count).
690 DiagnosticConsumer::HandleDiagnostic(Level
, Info
);
692 // Only record the diagnostic if it's part of the source manager we know
693 // about. This effectively drops diagnostics from modules we're building.
694 // FIXME: In the long run, ee don't want to drop source managers from modules.
695 if (!Info
.hasSourceManager() || &Info
.getSourceManager() == SourceMgr
) {
696 if (!CaptureNonErrorsFromIncludes
&& Level
<= DiagnosticsEngine::Warning
&&
697 !isInMainFile(Info
)) {
701 StoredDiagnostic
*ResultDiag
= nullptr;
703 StoredDiags
->emplace_back(Level
, Info
);
704 ResultDiag
= &StoredDiags
->back();
707 if (StandaloneDiags
) {
708 llvm::Optional
<StoredDiagnostic
> StoredDiag
;
710 StoredDiag
.emplace(Level
, Info
);
711 ResultDiag
= StoredDiag
.getPointer();
713 StandaloneDiags
->push_back(
714 makeStandaloneDiagnostic(*LangOpts
, *ResultDiag
));
719 IntrusiveRefCntPtr
<ASTReader
> ASTUnit::getASTReader() const {
723 ASTMutationListener
*ASTUnit::getASTMutationListener() {
725 return &WriterData
->Writer
;
729 ASTDeserializationListener
*ASTUnit::getDeserializationListener() {
731 return &WriterData
->Writer
;
735 std::unique_ptr
<llvm::MemoryBuffer
>
736 ASTUnit::getBufferForFile(StringRef Filename
, std::string
*ErrorStr
) {
738 auto Buffer
= FileMgr
->getBufferForFile(Filename
, UserFilesAreVolatile
);
740 return std::move(*Buffer
);
742 *ErrorStr
= Buffer
.getError().message();
746 /// Configure the diagnostics object for use with ASTUnit.
747 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags
,
749 CaptureDiagsKind CaptureDiagnostics
) {
750 assert(Diags
.get() && "no DiagnosticsEngine was provided");
751 if (CaptureDiagnostics
!= CaptureDiagsKind::None
)
752 Diags
->setClient(new FilterAndStoreDiagnosticConsumer(
753 &AST
.StoredDiagnostics
, nullptr,
754 CaptureDiagnostics
!= CaptureDiagsKind::AllWithoutNonErrorsFromIncludes
));
757 std::unique_ptr
<ASTUnit
> ASTUnit::LoadFromASTFile(
758 const std::string
&Filename
, const PCHContainerReader
&PCHContainerRdr
,
759 WhatToLoad ToLoad
, IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags
,
760 const FileSystemOptions
&FileSystemOpts
, bool UseDebugInfo
,
761 bool OnlyLocalDecls
, CaptureDiagsKind CaptureDiagnostics
,
762 bool AllowASTWithCompilerErrors
, bool UserFilesAreVolatile
,
763 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
) {
764 std::unique_ptr
<ASTUnit
> AST(new ASTUnit(true));
766 // Recover resources if we crash before exiting this method.
767 llvm::CrashRecoveryContextCleanupRegistrar
<ASTUnit
>
768 ASTUnitCleanup(AST
.get());
769 llvm::CrashRecoveryContextCleanupRegistrar
<DiagnosticsEngine
,
770 llvm::CrashRecoveryContextReleaseRefCleanup
<DiagnosticsEngine
>>
771 DiagCleanup(Diags
.get());
773 ConfigureDiags(Diags
, *AST
, CaptureDiagnostics
);
775 AST
->LangOpts
= std::make_shared
<LangOptions
>();
776 AST
->OnlyLocalDecls
= OnlyLocalDecls
;
777 AST
->CaptureDiagnostics
= CaptureDiagnostics
;
778 AST
->Diagnostics
= Diags
;
779 AST
->FileMgr
= new FileManager(FileSystemOpts
, VFS
);
780 AST
->UserFilesAreVolatile
= UserFilesAreVolatile
;
781 AST
->SourceMgr
= new SourceManager(AST
->getDiagnostics(),
782 AST
->getFileManager(),
783 UserFilesAreVolatile
);
784 AST
->ModuleCache
= new InMemoryModuleCache
;
785 AST
->HSOpts
= std::make_shared
<HeaderSearchOptions
>();
786 AST
->HSOpts
->ModuleFormat
= std::string(PCHContainerRdr
.getFormat());
787 AST
->HeaderInfo
.reset(new HeaderSearch(AST
->HSOpts
,
788 AST
->getSourceManager(),
789 AST
->getDiagnostics(),
791 /*Target=*/nullptr));
792 AST
->PPOpts
= std::make_shared
<PreprocessorOptions
>();
794 // Gather Info for preprocessor construction later on.
796 HeaderSearch
&HeaderInfo
= *AST
->HeaderInfo
;
799 AST
->PP
= std::make_shared
<Preprocessor
>(
800 AST
->PPOpts
, AST
->getDiagnostics(), *AST
->LangOpts
,
801 AST
->getSourceManager(), HeaderInfo
, AST
->ModuleLoader
,
802 /*IILookup=*/nullptr,
803 /*OwnsHeaderSearch=*/false);
804 Preprocessor
&PP
= *AST
->PP
;
806 if (ToLoad
>= LoadASTOnly
)
807 AST
->Ctx
= new ASTContext(*AST
->LangOpts
, AST
->getSourceManager(),
808 PP
.getIdentifierTable(), PP
.getSelectorTable(),
810 AST
->getTranslationUnitKind());
812 DisableValidationForModuleKind disableValid
=
813 DisableValidationForModuleKind::None
;
814 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
815 disableValid
= DisableValidationForModuleKind::All
;
816 AST
->Reader
= new ASTReader(
817 PP
, *AST
->ModuleCache
, AST
->Ctx
.get(), PCHContainerRdr
, {},
819 /*DisableValidationKind=*/disableValid
, AllowASTWithCompilerErrors
);
821 AST
->Reader
->setListener(std::make_unique
<ASTInfoCollector
>(
822 *AST
->PP
, AST
->Ctx
.get(), *AST
->HSOpts
, *AST
->PPOpts
, *AST
->LangOpts
,
823 AST
->TargetOpts
, AST
->Target
, Counter
));
825 // Attach the AST reader to the AST context as an external AST
826 // source, so that declarations will be deserialized from the
827 // AST file as needed.
828 // We need the external source to be set up before we read the AST, because
829 // eagerly-deserialized declarations may use it.
831 AST
->Ctx
->setExternalSource(AST
->Reader
);
833 switch (AST
->Reader
->ReadAST(Filename
, serialization::MK_MainFile
,
834 SourceLocation(), ASTReader::ARR_None
)) {
835 case ASTReader::Success
:
838 case ASTReader::Failure
:
839 case ASTReader::Missing
:
840 case ASTReader::OutOfDate
:
841 case ASTReader::VersionMismatch
:
842 case ASTReader::ConfigurationMismatch
:
843 case ASTReader::HadErrors
:
844 AST
->getDiagnostics().Report(diag::err_fe_unable_to_load_pch
);
848 AST
->OriginalSourceFile
= std::string(AST
->Reader
->getOriginalSourceFile());
850 PP
.setCounterValue(Counter
);
852 // Create an AST consumer, even though it isn't used.
853 if (ToLoad
>= LoadASTOnly
)
854 AST
->Consumer
.reset(new ASTConsumer
);
856 // Create a semantic analysis object and tell the AST reader about it.
857 if (ToLoad
>= LoadEverything
) {
858 AST
->TheSema
.reset(new Sema(PP
, *AST
->Ctx
, *AST
->Consumer
));
859 AST
->TheSema
->Initialize();
860 AST
->Reader
->InitializeSema(*AST
->TheSema
);
863 // Tell the diagnostic client that we have started a source file.
864 AST
->getDiagnostics().getClient()->BeginSourceFile(PP
.getLangOpts(), &PP
);
869 /// Add the given macro to the hash of all top-level entities.
870 static void AddDefinedMacroToHash(const Token
&MacroNameTok
, unsigned &Hash
) {
871 Hash
= llvm::djbHash(MacroNameTok
.getIdentifierInfo()->getName(), Hash
);
876 /// Preprocessor callback class that updates a hash value with the names
877 /// of all macros that have been defined by the translation unit.
878 class MacroDefinitionTrackerPPCallbacks
: public PPCallbacks
{
882 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash
) : Hash(Hash
) {}
884 void MacroDefined(const Token
&MacroNameTok
,
885 const MacroDirective
*MD
) override
{
886 AddDefinedMacroToHash(MacroNameTok
, Hash
);
892 /// Add the given declaration to the hash of all top-level entities.
893 static void AddTopLevelDeclarationToHash(Decl
*D
, unsigned &Hash
) {
897 DeclContext
*DC
= D
->getDeclContext();
901 if (!(DC
->isTranslationUnit() || DC
->getLookupParent()->isTranslationUnit()))
904 if (const auto *ND
= dyn_cast
<NamedDecl
>(D
)) {
905 if (const auto *EnumD
= dyn_cast
<EnumDecl
>(D
)) {
906 // For an unscoped enum include the enumerators in the hash since they
907 // enter the top-level namespace.
908 if (!EnumD
->isScoped()) {
909 for (const auto *EI
: EnumD
->enumerators()) {
910 if (EI
->getIdentifier())
911 Hash
= llvm::djbHash(EI
->getIdentifier()->getName(), Hash
);
916 if (ND
->getIdentifier())
917 Hash
= llvm::djbHash(ND
->getIdentifier()->getName(), Hash
);
918 else if (DeclarationName Name
= ND
->getDeclName()) {
919 std::string NameStr
= Name
.getAsString();
920 Hash
= llvm::djbHash(NameStr
, Hash
);
925 if (const auto *ImportD
= dyn_cast
<ImportDecl
>(D
)) {
926 if (const Module
*Mod
= ImportD
->getImportedModule()) {
927 std::string ModName
= Mod
->getFullModuleName();
928 Hash
= llvm::djbHash(ModName
, Hash
);
936 class TopLevelDeclTrackerConsumer
: public ASTConsumer
{
941 TopLevelDeclTrackerConsumer(ASTUnit
&_Unit
, unsigned &Hash
)
942 : Unit(_Unit
), Hash(Hash
) {
946 void handleTopLevelDecl(Decl
*D
) {
950 // FIXME: Currently ObjC method declarations are incorrectly being
951 // reported as top-level declarations, even though their DeclContext
952 // is the containing ObjC @interface/@implementation. This is a
953 // fundamental problem in the parser right now.
954 if (isa
<ObjCMethodDecl
>(D
))
957 AddTopLevelDeclarationToHash(D
, Hash
);
958 Unit
.addTopLevelDecl(D
);
960 handleFileLevelDecl(D
);
963 void handleFileLevelDecl(Decl
*D
) {
964 Unit
.addFileLevelDecl(D
);
965 if (auto *NSD
= dyn_cast
<NamespaceDecl
>(D
)) {
966 for (auto *I
: NSD
->decls())
967 handleFileLevelDecl(I
);
971 bool HandleTopLevelDecl(DeclGroupRef D
) override
{
972 for (auto *TopLevelDecl
: D
)
973 handleTopLevelDecl(TopLevelDecl
);
977 // We're not interested in "interesting" decls.
978 void HandleInterestingDecl(DeclGroupRef
) override
{}
980 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D
) override
{
981 for (auto *TopLevelDecl
: D
)
982 handleTopLevelDecl(TopLevelDecl
);
985 ASTMutationListener
*GetASTMutationListener() override
{
986 return Unit
.getASTMutationListener();
989 ASTDeserializationListener
*GetASTDeserializationListener() override
{
990 return Unit
.getDeserializationListener();
994 class TopLevelDeclTrackerAction
: public ASTFrontendAction
{
998 std::unique_ptr
<ASTConsumer
> CreateASTConsumer(CompilerInstance
&CI
,
999 StringRef InFile
) override
{
1000 CI
.getPreprocessor().addPPCallbacks(
1001 std::make_unique
<MacroDefinitionTrackerPPCallbacks
>(
1002 Unit
.getCurrentTopLevelHashValue()));
1003 return std::make_unique
<TopLevelDeclTrackerConsumer
>(
1004 Unit
, Unit
.getCurrentTopLevelHashValue());
1008 TopLevelDeclTrackerAction(ASTUnit
&_Unit
) : Unit(_Unit
) {}
1010 bool hasCodeCompletionSupport() const override
{ return false; }
1012 TranslationUnitKind
getTranslationUnitKind() override
{
1013 return Unit
.getTranslationUnitKind();
1017 class ASTUnitPreambleCallbacks
: public PreambleCallbacks
{
1019 unsigned getHash() const { return Hash
; }
1021 std::vector
<Decl
*> takeTopLevelDecls() { return std::move(TopLevelDecls
); }
1023 std::vector
<serialization::DeclID
> takeTopLevelDeclIDs() {
1024 return std::move(TopLevelDeclIDs
);
1027 void AfterPCHEmitted(ASTWriter
&Writer
) override
{
1028 TopLevelDeclIDs
.reserve(TopLevelDecls
.size());
1029 for (const auto *D
: TopLevelDecls
) {
1030 // Invalid top-level decls may not have been serialized.
1031 if (D
->isInvalidDecl())
1033 TopLevelDeclIDs
.push_back(Writer
.getDeclID(D
));
1037 void HandleTopLevelDecl(DeclGroupRef DG
) override
{
1038 for (auto *D
: DG
) {
1039 // FIXME: Currently ObjC method declarations are incorrectly being
1040 // reported as top-level declarations, even though their DeclContext
1041 // is the containing ObjC @interface/@implementation. This is a
1042 // fundamental problem in the parser right now.
1043 if (isa
<ObjCMethodDecl
>(D
))
1045 AddTopLevelDeclarationToHash(D
, Hash
);
1046 TopLevelDecls
.push_back(D
);
1050 std::unique_ptr
<PPCallbacks
> createPPCallbacks() override
{
1051 return std::make_unique
<MacroDefinitionTrackerPPCallbacks
>(Hash
);
1056 std::vector
<Decl
*> TopLevelDecls
;
1057 std::vector
<serialization::DeclID
> TopLevelDeclIDs
;
1058 llvm::SmallVector
<ASTUnit::StandaloneDiagnostic
, 4> PreambleDiags
;
1063 static bool isNonDriverDiag(const StoredDiagnostic
&StoredDiag
) {
1064 return StoredDiag
.getLocation().isValid();
1068 checkAndRemoveNonDriverDiags(SmallVectorImpl
<StoredDiagnostic
> &StoredDiags
) {
1069 // Get rid of stored diagnostics except the ones from the driver which do not
1070 // have a source location.
1071 llvm::erase_if(StoredDiags
, isNonDriverDiag
);
1074 static void checkAndSanitizeDiags(SmallVectorImpl
<StoredDiagnostic
> &
1076 SourceManager
&SM
) {
1077 // The stored diagnostic has the old source manager in it; update
1078 // the locations to refer into the new source manager. Since we've
1079 // been careful to make sure that the source manager's state
1080 // before and after are identical, so that we can reuse the source
1082 for (auto &SD
: StoredDiagnostics
) {
1083 if (SD
.getLocation().isValid()) {
1084 FullSourceLoc
Loc(SD
.getLocation(), SM
);
1085 SD
.setLocation(Loc
);
1090 /// Parse the source file into a translation unit using the given compiler
1091 /// invocation, replacing the current translation unit.
1093 /// \returns True if a failure occurred that causes the ASTUnit not to
1094 /// contain any translation-unit information, false otherwise.
1095 bool ASTUnit::Parse(std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1096 std::unique_ptr
<llvm::MemoryBuffer
> OverrideMainBuffer
,
1097 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
) {
1102 assert(VFS
== &FileMgr
->getVirtualFileSystem() &&
1103 "VFS passed to Parse and VFS in FileMgr are different");
1105 auto CCInvocation
= std::make_shared
<CompilerInvocation
>(*Invocation
);
1106 if (OverrideMainBuffer
) {
1108 "No preamble was built, but OverrideMainBuffer is not null");
1109 Preamble
->AddImplicitPreamble(*CCInvocation
, VFS
, OverrideMainBuffer
.get());
1110 // VFS may have changed...
1113 // Create the compiler instance to use for building the AST.
1114 std::unique_ptr
<CompilerInstance
> Clang(
1115 new CompilerInstance(std::move(PCHContainerOps
)));
1117 // Clean up on error, disengage it if the function returns successfully.
1118 auto CleanOnError
= llvm::make_scope_exit([&]() {
1119 // Remove the overridden buffer we used for the preamble.
1120 SavedMainFileBuffer
= nullptr;
1122 // Keep the ownership of the data in the ASTUnit because the client may
1123 // want to see the diagnostics.
1124 transferASTDataFromCompilerInstance(*Clang
);
1125 FailedParseDiagnostics
.swap(StoredDiagnostics
);
1126 StoredDiagnostics
.clear();
1127 NumStoredDiagnosticsFromDriver
= 0;
1130 // Ensure that Clang has a FileManager with the right VFS, which may have
1131 // changed above in AddImplicitPreamble. If VFS is nullptr, rely on
1132 // createFileManager to create one.
1133 if (VFS
&& FileMgr
&& &FileMgr
->getVirtualFileSystem() == VFS
)
1134 Clang
->setFileManager(&*FileMgr
);
1136 FileMgr
= Clang
->createFileManager(std::move(VFS
));
1138 // Recover resources if we crash before exiting this method.
1139 llvm::CrashRecoveryContextCleanupRegistrar
<CompilerInstance
>
1140 CICleanup(Clang
.get());
1142 Clang
->setInvocation(CCInvocation
);
1143 OriginalSourceFile
=
1144 std::string(Clang
->getFrontendOpts().Inputs
[0].getFile());
1146 // Set up diagnostics, capturing any diagnostics that would
1147 // otherwise be dropped.
1148 Clang
->setDiagnostics(&getDiagnostics());
1150 // Create the target instance.
1151 if (!Clang
->createTarget())
1154 assert(Clang
->getFrontendOpts().Inputs
.size() == 1 &&
1155 "Invocation must have exactly one source file!");
1156 assert(Clang
->getFrontendOpts().Inputs
[0].getKind().getFormat() ==
1157 InputKind::Source
&&
1158 "FIXME: AST inputs not yet supported here!");
1159 assert(Clang
->getFrontendOpts().Inputs
[0].getKind().getLanguage() !=
1160 Language::LLVM_IR
&&
1161 "IR inputs not support here!");
1163 // Configure the various subsystems.
1164 LangOpts
= Clang
->getInvocation().LangOpts
;
1165 FileSystemOpts
= Clang
->getFileSystemOpts();
1169 SourceMgr
= new SourceManager(getDiagnostics(), *FileMgr
,
1170 UserFilesAreVolatile
);
1171 if (!OverrideMainBuffer
) {
1172 checkAndRemoveNonDriverDiags(StoredDiagnostics
);
1173 TopLevelDeclsInPreamble
.clear();
1176 // Create the source manager.
1177 Clang
->setSourceManager(&getSourceManager());
1179 // If the main file has been overridden due to the use of a preamble,
1180 // make that override happen and introduce the preamble.
1181 if (OverrideMainBuffer
) {
1182 // The stored diagnostic has the old source manager in it; update
1183 // the locations to refer into the new source manager. Since we've
1184 // been careful to make sure that the source manager's state
1185 // before and after are identical, so that we can reuse the source
1187 checkAndSanitizeDiags(StoredDiagnostics
, getSourceManager());
1189 // Keep track of the override buffer;
1190 SavedMainFileBuffer
= std::move(OverrideMainBuffer
);
1193 std::unique_ptr
<TopLevelDeclTrackerAction
> Act(
1194 new TopLevelDeclTrackerAction(*this));
1196 // Recover resources if we crash before exiting this method.
1197 llvm::CrashRecoveryContextCleanupRegistrar
<TopLevelDeclTrackerAction
>
1198 ActCleanup(Act
.get());
1200 if (!Act
->BeginSourceFile(*Clang
.get(), Clang
->getFrontendOpts().Inputs
[0]))
1203 if (SavedMainFileBuffer
)
1204 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1205 PreambleDiagnostics
, StoredDiagnostics
);
1207 PreambleSrcLocCache
.clear();
1209 if (llvm::Error Err
= Act
->Execute()) {
1210 consumeError(std::move(Err
)); // FIXME this drops errors on the floor.
1214 transferASTDataFromCompilerInstance(*Clang
);
1216 Act
->EndSourceFile();
1218 FailedParseDiagnostics
.clear();
1220 CleanOnError
.release();
1225 static std::pair
<unsigned, unsigned>
1226 makeStandaloneRange(CharSourceRange Range
, const SourceManager
&SM
,
1227 const LangOptions
&LangOpts
) {
1228 CharSourceRange FileRange
= Lexer::makeFileCharRange(Range
, SM
, LangOpts
);
1229 unsigned Offset
= SM
.getFileOffset(FileRange
.getBegin());
1230 unsigned EndOffset
= SM
.getFileOffset(FileRange
.getEnd());
1231 return std::make_pair(Offset
, EndOffset
);
1234 static ASTUnit::StandaloneFixIt
makeStandaloneFixIt(const SourceManager
&SM
,
1235 const LangOptions
&LangOpts
,
1236 const FixItHint
&InFix
) {
1237 ASTUnit::StandaloneFixIt OutFix
;
1238 OutFix
.RemoveRange
= makeStandaloneRange(InFix
.RemoveRange
, SM
, LangOpts
);
1239 OutFix
.InsertFromRange
= makeStandaloneRange(InFix
.InsertFromRange
, SM
,
1241 OutFix
.CodeToInsert
= InFix
.CodeToInsert
;
1242 OutFix
.BeforePreviousInsertions
= InFix
.BeforePreviousInsertions
;
1246 static ASTUnit::StandaloneDiagnostic
1247 makeStandaloneDiagnostic(const LangOptions
&LangOpts
,
1248 const StoredDiagnostic
&InDiag
) {
1249 ASTUnit::StandaloneDiagnostic OutDiag
;
1250 OutDiag
.ID
= InDiag
.getID();
1251 OutDiag
.Level
= InDiag
.getLevel();
1252 OutDiag
.Message
= std::string(InDiag
.getMessage());
1253 OutDiag
.LocOffset
= 0;
1254 if (InDiag
.getLocation().isInvalid())
1256 const SourceManager
&SM
= InDiag
.getLocation().getManager();
1257 SourceLocation FileLoc
= SM
.getFileLoc(InDiag
.getLocation());
1258 OutDiag
.Filename
= std::string(SM
.getFilename(FileLoc
));
1259 if (OutDiag
.Filename
.empty())
1261 OutDiag
.LocOffset
= SM
.getFileOffset(FileLoc
);
1262 for (const auto &Range
: InDiag
.getRanges())
1263 OutDiag
.Ranges
.push_back(makeStandaloneRange(Range
, SM
, LangOpts
));
1264 for (const auto &FixIt
: InDiag
.getFixIts())
1265 OutDiag
.FixIts
.push_back(makeStandaloneFixIt(SM
, LangOpts
, FixIt
));
1270 /// Attempt to build or re-use a precompiled preamble when (re-)parsing
1271 /// the source file.
1273 /// This routine will compute the preamble of the main source file. If a
1274 /// non-trivial preamble is found, it will precompile that preamble into a
1275 /// precompiled header so that the precompiled preamble can be used to reduce
1276 /// reparsing time. If a precompiled preamble has already been constructed,
1277 /// this routine will determine if it is still valid and, if so, avoid
1278 /// rebuilding the precompiled preamble.
1280 /// \param AllowRebuild When true (the default), this routine is
1281 /// allowed to rebuild the precompiled preamble if it is found to be
1284 /// \param MaxLines When non-zero, the maximum number of lines that
1285 /// can occur within the preamble.
1287 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1288 /// buffer that should be used in place of the main file when doing so.
1289 /// Otherwise, returns a NULL pointer.
1290 std::unique_ptr
<llvm::MemoryBuffer
>
1291 ASTUnit::getMainBufferWithPrecompiledPreamble(
1292 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1293 CompilerInvocation
&PreambleInvocationIn
,
1294 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
, bool AllowRebuild
,
1295 unsigned MaxLines
) {
1297 PreambleInvocationIn
.getFrontendOpts().Inputs
[0].getFile();
1298 std::unique_ptr
<llvm::MemoryBuffer
> MainFileBuffer
=
1299 getBufferForFileHandlingRemapping(PreambleInvocationIn
, VFS
.get(),
1300 MainFilePath
, UserFilesAreVolatile
);
1301 if (!MainFileBuffer
)
1304 PreambleBounds Bounds
= ComputePreambleBounds(
1305 *PreambleInvocationIn
.getLangOpts(), *MainFileBuffer
, MaxLines
);
1310 if (Preamble
->CanReuse(PreambleInvocationIn
, *MainFileBuffer
, Bounds
,
1312 // Okay! We can re-use the precompiled preamble.
1314 // Set the state of the diagnostic object to mimic its state
1315 // after parsing the preamble.
1316 getDiagnostics().Reset();
1317 ProcessWarningOptions(getDiagnostics(),
1318 PreambleInvocationIn
.getDiagnosticOpts());
1319 getDiagnostics().setNumWarnings(NumWarningsInPreamble
);
1321 PreambleRebuildCountdown
= 1;
1322 return MainFileBuffer
;
1325 PreambleDiagnostics
.clear();
1326 TopLevelDeclsInPreamble
.clear();
1327 PreambleSrcLocCache
.clear();
1328 PreambleRebuildCountdown
= 1;
1332 // If the preamble rebuild counter > 1, it's because we previously
1333 // failed to build a preamble and we're not yet ready to try
1334 // again. Decrement the counter and return a failure.
1335 if (PreambleRebuildCountdown
> 1) {
1336 --PreambleRebuildCountdown
;
1340 assert(!Preamble
&& "No Preamble should be stored at that point");
1341 // If we aren't allowed to rebuild the precompiled preamble, just
1348 SmallVector
<StandaloneDiagnostic
, 4> NewPreambleDiagsStandalone
;
1349 SmallVector
<StoredDiagnostic
, 4> NewPreambleDiags
;
1350 ASTUnitPreambleCallbacks Callbacks
;
1352 llvm::Optional
<CaptureDroppedDiagnostics
> Capture
;
1353 if (CaptureDiagnostics
!= CaptureDiagsKind::None
)
1354 Capture
.emplace(CaptureDiagnostics
, *Diagnostics
, &NewPreambleDiags
,
1355 &NewPreambleDiagsStandalone
);
1357 // We did not previously compute a preamble, or it can't be reused anyway.
1358 SimpleTimer
PreambleTimer(WantTiming
);
1359 PreambleTimer
.setOutput("Precompiling preamble");
1361 const bool PreviousSkipFunctionBodies
=
1362 PreambleInvocationIn
.getFrontendOpts().SkipFunctionBodies
;
1363 if (SkipFunctionBodies
== SkipFunctionBodiesScope::Preamble
)
1364 PreambleInvocationIn
.getFrontendOpts().SkipFunctionBodies
= true;
1366 llvm::ErrorOr
<PrecompiledPreamble
> NewPreamble
= PrecompiledPreamble::Build(
1367 PreambleInvocationIn
, MainFileBuffer
.get(), Bounds
, *Diagnostics
, VFS
,
1368 PCHContainerOps
, /*StoreInMemory=*/false, Callbacks
);
1370 PreambleInvocationIn
.getFrontendOpts().SkipFunctionBodies
=
1371 PreviousSkipFunctionBodies
;
1374 Preamble
= std::move(*NewPreamble
);
1375 PreambleRebuildCountdown
= 1;
1377 switch (static_cast<BuildPreambleError
>(NewPreamble
.getError().value())) {
1378 case BuildPreambleError::CouldntCreateTempFile
:
1379 // Try again next time.
1380 PreambleRebuildCountdown
= 1;
1382 case BuildPreambleError::CouldntCreateTargetInfo
:
1383 case BuildPreambleError::BeginSourceFileFailed
:
1384 case BuildPreambleError::CouldntEmitPCH
:
1385 case BuildPreambleError::BadInputs
:
1386 // These erros are more likely to repeat, retry after some period.
1387 PreambleRebuildCountdown
= DefaultPreambleRebuildInterval
;
1390 llvm_unreachable("unexpected BuildPreambleError");
1394 assert(Preamble
&& "Preamble wasn't built");
1396 TopLevelDecls
.clear();
1397 TopLevelDeclsInPreamble
= Callbacks
.takeTopLevelDeclIDs();
1398 PreambleTopLevelHashValue
= Callbacks
.getHash();
1400 NumWarningsInPreamble
= getDiagnostics().getNumWarnings();
1402 checkAndRemoveNonDriverDiags(NewPreambleDiags
);
1403 StoredDiagnostics
= std::move(NewPreambleDiags
);
1404 PreambleDiagnostics
= std::move(NewPreambleDiagsStandalone
);
1406 // If the hash of top-level entities differs from the hash of the top-level
1407 // entities the last time we rebuilt the preamble, clear out the completion
1409 if (CurrentTopLevelHashValue
!= PreambleTopLevelHashValue
) {
1410 CompletionCacheTopLevelHashValue
= 0;
1411 PreambleTopLevelHashValue
= CurrentTopLevelHashValue
;
1414 return MainFileBuffer
;
1417 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1418 assert(Preamble
&& "Should only be called when preamble was built");
1420 std::vector
<Decl
*> Resolved
;
1421 Resolved
.reserve(TopLevelDeclsInPreamble
.size());
1422 ExternalASTSource
&Source
= *getASTContext().getExternalSource();
1423 for (const auto TopLevelDecl
: TopLevelDeclsInPreamble
) {
1424 // Resolve the declaration ID to an actual declaration, possibly
1425 // deserializing the declaration in the process.
1426 if (Decl
*D
= Source
.GetExternalDecl(TopLevelDecl
))
1427 Resolved
.push_back(D
);
1429 TopLevelDeclsInPreamble
.clear();
1430 TopLevelDecls
.insert(TopLevelDecls
.begin(), Resolved
.begin(), Resolved
.end());
1433 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance
&CI
) {
1434 // Steal the created target, context, and preprocessor if they have been
1436 assert(CI
.hasInvocation() && "missing invocation");
1437 LangOpts
= CI
.getInvocation().LangOpts
;
1438 TheSema
= CI
.takeSema();
1439 Consumer
= CI
.takeASTConsumer();
1440 if (CI
.hasASTContext())
1441 Ctx
= &CI
.getASTContext();
1442 if (CI
.hasPreprocessor())
1443 PP
= CI
.getPreprocessorPtr();
1444 CI
.setSourceManager(nullptr);
1445 CI
.setFileManager(nullptr);
1447 Target
= &CI
.getTarget();
1448 Reader
= CI
.getASTReader();
1449 HadModuleLoaderFatalFailure
= CI
.hadModuleLoaderFatalFailure();
1452 StringRef
ASTUnit::getMainFileName() const {
1453 if (Invocation
&& !Invocation
->getFrontendOpts().Inputs
.empty()) {
1454 const FrontendInputFile
&Input
= Invocation
->getFrontendOpts().Inputs
[0];
1456 return Input
.getFile();
1458 return Input
.getBuffer().getBufferIdentifier();
1462 if (const FileEntry
*
1463 FE
= SourceMgr
->getFileEntryForID(SourceMgr
->getMainFileID()))
1464 return FE
->getName();
1470 StringRef
ASTUnit::getASTFileName() const {
1471 if (!isMainFileAST())
1474 serialization::ModuleFile
&
1475 Mod
= Reader
->getModuleManager().getPrimaryModule();
1476 return Mod
.FileName
;
1479 std::unique_ptr
<ASTUnit
>
1480 ASTUnit::create(std::shared_ptr
<CompilerInvocation
> CI
,
1481 IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags
,
1482 CaptureDiagsKind CaptureDiagnostics
,
1483 bool UserFilesAreVolatile
) {
1484 std::unique_ptr
<ASTUnit
> AST(new ASTUnit(false));
1485 ConfigureDiags(Diags
, *AST
, CaptureDiagnostics
);
1486 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
=
1487 createVFSFromCompilerInvocation(*CI
, *Diags
);
1488 AST
->Diagnostics
= Diags
;
1489 AST
->FileSystemOpts
= CI
->getFileSystemOpts();
1490 AST
->Invocation
= std::move(CI
);
1491 AST
->FileMgr
= new FileManager(AST
->FileSystemOpts
, VFS
);
1492 AST
->UserFilesAreVolatile
= UserFilesAreVolatile
;
1493 AST
->SourceMgr
= new SourceManager(AST
->getDiagnostics(), *AST
->FileMgr
,
1494 UserFilesAreVolatile
);
1495 AST
->ModuleCache
= new InMemoryModuleCache
;
1500 ASTUnit
*ASTUnit::LoadFromCompilerInvocationAction(
1501 std::shared_ptr
<CompilerInvocation
> CI
,
1502 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1503 IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags
, FrontendAction
*Action
,
1504 ASTUnit
*Unit
, bool Persistent
, StringRef ResourceFilesPath
,
1505 bool OnlyLocalDecls
, CaptureDiagsKind CaptureDiagnostics
,
1506 unsigned PrecompilePreambleAfterNParses
, bool CacheCodeCompletionResults
,
1507 bool UserFilesAreVolatile
, std::unique_ptr
<ASTUnit
> *ErrAST
) {
1508 assert(CI
&& "A CompilerInvocation is required");
1510 std::unique_ptr
<ASTUnit
> OwnAST
;
1511 ASTUnit
*AST
= Unit
;
1513 // Create the AST unit.
1514 OwnAST
= create(CI
, Diags
, CaptureDiagnostics
, UserFilesAreVolatile
);
1520 if (!ResourceFilesPath
.empty()) {
1521 // Override the resources path.
1522 CI
->getHeaderSearchOpts().ResourceDir
= std::string(ResourceFilesPath
);
1524 AST
->OnlyLocalDecls
= OnlyLocalDecls
;
1525 AST
->CaptureDiagnostics
= CaptureDiagnostics
;
1526 if (PrecompilePreambleAfterNParses
> 0)
1527 AST
->PreambleRebuildCountdown
= PrecompilePreambleAfterNParses
;
1528 AST
->TUKind
= Action
? Action
->getTranslationUnitKind() : TU_Complete
;
1529 AST
->ShouldCacheCodeCompletionResults
= CacheCodeCompletionResults
;
1530 AST
->IncludeBriefCommentsInCodeCompletion
= false;
1532 // Recover resources if we crash before exiting this method.
1533 llvm::CrashRecoveryContextCleanupRegistrar
<ASTUnit
>
1534 ASTUnitCleanup(OwnAST
.get());
1535 llvm::CrashRecoveryContextCleanupRegistrar
<DiagnosticsEngine
,
1536 llvm::CrashRecoveryContextReleaseRefCleanup
<DiagnosticsEngine
>>
1537 DiagCleanup(Diags
.get());
1539 // We'll manage file buffers ourselves.
1540 CI
->getPreprocessorOpts().RetainRemappedFileBuffers
= true;
1541 CI
->getFrontendOpts().DisableFree
= false;
1542 ProcessWarningOptions(AST
->getDiagnostics(), CI
->getDiagnosticOpts());
1544 // Create the compiler instance to use for building the AST.
1545 std::unique_ptr
<CompilerInstance
> Clang(
1546 new CompilerInstance(std::move(PCHContainerOps
)));
1548 // Recover resources if we crash before exiting this method.
1549 llvm::CrashRecoveryContextCleanupRegistrar
<CompilerInstance
>
1550 CICleanup(Clang
.get());
1552 Clang
->setInvocation(std::move(CI
));
1553 AST
->OriginalSourceFile
=
1554 std::string(Clang
->getFrontendOpts().Inputs
[0].getFile());
1556 // Set up diagnostics, capturing any diagnostics that would
1557 // otherwise be dropped.
1558 Clang
->setDiagnostics(&AST
->getDiagnostics());
1560 // Create the target instance.
1561 if (!Clang
->createTarget())
1564 assert(Clang
->getFrontendOpts().Inputs
.size() == 1 &&
1565 "Invocation must have exactly one source file!");
1566 assert(Clang
->getFrontendOpts().Inputs
[0].getKind().getFormat() ==
1567 InputKind::Source
&&
1568 "FIXME: AST inputs not yet supported here!");
1569 assert(Clang
->getFrontendOpts().Inputs
[0].getKind().getLanguage() !=
1570 Language::LLVM_IR
&&
1571 "IR inputs not support here!");
1573 // Configure the various subsystems.
1574 AST
->TheSema
.reset();
1577 AST
->Reader
= nullptr;
1579 // Create a file manager object to provide access to and cache the filesystem.
1580 Clang
->setFileManager(&AST
->getFileManager());
1582 // Create the source manager.
1583 Clang
->setSourceManager(&AST
->getSourceManager());
1585 FrontendAction
*Act
= Action
;
1587 std::unique_ptr
<TopLevelDeclTrackerAction
> TrackerAct
;
1589 TrackerAct
.reset(new TopLevelDeclTrackerAction(*AST
));
1590 Act
= TrackerAct
.get();
1593 // Recover resources if we crash before exiting this method.
1594 llvm::CrashRecoveryContextCleanupRegistrar
<TopLevelDeclTrackerAction
>
1595 ActCleanup(TrackerAct
.get());
1597 if (!Act
->BeginSourceFile(*Clang
.get(), Clang
->getFrontendOpts().Inputs
[0])) {
1598 AST
->transferASTDataFromCompilerInstance(*Clang
);
1599 if (OwnAST
&& ErrAST
)
1600 ErrAST
->swap(OwnAST
);
1605 if (Persistent
&& !TrackerAct
) {
1606 Clang
->getPreprocessor().addPPCallbacks(
1607 std::make_unique
<MacroDefinitionTrackerPPCallbacks
>(
1608 AST
->getCurrentTopLevelHashValue()));
1609 std::vector
<std::unique_ptr
<ASTConsumer
>> Consumers
;
1610 if (Clang
->hasASTConsumer())
1611 Consumers
.push_back(Clang
->takeASTConsumer());
1612 Consumers
.push_back(std::make_unique
<TopLevelDeclTrackerConsumer
>(
1613 *AST
, AST
->getCurrentTopLevelHashValue()));
1614 Clang
->setASTConsumer(
1615 std::make_unique
<MultiplexConsumer
>(std::move(Consumers
)));
1617 if (llvm::Error Err
= Act
->Execute()) {
1618 consumeError(std::move(Err
)); // FIXME this drops errors on the floor.
1619 AST
->transferASTDataFromCompilerInstance(*Clang
);
1620 if (OwnAST
&& ErrAST
)
1621 ErrAST
->swap(OwnAST
);
1626 // Steal the created target, context, and preprocessor.
1627 AST
->transferASTDataFromCompilerInstance(*Clang
);
1629 Act
->EndSourceFile();
1632 return OwnAST
.release();
1637 bool ASTUnit::LoadFromCompilerInvocation(
1638 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1639 unsigned PrecompilePreambleAfterNParses
,
1640 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
) {
1644 assert(VFS
&& "VFS is null");
1646 // We'll manage file buffers ourselves.
1647 Invocation
->getPreprocessorOpts().RetainRemappedFileBuffers
= true;
1648 Invocation
->getFrontendOpts().DisableFree
= false;
1649 getDiagnostics().Reset();
1650 ProcessWarningOptions(getDiagnostics(), Invocation
->getDiagnosticOpts());
1652 std::unique_ptr
<llvm::MemoryBuffer
> OverrideMainBuffer
;
1653 if (PrecompilePreambleAfterNParses
> 0) {
1654 PreambleRebuildCountdown
= PrecompilePreambleAfterNParses
;
1655 OverrideMainBuffer
=
1656 getMainBufferWithPrecompiledPreamble(PCHContainerOps
, *Invocation
, VFS
);
1657 getDiagnostics().Reset();
1658 ProcessWarningOptions(getDiagnostics(), Invocation
->getDiagnosticOpts());
1661 SimpleTimer
ParsingTimer(WantTiming
);
1662 ParsingTimer
.setOutput("Parsing " + getMainFileName());
1664 // Recover resources if we crash before exiting this method.
1665 llvm::CrashRecoveryContextCleanupRegistrar
<llvm::MemoryBuffer
>
1666 MemBufferCleanup(OverrideMainBuffer
.get());
1668 return Parse(std::move(PCHContainerOps
), std::move(OverrideMainBuffer
), VFS
);
1671 std::unique_ptr
<ASTUnit
> ASTUnit::LoadFromCompilerInvocation(
1672 std::shared_ptr
<CompilerInvocation
> CI
,
1673 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1674 IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags
, FileManager
*FileMgr
,
1675 bool OnlyLocalDecls
, CaptureDiagsKind CaptureDiagnostics
,
1676 unsigned PrecompilePreambleAfterNParses
, TranslationUnitKind TUKind
,
1677 bool CacheCodeCompletionResults
, bool IncludeBriefCommentsInCodeCompletion
,
1678 bool UserFilesAreVolatile
) {
1679 // Create the AST unit.
1680 std::unique_ptr
<ASTUnit
> AST(new ASTUnit(false));
1681 ConfigureDiags(Diags
, *AST
, CaptureDiagnostics
);
1682 AST
->Diagnostics
= Diags
;
1683 AST
->OnlyLocalDecls
= OnlyLocalDecls
;
1684 AST
->CaptureDiagnostics
= CaptureDiagnostics
;
1685 AST
->TUKind
= TUKind
;
1686 AST
->ShouldCacheCodeCompletionResults
= CacheCodeCompletionResults
;
1687 AST
->IncludeBriefCommentsInCodeCompletion
1688 = IncludeBriefCommentsInCodeCompletion
;
1689 AST
->Invocation
= std::move(CI
);
1690 AST
->FileSystemOpts
= FileMgr
->getFileSystemOpts();
1691 AST
->FileMgr
= FileMgr
;
1692 AST
->UserFilesAreVolatile
= UserFilesAreVolatile
;
1694 // Recover resources if we crash before exiting this method.
1695 llvm::CrashRecoveryContextCleanupRegistrar
<ASTUnit
>
1696 ASTUnitCleanup(AST
.get());
1697 llvm::CrashRecoveryContextCleanupRegistrar
<DiagnosticsEngine
,
1698 llvm::CrashRecoveryContextReleaseRefCleanup
<DiagnosticsEngine
>>
1699 DiagCleanup(Diags
.get());
1701 if (AST
->LoadFromCompilerInvocation(std::move(PCHContainerOps
),
1702 PrecompilePreambleAfterNParses
,
1703 &AST
->FileMgr
->getVirtualFileSystem()))
1708 ASTUnit
*ASTUnit::LoadFromCommandLine(
1709 const char **ArgBegin
, const char **ArgEnd
,
1710 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1711 IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags
, StringRef ResourceFilesPath
,
1712 bool OnlyLocalDecls
, CaptureDiagsKind CaptureDiagnostics
,
1713 ArrayRef
<RemappedFile
> RemappedFiles
, bool RemappedFilesKeepOriginalName
,
1714 unsigned PrecompilePreambleAfterNParses
, TranslationUnitKind TUKind
,
1715 bool CacheCodeCompletionResults
, bool IncludeBriefCommentsInCodeCompletion
,
1716 bool AllowPCHWithCompilerErrors
, SkipFunctionBodiesScope SkipFunctionBodies
,
1717 bool SingleFileParse
, bool UserFilesAreVolatile
, bool ForSerialization
,
1718 bool RetainExcludedConditionalBlocks
,
1719 llvm::Optional
<StringRef
> ModuleFormat
, std::unique_ptr
<ASTUnit
> *ErrAST
,
1720 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
) {
1721 assert(Diags
.get() && "no DiagnosticsEngine was provided");
1723 SmallVector
<StoredDiagnostic
, 4> StoredDiagnostics
;
1725 std::shared_ptr
<CompilerInvocation
> CI
;
1728 CaptureDroppedDiagnostics
Capture(CaptureDiagnostics
, *Diags
,
1729 &StoredDiagnostics
, nullptr);
1731 CreateInvocationOptions CIOpts
;
1733 CIOpts
.Diags
= Diags
;
1734 CIOpts
.ProbePrecompiled
= true; // FIXME: historical default. Needed?
1735 CI
= createInvocation(llvm::makeArrayRef(ArgBegin
, ArgEnd
),
1741 // Override any files that need remapping
1742 for (const auto &RemappedFile
: RemappedFiles
) {
1743 CI
->getPreprocessorOpts().addRemappedFile(RemappedFile
.first
,
1744 RemappedFile
.second
);
1746 PreprocessorOptions
&PPOpts
= CI
->getPreprocessorOpts();
1747 PPOpts
.RemappedFilesKeepOriginalName
= RemappedFilesKeepOriginalName
;
1748 PPOpts
.AllowPCHWithCompilerErrors
= AllowPCHWithCompilerErrors
;
1749 PPOpts
.SingleFileParseMode
= SingleFileParse
;
1750 PPOpts
.RetainExcludedConditionalBlocks
= RetainExcludedConditionalBlocks
;
1752 // Override the resources path.
1753 CI
->getHeaderSearchOpts().ResourceDir
= std::string(ResourceFilesPath
);
1755 CI
->getFrontendOpts().SkipFunctionBodies
=
1756 SkipFunctionBodies
== SkipFunctionBodiesScope::PreambleAndMainFile
;
1759 CI
->getHeaderSearchOpts().ModuleFormat
= std::string(*ModuleFormat
);
1761 // Create the AST unit.
1762 std::unique_ptr
<ASTUnit
> AST
;
1763 AST
.reset(new ASTUnit(false));
1764 AST
->NumStoredDiagnosticsFromDriver
= StoredDiagnostics
.size();
1765 AST
->StoredDiagnostics
.swap(StoredDiagnostics
);
1766 ConfigureDiags(Diags
, *AST
, CaptureDiagnostics
);
1767 AST
->Diagnostics
= Diags
;
1768 AST
->FileSystemOpts
= CI
->getFileSystemOpts();
1770 VFS
= llvm::vfs::getRealFileSystem();
1771 VFS
= createVFSFromCompilerInvocation(*CI
, *Diags
, VFS
);
1772 AST
->FileMgr
= new FileManager(AST
->FileSystemOpts
, VFS
);
1773 AST
->ModuleCache
= new InMemoryModuleCache
;
1774 AST
->OnlyLocalDecls
= OnlyLocalDecls
;
1775 AST
->CaptureDiagnostics
= CaptureDiagnostics
;
1776 AST
->TUKind
= TUKind
;
1777 AST
->ShouldCacheCodeCompletionResults
= CacheCodeCompletionResults
;
1778 AST
->IncludeBriefCommentsInCodeCompletion
1779 = IncludeBriefCommentsInCodeCompletion
;
1780 AST
->UserFilesAreVolatile
= UserFilesAreVolatile
;
1781 AST
->Invocation
= CI
;
1782 AST
->SkipFunctionBodies
= SkipFunctionBodies
;
1783 if (ForSerialization
)
1784 AST
->WriterData
.reset(new ASTWriterData(*AST
->ModuleCache
));
1785 // Zero out now to ease cleanup during crash recovery.
1789 // Recover resources if we crash before exiting this method.
1790 llvm::CrashRecoveryContextCleanupRegistrar
<ASTUnit
>
1791 ASTUnitCleanup(AST
.get());
1793 if (AST
->LoadFromCompilerInvocation(std::move(PCHContainerOps
),
1794 PrecompilePreambleAfterNParses
,
1796 // Some error occurred, if caller wants to examine diagnostics, pass it the
1799 AST
->StoredDiagnostics
.swap(AST
->FailedParseDiagnostics
);
1805 return AST
.release();
1808 bool ASTUnit::Reparse(std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
1809 ArrayRef
<RemappedFile
> RemappedFiles
,
1810 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
) {
1815 assert(FileMgr
&& "FileMgr is null on Reparse call");
1816 VFS
= &FileMgr
->getVirtualFileSystem();
1819 clearFileLevelDecls();
1821 SimpleTimer
ParsingTimer(WantTiming
);
1822 ParsingTimer
.setOutput("Reparsing " + getMainFileName());
1825 PreprocessorOptions
&PPOpts
= Invocation
->getPreprocessorOpts();
1826 for (const auto &RB
: PPOpts
.RemappedFileBuffers
)
1829 Invocation
->getPreprocessorOpts().clearRemappedFiles();
1830 for (const auto &RemappedFile
: RemappedFiles
) {
1831 Invocation
->getPreprocessorOpts().addRemappedFile(RemappedFile
.first
,
1832 RemappedFile
.second
);
1835 // If we have a preamble file lying around, or if we might try to
1836 // build a precompiled preamble, do so now.
1837 std::unique_ptr
<llvm::MemoryBuffer
> OverrideMainBuffer
;
1838 if (Preamble
|| PreambleRebuildCountdown
> 0)
1839 OverrideMainBuffer
=
1840 getMainBufferWithPrecompiledPreamble(PCHContainerOps
, *Invocation
, VFS
);
1842 // Clear out the diagnostics state.
1844 getDiagnostics().Reset();
1845 ProcessWarningOptions(getDiagnostics(), Invocation
->getDiagnosticOpts());
1846 if (OverrideMainBuffer
)
1847 getDiagnostics().setNumWarnings(NumWarningsInPreamble
);
1849 // Parse the sources
1851 Parse(std::move(PCHContainerOps
), std::move(OverrideMainBuffer
), VFS
);
1853 // If we're caching global code-completion results, and the top-level
1854 // declarations have changed, clear out the code-completion cache.
1855 if (!Result
&& ShouldCacheCodeCompletionResults
&&
1856 CurrentTopLevelHashValue
!= CompletionCacheTopLevelHashValue
)
1857 CacheCodeCompletionResults();
1859 // We now need to clear out the completion info related to this translation
1860 // unit; it'll be recreated if necessary.
1866 void ASTUnit::ResetForParse() {
1867 SavedMainFileBuffer
.reset();
1875 TopLevelDecls
.clear();
1876 clearFileLevelDecls();
1879 //----------------------------------------------------------------------------//
1881 //----------------------------------------------------------------------------//
1885 /// Code completion consumer that combines the cached code-completion
1886 /// results from an ASTUnit with the code-completion results provided to it,
1887 /// then passes the result on to
1888 class AugmentedCodeCompleteConsumer
: public CodeCompleteConsumer
{
1889 uint64_t NormalContexts
;
1891 CodeCompleteConsumer
&Next
;
1894 AugmentedCodeCompleteConsumer(ASTUnit
&AST
, CodeCompleteConsumer
&Next
,
1895 const CodeCompleteOptions
&CodeCompleteOpts
)
1896 : CodeCompleteConsumer(CodeCompleteOpts
), AST(AST
), Next(Next
) {
1897 // Compute the set of contexts in which we will look when we don't have
1898 // any information about the specific context.
1900 = (1LL << CodeCompletionContext::CCC_TopLevel
)
1901 | (1LL << CodeCompletionContext::CCC_ObjCInterface
)
1902 | (1LL << CodeCompletionContext::CCC_ObjCImplementation
)
1903 | (1LL << CodeCompletionContext::CCC_ObjCIvarList
)
1904 | (1LL << CodeCompletionContext::CCC_Statement
)
1905 | (1LL << CodeCompletionContext::CCC_Expression
)
1906 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver
)
1907 | (1LL << CodeCompletionContext::CCC_DotMemberAccess
)
1908 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess
)
1909 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess
)
1910 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName
)
1911 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression
)
1912 | (1LL << CodeCompletionContext::CCC_Recovery
);
1914 if (AST
.getASTContext().getLangOpts().CPlusPlus
)
1915 NormalContexts
|= (1LL << CodeCompletionContext::CCC_EnumTag
)
1916 | (1LL << CodeCompletionContext::CCC_UnionTag
)
1917 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag
);
1920 void ProcessCodeCompleteResults(Sema
&S
, CodeCompletionContext Context
,
1921 CodeCompletionResult
*Results
,
1922 unsigned NumResults
) override
;
1924 void ProcessOverloadCandidates(Sema
&S
, unsigned CurrentArg
,
1925 OverloadCandidate
*Candidates
,
1926 unsigned NumCandidates
,
1927 SourceLocation OpenParLoc
,
1928 bool Braced
) override
{
1929 Next
.ProcessOverloadCandidates(S
, CurrentArg
, Candidates
, NumCandidates
,
1930 OpenParLoc
, Braced
);
1933 CodeCompletionAllocator
&getAllocator() override
{
1934 return Next
.getAllocator();
1937 CodeCompletionTUInfo
&getCodeCompletionTUInfo() override
{
1938 return Next
.getCodeCompletionTUInfo();
1944 /// Helper function that computes which global names are hidden by the
1945 /// local code-completion results.
1946 static void CalculateHiddenNames(const CodeCompletionContext
&Context
,
1947 CodeCompletionResult
*Results
,
1948 unsigned NumResults
,
1950 llvm::StringSet
<llvm::BumpPtrAllocator
> &HiddenNames
){
1951 bool OnlyTagNames
= false;
1952 switch (Context
.getKind()) {
1953 case CodeCompletionContext::CCC_Recovery
:
1954 case CodeCompletionContext::CCC_TopLevel
:
1955 case CodeCompletionContext::CCC_ObjCInterface
:
1956 case CodeCompletionContext::CCC_ObjCImplementation
:
1957 case CodeCompletionContext::CCC_ObjCIvarList
:
1958 case CodeCompletionContext::CCC_ClassStructUnion
:
1959 case CodeCompletionContext::CCC_Statement
:
1960 case CodeCompletionContext::CCC_Expression
:
1961 case CodeCompletionContext::CCC_ObjCMessageReceiver
:
1962 case CodeCompletionContext::CCC_DotMemberAccess
:
1963 case CodeCompletionContext::CCC_ArrowMemberAccess
:
1964 case CodeCompletionContext::CCC_ObjCPropertyAccess
:
1965 case CodeCompletionContext::CCC_Namespace
:
1966 case CodeCompletionContext::CCC_Type
:
1967 case CodeCompletionContext::CCC_Symbol
:
1968 case CodeCompletionContext::CCC_SymbolOrNewName
:
1969 case CodeCompletionContext::CCC_ParenthesizedExpression
:
1970 case CodeCompletionContext::CCC_ObjCInterfaceName
:
1973 case CodeCompletionContext::CCC_EnumTag
:
1974 case CodeCompletionContext::CCC_UnionTag
:
1975 case CodeCompletionContext::CCC_ClassOrStructTag
:
1976 OnlyTagNames
= true;
1979 case CodeCompletionContext::CCC_ObjCProtocolName
:
1980 case CodeCompletionContext::CCC_MacroName
:
1981 case CodeCompletionContext::CCC_MacroNameUse
:
1982 case CodeCompletionContext::CCC_PreprocessorExpression
:
1983 case CodeCompletionContext::CCC_PreprocessorDirective
:
1984 case CodeCompletionContext::CCC_NaturalLanguage
:
1985 case CodeCompletionContext::CCC_SelectorName
:
1986 case CodeCompletionContext::CCC_TypeQualifiers
:
1987 case CodeCompletionContext::CCC_Other
:
1988 case CodeCompletionContext::CCC_OtherWithMacros
:
1989 case CodeCompletionContext::CCC_ObjCInstanceMessage
:
1990 case CodeCompletionContext::CCC_ObjCClassMessage
:
1991 case CodeCompletionContext::CCC_ObjCCategoryName
:
1992 case CodeCompletionContext::CCC_IncludedFile
:
1993 case CodeCompletionContext::CCC_Attribute
:
1994 case CodeCompletionContext::CCC_NewName
:
1995 // We're looking for nothing, or we're looking for names that cannot
2000 using Result
= CodeCompletionResult
;
2001 for (unsigned I
= 0; I
!= NumResults
; ++I
) {
2002 if (Results
[I
].Kind
!= Result::RK_Declaration
)
2006 = Results
[I
].Declaration
->getUnderlyingDecl()->getIdentifierNamespace();
2008 bool Hiding
= false;
2010 Hiding
= (IDNS
& Decl::IDNS_Tag
);
2012 unsigned HiddenIDNS
= (Decl::IDNS_Type
| Decl::IDNS_Member
|
2013 Decl::IDNS_Namespace
| Decl::IDNS_Ordinary
|
2014 Decl::IDNS_NonMemberOperator
);
2015 if (Ctx
.getLangOpts().CPlusPlus
)
2016 HiddenIDNS
|= Decl::IDNS_Tag
;
2017 Hiding
= (IDNS
& HiddenIDNS
);
2023 DeclarationName Name
= Results
[I
].Declaration
->getDeclName();
2024 if (IdentifierInfo
*Identifier
= Name
.getAsIdentifierInfo())
2025 HiddenNames
.insert(Identifier
->getName());
2027 HiddenNames
.insert(Name
.getAsString());
2031 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema
&S
,
2032 CodeCompletionContext Context
,
2033 CodeCompletionResult
*Results
,
2034 unsigned NumResults
) {
2035 // Merge the results we were given with the results we cached.
2036 bool AddedResult
= false;
2037 uint64_t InContexts
=
2038 Context
.getKind() == CodeCompletionContext::CCC_Recovery
2039 ? NormalContexts
: (1LL << Context
.getKind());
2040 // Contains the set of names that are hidden by "local" completion results.
2041 llvm::StringSet
<llvm::BumpPtrAllocator
> HiddenNames
;
2042 using Result
= CodeCompletionResult
;
2043 SmallVector
<Result
, 8> AllResults
;
2044 for (ASTUnit::cached_completion_iterator
2045 C
= AST
.cached_completion_begin(),
2046 CEnd
= AST
.cached_completion_end();
2048 // If the context we are in matches any of the contexts we are
2049 // interested in, we'll add this result.
2050 if ((C
->ShowInContexts
& InContexts
) == 0)
2053 // If we haven't added any results previously, do so now.
2055 CalculateHiddenNames(Context
, Results
, NumResults
, S
.Context
,
2057 AllResults
.insert(AllResults
.end(), Results
, Results
+ NumResults
);
2061 // Determine whether this global completion result is hidden by a local
2062 // completion result. If so, skip it.
2063 if (C
->Kind
!= CXCursor_MacroDefinition
&&
2064 HiddenNames
.count(C
->Completion
->getTypedText()))
2067 // Adjust priority based on similar type classes.
2068 unsigned Priority
= C
->Priority
;
2069 CodeCompletionString
*Completion
= C
->Completion
;
2070 if (!Context
.getPreferredType().isNull()) {
2071 if (C
->Kind
== CXCursor_MacroDefinition
) {
2072 Priority
= getMacroUsagePriority(C
->Completion
->getTypedText(),
2074 Context
.getPreferredType()->isAnyPointerType());
2075 } else if (C
->Type
) {
2076 CanQualType Expected
2077 = S
.Context
.getCanonicalType(
2078 Context
.getPreferredType().getUnqualifiedType());
2079 SimplifiedTypeClass ExpectedSTC
= getSimplifiedTypeClass(Expected
);
2080 if (ExpectedSTC
== C
->TypeClass
) {
2081 // We know this type is similar; check for an exact match.
2082 llvm::StringMap
<unsigned> &CachedCompletionTypes
2083 = AST
.getCachedCompletionTypes();
2084 llvm::StringMap
<unsigned>::iterator Pos
2085 = CachedCompletionTypes
.find(QualType(Expected
).getAsString());
2086 if (Pos
!= CachedCompletionTypes
.end() && Pos
->second
== C
->Type
)
2087 Priority
/= CCF_ExactTypeMatch
;
2089 Priority
/= CCF_SimilarTypeMatch
;
2094 // Adjust the completion string, if required.
2095 if (C
->Kind
== CXCursor_MacroDefinition
&&
2096 Context
.getKind() == CodeCompletionContext::CCC_MacroNameUse
) {
2097 // Create a new code-completion string that just contains the
2098 // macro name, without its arguments.
2099 CodeCompletionBuilder
Builder(getAllocator(), getCodeCompletionTUInfo(),
2100 CCP_CodePattern
, C
->Availability
);
2101 Builder
.AddTypedTextChunk(C
->Completion
->getTypedText());
2102 Priority
= CCP_CodePattern
;
2103 Completion
= Builder
.TakeString();
2106 AllResults
.push_back(Result(Completion
, Priority
, C
->Kind
,
2110 // If we did not add any cached completion results, just forward the
2111 // results we were given to the next consumer.
2113 Next
.ProcessCodeCompleteResults(S
, Context
, Results
, NumResults
);
2117 Next
.ProcessCodeCompleteResults(S
, Context
, AllResults
.data(),
2121 void ASTUnit::CodeComplete(
2122 StringRef File
, unsigned Line
, unsigned Column
,
2123 ArrayRef
<RemappedFile
> RemappedFiles
, bool IncludeMacros
,
2124 bool IncludeCodePatterns
, bool IncludeBriefComments
,
2125 CodeCompleteConsumer
&Consumer
,
2126 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
2127 DiagnosticsEngine
&Diag
, LangOptions
&LangOpts
, SourceManager
&SourceMgr
,
2128 FileManager
&FileMgr
, SmallVectorImpl
<StoredDiagnostic
> &StoredDiagnostics
,
2129 SmallVectorImpl
<const llvm::MemoryBuffer
*> &OwnedBuffers
) {
2133 SimpleTimer
CompletionTimer(WantTiming
);
2134 CompletionTimer
.setOutput("Code completion @ " + File
+ ":" +
2135 Twine(Line
) + ":" + Twine(Column
));
2137 auto CCInvocation
= std::make_shared
<CompilerInvocation
>(*Invocation
);
2139 FrontendOptions
&FrontendOpts
= CCInvocation
->getFrontendOpts();
2140 CodeCompleteOptions
&CodeCompleteOpts
= FrontendOpts
.CodeCompleteOpts
;
2141 PreprocessorOptions
&PreprocessorOpts
= CCInvocation
->getPreprocessorOpts();
2143 CodeCompleteOpts
.IncludeMacros
= IncludeMacros
&&
2144 CachedCompletionResults
.empty();
2145 CodeCompleteOpts
.IncludeCodePatterns
= IncludeCodePatterns
;
2146 CodeCompleteOpts
.IncludeGlobals
= CachedCompletionResults
.empty();
2147 CodeCompleteOpts
.IncludeBriefComments
= IncludeBriefComments
;
2148 CodeCompleteOpts
.LoadExternal
= Consumer
.loadExternal();
2149 CodeCompleteOpts
.IncludeFixIts
= Consumer
.includeFixIts();
2151 assert(IncludeBriefComments
== this->IncludeBriefCommentsInCodeCompletion
);
2153 FrontendOpts
.CodeCompletionAt
.FileName
= std::string(File
);
2154 FrontendOpts
.CodeCompletionAt
.Line
= Line
;
2155 FrontendOpts
.CodeCompletionAt
.Column
= Column
;
2157 // Set the language options appropriately.
2158 LangOpts
= *CCInvocation
->getLangOpts();
2160 // Spell-checking and warnings are wasteful during code-completion.
2161 LangOpts
.SpellChecking
= false;
2162 CCInvocation
->getDiagnosticOpts().IgnoreWarnings
= true;
2164 std::unique_ptr
<CompilerInstance
> Clang(
2165 new CompilerInstance(PCHContainerOps
));
2167 // Recover resources if we crash before exiting this method.
2168 llvm::CrashRecoveryContextCleanupRegistrar
<CompilerInstance
>
2169 CICleanup(Clang
.get());
2171 auto &Inv
= *CCInvocation
;
2172 Clang
->setInvocation(std::move(CCInvocation
));
2173 OriginalSourceFile
=
2174 std::string(Clang
->getFrontendOpts().Inputs
[0].getFile());
2176 // Set up diagnostics, capturing any diagnostics produced.
2177 Clang
->setDiagnostics(&Diag
);
2178 CaptureDroppedDiagnostics
Capture(CaptureDiagsKind::All
,
2179 Clang
->getDiagnostics(),
2180 &StoredDiagnostics
, nullptr);
2181 ProcessWarningOptions(Diag
, Inv
.getDiagnosticOpts());
2183 // Create the target instance.
2184 if (!Clang
->createTarget()) {
2185 Clang
->setInvocation(nullptr);
2189 assert(Clang
->getFrontendOpts().Inputs
.size() == 1 &&
2190 "Invocation must have exactly one source file!");
2191 assert(Clang
->getFrontendOpts().Inputs
[0].getKind().getFormat() ==
2192 InputKind::Source
&&
2193 "FIXME: AST inputs not yet supported here!");
2194 assert(Clang
->getFrontendOpts().Inputs
[0].getKind().getLanguage() !=
2195 Language::LLVM_IR
&&
2196 "IR inputs not support here!");
2198 // Use the source and file managers that we were given.
2199 Clang
->setFileManager(&FileMgr
);
2200 Clang
->setSourceManager(&SourceMgr
);
2203 PreprocessorOpts
.clearRemappedFiles();
2204 PreprocessorOpts
.RetainRemappedFileBuffers
= true;
2205 for (const auto &RemappedFile
: RemappedFiles
) {
2206 PreprocessorOpts
.addRemappedFile(RemappedFile
.first
, RemappedFile
.second
);
2207 OwnedBuffers
.push_back(RemappedFile
.second
);
2210 // Use the code completion consumer we were given, but adding any cached
2211 // code-completion results.
2212 AugmentedCodeCompleteConsumer
*AugmentedConsumer
2213 = new AugmentedCodeCompleteConsumer(*this, Consumer
, CodeCompleteOpts
);
2214 Clang
->setCodeCompletionConsumer(AugmentedConsumer
);
2217 [&FileMgr
](StringRef Filename
) -> Optional
<llvm::sys::fs::UniqueID
> {
2218 if (auto Status
= FileMgr
.getVirtualFileSystem().status(Filename
))
2219 return Status
->getUniqueID();
2223 auto hasSameUniqueID
= [getUniqueID
](StringRef LHS
, StringRef RHS
) {
2226 if (auto LHSID
= getUniqueID(LHS
))
2227 if (auto RHSID
= getUniqueID(RHS
))
2228 return *LHSID
== *RHSID
;
2232 // If we have a precompiled preamble, try to use it. We only allow
2233 // the use of the precompiled preamble if we're if the completion
2234 // point is within the main file, after the end of the precompiled
2236 std::unique_ptr
<llvm::MemoryBuffer
> OverrideMainBuffer
;
2237 if (Preamble
&& Line
> 1 && hasSameUniqueID(File
, OriginalSourceFile
)) {
2238 OverrideMainBuffer
= getMainBufferWithPrecompiledPreamble(
2239 PCHContainerOps
, Inv
, &FileMgr
.getVirtualFileSystem(), false, Line
- 1);
2242 // If the main file has been overridden due to the use of a preamble,
2243 // make that override happen and introduce the preamble.
2244 if (OverrideMainBuffer
) {
2246 "No preamble was built, but OverrideMainBuffer is not null");
2248 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
=
2249 &FileMgr
.getVirtualFileSystem();
2250 Preamble
->AddImplicitPreamble(Clang
->getInvocation(), VFS
,
2251 OverrideMainBuffer
.get());
2252 // FIXME: there is no way to update VFS if it was changed by
2253 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2254 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2255 // PCH files are always readable.
2256 OwnedBuffers
.push_back(OverrideMainBuffer
.release());
2258 PreprocessorOpts
.PrecompiledPreambleBytes
.first
= 0;
2259 PreprocessorOpts
.PrecompiledPreambleBytes
.second
= false;
2262 // Disable the preprocessing record if modules are not enabled.
2263 if (!Clang
->getLangOpts().Modules
)
2264 PreprocessorOpts
.DetailedRecord
= false;
2266 std::unique_ptr
<SyntaxOnlyAction
> Act
;
2267 Act
.reset(new SyntaxOnlyAction
);
2268 if (Act
->BeginSourceFile(*Clang
.get(), Clang
->getFrontendOpts().Inputs
[0])) {
2269 if (llvm::Error Err
= Act
->Execute()) {
2270 consumeError(std::move(Err
)); // FIXME this drops errors on the floor.
2272 Act
->EndSourceFile();
2276 bool ASTUnit::Save(StringRef File
) {
2277 if (HadModuleLoaderFatalFailure
)
2280 // Write to a temporary file and later rename it to the actual file, to avoid
2281 // possible race conditions.
2282 SmallString
<128> TempPath
;
2284 TempPath
+= "-%%%%%%%%";
2285 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2286 // unconditionally create a stat cache when we parse the file?
2288 if (llvm::Error Err
= llvm::writeFileAtomically(
2289 TempPath
, File
, [this](llvm::raw_ostream
&Out
) {
2290 return serialize(Out
) ? llvm::make_error
<llvm::StringError
>(
2291 "ASTUnit serialization failed",
2292 llvm::inconvertibleErrorCode())
2293 : llvm::Error::success();
2295 consumeError(std::move(Err
));
2301 static bool serializeUnit(ASTWriter
&Writer
,
2302 SmallVectorImpl
<char> &Buffer
,
2306 Writer
.WriteAST(S
, std::string(), nullptr, "", hasErrors
);
2308 // Write the generated bitstream to "Out".
2309 if (!Buffer
.empty())
2310 OS
.write(Buffer
.data(), Buffer
.size());
2315 bool ASTUnit::serialize(raw_ostream
&OS
) {
2316 // For serialization we are lenient if the errors were only warn-as-error kind.
2317 bool hasErrors
= getDiagnostics().hasUncompilableErrorOccurred();
2320 return serializeUnit(WriterData
->Writer
, WriterData
->Buffer
,
2321 getSema(), hasErrors
, OS
);
2323 SmallString
<128> Buffer
;
2324 llvm::BitstreamWriter
Stream(Buffer
);
2325 InMemoryModuleCache ModuleCache
;
2326 ASTWriter
Writer(Stream
, Buffer
, ModuleCache
, {});
2327 return serializeUnit(Writer
, Buffer
, getSema(), hasErrors
, OS
);
2330 using SLocRemap
= ContinuousRangeMap
<unsigned, int, 2>;
2332 void ASTUnit::TranslateStoredDiagnostics(
2333 FileManager
&FileMgr
,
2334 SourceManager
&SrcMgr
,
2335 const SmallVectorImpl
<StandaloneDiagnostic
> &Diags
,
2336 SmallVectorImpl
<StoredDiagnostic
> &Out
) {
2337 // Map the standalone diagnostic into the new source manager. We also need to
2338 // remap all the locations to the new view. This includes the diag location,
2339 // any associated source ranges, and the source ranges of associated fix-its.
2340 // FIXME: There should be a cleaner way to do this.
2341 SmallVector
<StoredDiagnostic
, 4> Result
;
2342 Result
.reserve(Diags
.size());
2344 for (const auto &SD
: Diags
) {
2345 // Rebuild the StoredDiagnostic.
2346 if (SD
.Filename
.empty())
2348 auto FE
= FileMgr
.getFile(SD
.Filename
);
2351 SourceLocation FileLoc
;
2352 auto ItFileID
= PreambleSrcLocCache
.find(SD
.Filename
);
2353 if (ItFileID
== PreambleSrcLocCache
.end()) {
2354 FileID FID
= SrcMgr
.translateFile(*FE
);
2355 FileLoc
= SrcMgr
.getLocForStartOfFile(FID
);
2356 PreambleSrcLocCache
[SD
.Filename
] = FileLoc
;
2358 FileLoc
= ItFileID
->getValue();
2361 if (FileLoc
.isInvalid())
2363 SourceLocation L
= FileLoc
.getLocWithOffset(SD
.LocOffset
);
2364 FullSourceLoc
Loc(L
, SrcMgr
);
2366 SmallVector
<CharSourceRange
, 4> Ranges
;
2367 Ranges
.reserve(SD
.Ranges
.size());
2368 for (const auto &Range
: SD
.Ranges
) {
2369 SourceLocation BL
= FileLoc
.getLocWithOffset(Range
.first
);
2370 SourceLocation EL
= FileLoc
.getLocWithOffset(Range
.second
);
2371 Ranges
.push_back(CharSourceRange::getCharRange(BL
, EL
));
2374 SmallVector
<FixItHint
, 2> FixIts
;
2375 FixIts
.reserve(SD
.FixIts
.size());
2376 for (const auto &FixIt
: SD
.FixIts
) {
2377 FixIts
.push_back(FixItHint());
2378 FixItHint
&FH
= FixIts
.back();
2379 FH
.CodeToInsert
= FixIt
.CodeToInsert
;
2380 SourceLocation BL
= FileLoc
.getLocWithOffset(FixIt
.RemoveRange
.first
);
2381 SourceLocation EL
= FileLoc
.getLocWithOffset(FixIt
.RemoveRange
.second
);
2382 FH
.RemoveRange
= CharSourceRange::getCharRange(BL
, EL
);
2385 Result
.push_back(StoredDiagnostic(SD
.Level
, SD
.ID
,
2386 SD
.Message
, Loc
, Ranges
, FixIts
));
2391 void ASTUnit::addFileLevelDecl(Decl
*D
) {
2394 // We only care about local declarations.
2395 if (D
->isFromASTFile())
2398 SourceManager
&SM
= *SourceMgr
;
2399 SourceLocation Loc
= D
->getLocation();
2400 if (Loc
.isInvalid() || !SM
.isLocalSourceLocation(Loc
))
2403 // We only keep track of the file-level declarations of each file.
2404 if (!D
->getLexicalDeclContext()->isFileContext())
2407 SourceLocation FileLoc
= SM
.getFileLoc(Loc
);
2408 assert(SM
.isLocalSourceLocation(FileLoc
));
2411 std::tie(FID
, Offset
) = SM
.getDecomposedLoc(FileLoc
);
2412 if (FID
.isInvalid())
2415 std::unique_ptr
<LocDeclsTy
> &Decls
= FileDecls
[FID
];
2417 Decls
= std::make_unique
<LocDeclsTy
>();
2419 std::pair
<unsigned, Decl
*> LocDecl(Offset
, D
);
2421 if (Decls
->empty() || Decls
->back().first
<= Offset
) {
2422 Decls
->push_back(LocDecl
);
2426 LocDeclsTy::iterator I
=
2427 llvm::upper_bound(*Decls
, LocDecl
, llvm::less_first());
2429 Decls
->insert(I
, LocDecl
);
2432 void ASTUnit::findFileRegionDecls(FileID File
, unsigned Offset
, unsigned Length
,
2433 SmallVectorImpl
<Decl
*> &Decls
) {
2434 if (File
.isInvalid())
2437 if (SourceMgr
->isLoadedFileID(File
)) {
2438 assert(Ctx
->getExternalSource() && "No external source!");
2439 return Ctx
->getExternalSource()->FindFileRegionDecls(File
, Offset
, Length
,
2443 FileDeclsTy::iterator I
= FileDecls
.find(File
);
2444 if (I
== FileDecls
.end())
2447 LocDeclsTy
&LocDecls
= *I
->second
;
2448 if (LocDecls
.empty())
2451 LocDeclsTy::iterator BeginIt
=
2452 llvm::partition_point(LocDecls
, [=](std::pair
<unsigned, Decl
*> LD
) {
2453 return LD
.first
< Offset
;
2455 if (BeginIt
!= LocDecls
.begin())
2458 // If we are pointing at a top-level decl inside an objc container, we need
2459 // to backtrack until we find it otherwise we will fail to report that the
2460 // region overlaps with an objc container.
2461 while (BeginIt
!= LocDecls
.begin() &&
2462 BeginIt
->second
->isTopLevelDeclInObjCContainer())
2465 LocDeclsTy::iterator EndIt
= llvm::upper_bound(
2466 LocDecls
, std::make_pair(Offset
+ Length
, (Decl
*)nullptr),
2467 llvm::less_first());
2468 if (EndIt
!= LocDecls
.end())
2471 for (LocDeclsTy::iterator DIt
= BeginIt
; DIt
!= EndIt
; ++DIt
)
2472 Decls
.push_back(DIt
->second
);
2475 SourceLocation
ASTUnit::getLocation(const FileEntry
*File
,
2476 unsigned Line
, unsigned Col
) const {
2477 const SourceManager
&SM
= getSourceManager();
2478 SourceLocation Loc
= SM
.translateFileLineCol(File
, Line
, Col
);
2479 return SM
.getMacroArgExpandedLocation(Loc
);
2482 SourceLocation
ASTUnit::getLocation(const FileEntry
*File
,
2483 unsigned Offset
) const {
2484 const SourceManager
&SM
= getSourceManager();
2485 SourceLocation FileLoc
= SM
.translateFileLineCol(File
, 1, 1);
2486 return SM
.getMacroArgExpandedLocation(FileLoc
.getLocWithOffset(Offset
));
2489 /// If \arg Loc is a loaded location from the preamble, returns
2490 /// the corresponding local location of the main file, otherwise it returns
2492 SourceLocation
ASTUnit::mapLocationFromPreamble(SourceLocation Loc
) const {
2495 PreambleID
= SourceMgr
->getPreambleFileID();
2497 if (Loc
.isInvalid() || !Preamble
|| PreambleID
.isInvalid())
2501 if (SourceMgr
->isInFileID(Loc
, PreambleID
, &Offs
) && Offs
< Preamble
->getBounds().Size
) {
2502 SourceLocation FileLoc
2503 = SourceMgr
->getLocForStartOfFile(SourceMgr
->getMainFileID());
2504 return FileLoc
.getLocWithOffset(Offs
);
2510 /// If \arg Loc is a local location of the main file but inside the
2511 /// preamble chunk, returns the corresponding loaded location from the
2512 /// preamble, otherwise it returns \arg Loc.
2513 SourceLocation
ASTUnit::mapLocationToPreamble(SourceLocation Loc
) const {
2516 PreambleID
= SourceMgr
->getPreambleFileID();
2518 if (Loc
.isInvalid() || !Preamble
|| PreambleID
.isInvalid())
2522 if (SourceMgr
->isInFileID(Loc
, SourceMgr
->getMainFileID(), &Offs
) &&
2523 Offs
< Preamble
->getBounds().Size
) {
2524 SourceLocation FileLoc
= SourceMgr
->getLocForStartOfFile(PreambleID
);
2525 return FileLoc
.getLocWithOffset(Offs
);
2531 bool ASTUnit::isInPreambleFileID(SourceLocation Loc
) const {
2534 FID
= SourceMgr
->getPreambleFileID();
2536 if (Loc
.isInvalid() || FID
.isInvalid())
2539 return SourceMgr
->isInFileID(Loc
, FID
);
2542 bool ASTUnit::isInMainFileID(SourceLocation Loc
) const {
2545 FID
= SourceMgr
->getMainFileID();
2547 if (Loc
.isInvalid() || FID
.isInvalid())
2550 return SourceMgr
->isInFileID(Loc
, FID
);
2553 SourceLocation
ASTUnit::getEndOfPreambleFileID() const {
2556 FID
= SourceMgr
->getPreambleFileID();
2558 if (FID
.isInvalid())
2561 return SourceMgr
->getLocForEndOfFile(FID
);
2564 SourceLocation
ASTUnit::getStartOfMainFileID() const {
2567 FID
= SourceMgr
->getMainFileID();
2569 if (FID
.isInvalid())
2572 return SourceMgr
->getLocForStartOfFile(FID
);
2575 llvm::iterator_range
<PreprocessingRecord::iterator
>
2576 ASTUnit::getLocalPreprocessingEntities() const {
2577 if (isMainFileAST()) {
2578 serialization::ModuleFile
&
2579 Mod
= Reader
->getModuleManager().getPrimaryModule();
2580 return Reader
->getModulePreprocessedEntities(Mod
);
2583 if (PreprocessingRecord
*PPRec
= PP
->getPreprocessingRecord())
2584 return llvm::make_range(PPRec
->local_begin(), PPRec
->local_end());
2586 return llvm::make_range(PreprocessingRecord::iterator(),
2587 PreprocessingRecord::iterator());
2590 bool ASTUnit::visitLocalTopLevelDecls(void *context
, DeclVisitorFn Fn
) {
2591 if (isMainFileAST()) {
2592 serialization::ModuleFile
&
2593 Mod
= Reader
->getModuleManager().getPrimaryModule();
2594 for (const auto *D
: Reader
->getModuleFileLevelDecls(Mod
)) {
2595 if (!Fn(context
, D
))
2602 for (ASTUnit::top_level_iterator TL
= top_level_begin(),
2603 TLEnd
= top_level_end();
2604 TL
!= TLEnd
; ++TL
) {
2605 if (!Fn(context
, *TL
))
2612 const FileEntry
*ASTUnit::getPCHFile() {
2616 serialization::ModuleFile
*Mod
= nullptr;
2617 Reader
->getModuleManager().visit([&Mod
](serialization::ModuleFile
&M
) {
2619 case serialization::MK_ImplicitModule
:
2620 case serialization::MK_ExplicitModule
:
2621 case serialization::MK_PrebuiltModule
:
2622 return true; // skip dependencies.
2623 case serialization::MK_PCH
:
2625 return true; // found it.
2626 case serialization::MK_Preamble
:
2627 return false; // look in dependencies.
2628 case serialization::MK_MainFile
:
2629 return false; // look in dependencies.
2640 bool ASTUnit::isModuleFile() const {
2641 return isMainFileAST() && getLangOpts().isCompilingModule();
2644 InputKind
ASTUnit::getInputKind() const {
2645 auto &LangOpts
= getLangOpts();
2648 if (LangOpts
.OpenCL
)
2649 Lang
= Language::OpenCL
;
2650 else if (LangOpts
.CUDA
)
2651 Lang
= Language::CUDA
;
2652 else if (LangOpts
.RenderScript
)
2653 Lang
= Language::RenderScript
;
2654 else if (LangOpts
.CPlusPlus
)
2655 Lang
= LangOpts
.ObjC
? Language::ObjCXX
: Language::CXX
;
2657 Lang
= LangOpts
.ObjC
? Language::ObjC
: Language::C
;
2659 InputKind::Format Fmt
= InputKind::Source
;
2660 if (LangOpts
.getCompilingModule() == LangOptions::CMK_ModuleMap
)
2661 Fmt
= InputKind::ModuleMap
;
2663 // We don't know if input was preprocessed. Assume not.
2666 return InputKind(Lang
, Fmt
, PP
);
2670 ASTUnit::ConcurrencyState::ConcurrencyState() {
2671 Mutex
= new std::recursive_mutex
;
2674 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2675 delete static_cast<std::recursive_mutex
*>(Mutex
);
2678 void ASTUnit::ConcurrencyState::start() {
2679 bool acquired
= static_cast<std::recursive_mutex
*>(Mutex
)->try_lock();
2680 assert(acquired
&& "Concurrent access to ASTUnit!");
2683 void ASTUnit::ConcurrencyState::finish() {
2684 static_cast<std::recursive_mutex
*>(Mutex
)->unlock();
2689 ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex
= nullptr; }
2690 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2691 void ASTUnit::ConcurrencyState::start() {}
2692 void ASTUnit::ConcurrencyState::finish() {}