/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/ASTUnit.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===- ASTUnit.cpp - ASTUnit utility --------------------------------------===// |
2 | | // |
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 |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // ASTUnit Implementation. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
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" |
93 | | #include <algorithm> |
94 | | #include <atomic> |
95 | | #include <cassert> |
96 | | #include <cstdint> |
97 | | #include <cstdio> |
98 | | #include <cstdlib> |
99 | | #include <memory> |
100 | | #include <mutex> |
101 | | #include <string> |
102 | | #include <tuple> |
103 | | #include <utility> |
104 | | #include <vector> |
105 | | |
106 | | using namespace clang; |
107 | | |
108 | | using llvm::TimeRecord; |
109 | | |
110 | | namespace { |
111 | | |
112 | | class SimpleTimer { |
113 | | bool WantTiming; |
114 | | TimeRecord Start; |
115 | | std::string Output; |
116 | | |
117 | | public: |
118 | 10.0k | explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) { |
119 | 10.0k | if (WantTiming) |
120 | 18 | Start = TimeRecord::getCurrentTime(); |
121 | 10.0k | } |
122 | | |
123 | 10.0k | ~SimpleTimer() { |
124 | 10.0k | if (WantTiming) { |
125 | 18 | TimeRecord Elapsed = TimeRecord::getCurrentTime(); |
126 | 18 | Elapsed -= Start; |
127 | 18 | llvm::errs() << Output << ':'; |
128 | 18 | Elapsed.print(Elapsed, llvm::errs()); |
129 | 18 | llvm::errs() << '\n'; |
130 | 18 | } |
131 | 10.0k | } |
132 | | |
133 | 10.0k | void setOutput(const Twine &Output) { |
134 | 10.0k | if (WantTiming) |
135 | 18 | this->Output = Output.str(); |
136 | 10.0k | } |
137 | | }; |
138 | | |
139 | | } // namespace |
140 | | |
141 | | template <class T> |
142 | 509 | static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) { |
143 | 509 | if (!Val) |
144 | 0 | return nullptr; |
145 | 509 | return std::move(*Val); |
146 | 509 | } |
147 | | |
148 | | template <class T> |
149 | | static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) { |
150 | | if (!Val) |
151 | | return false; |
152 | | Output = std::move(*Val); |
153 | | return true; |
154 | | } |
155 | | |
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 | 520 | StringRef FilePath, bool isVolatile) { |
162 | 520 | const auto &PreprocessorOpts = Invocation.getPreprocessorOpts(); |
163 | | |
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 | 520 | llvm::MemoryBuffer *Buffer = nullptr; |
168 | 520 | std::unique_ptr<llvm::MemoryBuffer> BufferOwner; |
169 | 520 | auto FileStatus = VFS->status(FilePath); |
170 | 520 | if (FileStatus) { |
171 | 520 | llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID(); |
172 | | |
173 | | // Check whether there is a file-file remapping of the main file |
174 | 520 | for (const auto &RF : PreprocessorOpts.RemappedFiles) { |
175 | 0 | std::string MPath(RF.first); |
176 | 0 | auto MPathStatus = VFS->status(MPath); |
177 | 0 | if (MPathStatus) { |
178 | 0 | llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID(); |
179 | 0 | if (MainFileID == MID) { |
180 | | // We found a remapping. Try to load the resulting, remapped source. |
181 | 0 | BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile)); |
182 | 0 | if (!BufferOwner) |
183 | 0 | return nullptr; |
184 | 0 | } |
185 | 0 | } |
186 | 0 | } |
187 | | |
188 | | // Check whether there is a file-buffer remapping. It supercedes the |
189 | | // file-file remapping. |
190 | 520 | for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) { |
191 | 23 | std::string MPath(RB.first); |
192 | 23 | auto MPathStatus = VFS->status(MPath); |
193 | 23 | if (MPathStatus) { |
194 | 19 | llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID(); |
195 | 19 | if (MainFileID == MID) { |
196 | | // We found a remapping. |
197 | 11 | BufferOwner.reset(); |
198 | 11 | Buffer = const_cast<llvm::MemoryBuffer *>(RB.second); |
199 | 11 | } |
200 | 19 | } |
201 | 23 | } |
202 | 520 | } |
203 | | |
204 | | // If the main source file was not remapped, load it now. |
205 | 520 | if (!Buffer && !BufferOwner509 ) { |
206 | 509 | BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile)); |
207 | 509 | if (!BufferOwner) |
208 | 0 | return nullptr; |
209 | 509 | } |
210 | | |
211 | 520 | if (BufferOwner) |
212 | 509 | return BufferOwner; |
213 | 11 | if (!Buffer) |
214 | 0 | return nullptr; |
215 | 11 | return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath); |
216 | 11 | } |
217 | | |
218 | | struct ASTUnit::ASTWriterData { |
219 | | SmallString<128> Buffer; |
220 | | llvm::BitstreamWriter Stream; |
221 | | ASTWriter Writer; |
222 | | |
223 | | ASTWriterData(InMemoryModuleCache &ModuleCache) |
224 | 60 | : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {} |
225 | | }; |
226 | | |
227 | 18.6k | void ASTUnit::clearFileLevelDecls() { |
228 | 18.6k | FileDecls.clear(); |
229 | 18.6k | } |
230 | | |
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 |
234 | | /// preamble. |
235 | | const unsigned DefaultPreambleRebuildInterval = 5; |
236 | | |
237 | | /// Tracks the number of ASTUnit objects that are currently active. |
238 | | /// |
239 | | /// Used for debugging purposes only. |
240 | | static std::atomic<unsigned> ActiveASTUnitObjects; |
241 | | |
242 | | ASTUnit::ASTUnit(bool _MainFileIsAST) |
243 | | : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")), |
244 | | ShouldCacheCodeCompletionResults(false), |
245 | | IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false), |
246 | 8.68k | UnsafeToFree(false) { |
247 | 8.68k | if (getenv("LIBCLANG_OBJTRACKING")) |
248 | 0 | fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects); |
249 | 8.68k | } |
250 | | |
251 | 8.66k | ASTUnit::~ASTUnit() { |
252 | | // If we loaded from an AST file, balance out the BeginSourceFile call. |
253 | 8.66k | if (MainFileIsAST && getDiagnostics().getClient()172 ) { |
254 | 172 | getDiagnostics().getClient()->EndSourceFile(); |
255 | 172 | } |
256 | | |
257 | 8.66k | clearFileLevelDecls(); |
258 | | |
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 |
262 | | // parser. |
263 | 8.66k | if (Invocation && OwnsRemappedFileBuffers8.49k ) { |
264 | 8.42k | PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); |
265 | 8.42k | for (const auto &RB : PPOpts.RemappedFileBuffers) |
266 | 13 | delete RB.second; |
267 | 8.42k | } |
268 | | |
269 | 8.66k | ClearCachedCompletionResults(); |
270 | | |
271 | 8.66k | if (getenv("LIBCLANG_OBJTRACKING")) |
272 | 0 | fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects); |
273 | 8.66k | } |
274 | | |
275 | 89 | void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) { |
276 | 89 | this->PP = std::move(PP); |
277 | 89 | } |
278 | | |
279 | 4.87k | void ASTUnit::enableSourceFileDiagnostics() { |
280 | 4.87k | assert(getDiagnostics().getClient() && Ctx && |
281 | 4.87k | "Bad context for source file"); |
282 | 0 | getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get()); |
283 | 4.87k | } |
284 | | |
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 | 517 | bool &IsNestedNameSpecifier) { |
290 | 517 | IsNestedNameSpecifier = false; |
291 | | |
292 | 517 | if (isa<UsingShadowDecl>(ND)) |
293 | 2 | ND = ND->getUnderlyingDecl(); |
294 | 517 | if (!ND) |
295 | 0 | return 0; |
296 | | |
297 | 517 | uint64_t Contexts = 0; |
298 | 517 | if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)344 || |
299 | 517 | isa<ClassTemplateDecl>(ND)294 || isa<TemplateTemplateParmDecl>(ND)287 || |
300 | 517 | isa<TypeAliasTemplateDecl>(ND)287 ) { |
301 | | // Types can appear in these contexts. |
302 | 231 | if (LangOpts.CPlusPlus || !isa<TagDecl>(ND)185 ) |
303 | 212 | Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel) |
304 | 212 | | (1LL << CodeCompletionContext::CCC_ObjCIvarList) |
305 | 212 | | (1LL << CodeCompletionContext::CCC_ClassStructUnion) |
306 | 212 | | (1LL << CodeCompletionContext::CCC_Statement) |
307 | 212 | | (1LL << CodeCompletionContext::CCC_Type) |
308 | 212 | | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); |
309 | | |
310 | | // In C++, types can appear in expressions contexts (for functional casts). |
311 | 231 | if (LangOpts.CPlusPlus) |
312 | 46 | Contexts |= (1LL << CodeCompletionContext::CCC_Expression); |
313 | | |
314 | | // In Objective-C, message sends can send interfaces. In Objective-C++, |
315 | | // all types are available due to functional casts. |
316 | 231 | if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND)185 ) |
317 | 94 | Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver); |
318 | | |
319 | | // In Objective-C, you can only be a subclass of another Objective-C class |
320 | 231 | if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) { |
321 | | // Objective-C interfaces can be used in a class property expression. |
322 | 50 | if (ID->getDefinition()) |
323 | 14 | Contexts |= (1LL << CodeCompletionContext::CCC_Expression); |
324 | 50 | Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName); |
325 | 50 | } |
326 | | |
327 | | // Deal with tag names. |
328 | 231 | if (isa<EnumDecl>(ND)) { |
329 | 2 | Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag); |
330 | | |
331 | | // Part of the nested-name-specifier in C++0x. |
332 | 2 | if (LangOpts.CPlusPlus11) |
333 | 0 | IsNestedNameSpecifier = true; |
334 | 229 | } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) { |
335 | 50 | if (Record->isUnion()) |
336 | 0 | Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag); |
337 | 50 | else |
338 | 50 | Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag); |
339 | | |
340 | 50 | if (LangOpts.CPlusPlus) |
341 | 33 | IsNestedNameSpecifier = true; |
342 | 179 | } else if (isa<ClassTemplateDecl>(ND)) |
343 | 7 | IsNestedNameSpecifier = true; |
344 | 286 | } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)21 ) { |
345 | | // Values can appear in these contexts. |
346 | 269 | Contexts = (1LL << CodeCompletionContext::CCC_Statement) |
347 | 269 | | (1LL << CodeCompletionContext::CCC_Expression) |
348 | 269 | | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) |
349 | 269 | | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver); |
350 | 269 | } else if (17 isa<ObjCProtocolDecl>(ND)17 ) { |
351 | 4 | Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName); |
352 | 13 | } else if (isa<ObjCCategoryDecl>(ND)) { |
353 | 0 | Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName); |
354 | 13 | } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)1 ) { |
355 | 12 | Contexts = (1LL << CodeCompletionContext::CCC_Namespace); |
356 | | |
357 | | // Part of the nested-name-specifier. |
358 | 12 | IsNestedNameSpecifier = true; |
359 | 12 | } |
360 | | |
361 | 517 | return Contexts; |
362 | 517 | } |
363 | | |
364 | 104 | void ASTUnit::CacheCodeCompletionResults() { |
365 | 104 | if (!TheSema) |
366 | 0 | return; |
367 | | |
368 | 104 | SimpleTimer Timer(WantTiming); |
369 | 104 | Timer.setOutput("Cache global code completions for " + getMainFileName()); |
370 | | |
371 | | // Clear out the previous results. |
372 | 104 | ClearCachedCompletionResults(); |
373 | | |
374 | | // Gather the set of global code completions. |
375 | 104 | using Result = CodeCompletionResult; |
376 | 104 | SmallVector<Result, 8> Results; |
377 | 104 | CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>(); |
378 | 104 | CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator); |
379 | 104 | TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, |
380 | 104 | CCTUInfo, Results); |
381 | | |
382 | | // Translate global code completions into cached completions. |
383 | 104 | llvm::DenseMap<CanQualType, unsigned> CompletionTypes; |
384 | 104 | CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel); |
385 | | |
386 | 44.7k | for (auto &R : Results) { |
387 | 44.7k | switch (R.Kind) { |
388 | 517 | case Result::RK_Declaration: { |
389 | 517 | bool IsNestedNameSpecifier = false; |
390 | 517 | CachedCodeCompletionResult CachedResult; |
391 | 517 | CachedResult.Completion = R.CreateCodeCompletionString( |
392 | 517 | *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, |
393 | 517 | IncludeBriefCommentsInCodeCompletion); |
394 | 517 | CachedResult.ShowInContexts = getDeclShowContexts( |
395 | 517 | R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier); |
396 | 517 | CachedResult.Priority = R.Priority; |
397 | 517 | CachedResult.Kind = R.CursorKind; |
398 | 517 | CachedResult.Availability = R.Availability; |
399 | | |
400 | | // Keep track of the type of this completion in an ASTContext-agnostic |
401 | | // way. |
402 | 517 | QualType UsageType = getDeclUsageType(*Ctx, R.Declaration); |
403 | 517 | if (UsageType.isNull()) { |
404 | 25 | CachedResult.TypeClass = STC_Void; |
405 | 25 | CachedResult.Type = 0; |
406 | 492 | } else { |
407 | 492 | CanQualType CanUsageType |
408 | 492 | = Ctx->getCanonicalType(UsageType.getUnqualifiedType()); |
409 | 492 | CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType); |
410 | | |
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 | 492 | unsigned &TypeValue = CompletionTypes[CanUsageType]; |
415 | 492 | if (TypeValue == 0) { |
416 | 346 | TypeValue = CompletionTypes.size(); |
417 | 346 | CachedCompletionTypes[QualType(CanUsageType).getAsString()] |
418 | 346 | = TypeValue; |
419 | 346 | } |
420 | | |
421 | 492 | CachedResult.Type = TypeValue; |
422 | 492 | } |
423 | | |
424 | 517 | CachedCompletionResults.push_back(CachedResult); |
425 | | |
426 | | /// Handle nested-name-specifiers in C++. |
427 | 517 | if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier139 && |
428 | 517 | !R.StartsNestedNameSpecifier52 ) { |
429 | | // The contexts in which a nested-name-specifier can appear in C++. |
430 | 52 | uint64_t NNSContexts |
431 | 52 | = (1LL << CodeCompletionContext::CCC_TopLevel) |
432 | 52 | | (1LL << CodeCompletionContext::CCC_ObjCIvarList) |
433 | 52 | | (1LL << CodeCompletionContext::CCC_ClassStructUnion) |
434 | 52 | | (1LL << CodeCompletionContext::CCC_Statement) |
435 | 52 | | (1LL << CodeCompletionContext::CCC_Expression) |
436 | 52 | | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) |
437 | 52 | | (1LL << CodeCompletionContext::CCC_EnumTag) |
438 | 52 | | (1LL << CodeCompletionContext::CCC_UnionTag) |
439 | 52 | | (1LL << CodeCompletionContext::CCC_ClassOrStructTag) |
440 | 52 | | (1LL << CodeCompletionContext::CCC_Type) |
441 | 52 | | (1LL << CodeCompletionContext::CCC_SymbolOrNewName) |
442 | 52 | | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); |
443 | | |
444 | 52 | if (isa<NamespaceDecl>(R.Declaration) || |
445 | 52 | isa<NamespaceAliasDecl>(R.Declaration)40 ) |
446 | 12 | NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace); |
447 | | |
448 | 52 | if (uint64_t RemainingContexts |
449 | 52 | = 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 | 52 | R.StartsNestedNameSpecifier = true; |
454 | 52 | CachedResult.Completion = R.CreateCodeCompletionString( |
455 | 52 | *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, |
456 | 52 | IncludeBriefCommentsInCodeCompletion); |
457 | 52 | CachedResult.ShowInContexts = RemainingContexts; |
458 | 52 | CachedResult.Priority = CCP_NestedNameSpecifier; |
459 | 52 | CachedResult.TypeClass = STC_Void; |
460 | 52 | CachedResult.Type = 0; |
461 | 52 | CachedCompletionResults.push_back(CachedResult); |
462 | 52 | } |
463 | 52 | } |
464 | 517 | break; |
465 | 0 | } |
466 | | |
467 | 0 | case Result::RK_Keyword: |
468 | 0 | case Result::RK_Pattern: |
469 | | // Ignore keywords and patterns; we don't care, since they are so |
470 | | // easily regenerated. |
471 | 0 | break; |
472 | | |
473 | 44.2k | case Result::RK_Macro: { |
474 | 44.2k | CachedCodeCompletionResult CachedResult; |
475 | 44.2k | CachedResult.Completion = R.CreateCodeCompletionString( |
476 | 44.2k | *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, |
477 | 44.2k | IncludeBriefCommentsInCodeCompletion); |
478 | 44.2k | CachedResult.ShowInContexts |
479 | 44.2k | = (1LL << CodeCompletionContext::CCC_TopLevel) |
480 | 44.2k | | (1LL << CodeCompletionContext::CCC_ObjCInterface) |
481 | 44.2k | | (1LL << CodeCompletionContext::CCC_ObjCImplementation) |
482 | 44.2k | | (1LL << CodeCompletionContext::CCC_ObjCIvarList) |
483 | 44.2k | | (1LL << CodeCompletionContext::CCC_ClassStructUnion) |
484 | 44.2k | | (1LL << CodeCompletionContext::CCC_Statement) |
485 | 44.2k | | (1LL << CodeCompletionContext::CCC_Expression) |
486 | 44.2k | | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) |
487 | 44.2k | | (1LL << CodeCompletionContext::CCC_MacroNameUse) |
488 | 44.2k | | (1LL << CodeCompletionContext::CCC_PreprocessorExpression) |
489 | 44.2k | | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) |
490 | 44.2k | | (1LL << CodeCompletionContext::CCC_OtherWithMacros); |
491 | | |
492 | 44.2k | CachedResult.Priority = R.Priority; |
493 | 44.2k | CachedResult.Kind = R.CursorKind; |
494 | 44.2k | CachedResult.Availability = R.Availability; |
495 | 44.2k | CachedResult.TypeClass = STC_Void; |
496 | 44.2k | CachedResult.Type = 0; |
497 | 44.2k | CachedCompletionResults.push_back(CachedResult); |
498 | 44.2k | break; |
499 | 0 | } |
500 | 44.7k | } |
501 | 44.7k | } |
502 | | |
503 | | // Save the current top-level hash value. |
504 | 104 | CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue; |
505 | 104 | } |
506 | | |
507 | 8.76k | void ASTUnit::ClearCachedCompletionResults() { |
508 | 8.76k | CachedCompletionResults.clear(); |
509 | 8.76k | CachedCompletionTypes.clear(); |
510 | 8.76k | CachedCompletionAllocator = nullptr; |
511 | 8.76k | } |
512 | | |
513 | | namespace { |
514 | | |
515 | | /// Gathers information from ASTReader that will be used to initialize |
516 | | /// a Preprocessor. |
517 | | class ASTInfoCollector : public ASTReaderListener { |
518 | | Preprocessor &PP; |
519 | | ASTContext *Context; |
520 | | HeaderSearchOptions &HSOpts; |
521 | | PreprocessorOptions &PPOpts; |
522 | | LangOptions &LangOpt; |
523 | | std::shared_ptr<TargetOptions> &TargetOpts; |
524 | | IntrusiveRefCntPtr<TargetInfo> &Target; |
525 | | unsigned &Counter; |
526 | | bool InitializedLanguage = false; |
527 | | |
528 | | public: |
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), |
536 | 182 | Counter(Counter) {} |
537 | | |
538 | | bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, |
539 | 182 | bool AllowCompatibleDifferences) override { |
540 | 182 | if (InitializedLanguage) |
541 | 0 | return false; |
542 | | |
543 | 182 | LangOpt = LangOpts; |
544 | 182 | InitializedLanguage = true; |
545 | | |
546 | 182 | updated(); |
547 | 182 | return false; |
548 | 182 | } |
549 | | |
550 | | bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, |
551 | | StringRef SpecificModuleCachePath, |
552 | 182 | bool Complain) override { |
553 | 182 | this->HSOpts = HSOpts; |
554 | 182 | return false; |
555 | 182 | } |
556 | | |
557 | | bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, |
558 | 182 | std::string &SuggestedPredefines) override { |
559 | 182 | this->PPOpts = PPOpts; |
560 | 182 | return false; |
561 | 182 | } |
562 | | |
563 | | bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, |
564 | 182 | bool AllowCompatibleDifferences) override { |
565 | | // If we've already initialized the target, don't do it again. |
566 | 182 | if (Target) |
567 | 0 | return false; |
568 | | |
569 | 182 | this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts); |
570 | 182 | Target = |
571 | 182 | TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts); |
572 | | |
573 | 182 | updated(); |
574 | 182 | return false; |
575 | 182 | } |
576 | | |
577 | | void ReadCounter(const serialization::ModuleFile &M, |
578 | 0 | unsigned Value) override { |
579 | 0 | Counter = Value; |
580 | 0 | } |
581 | | |
582 | | private: |
583 | 364 | void updated() { |
584 | 364 | if (!Target || !InitializedLanguage182 ) |
585 | 182 | return; |
586 | | |
587 | | // Inform the target of the language options. |
588 | | // |
589 | | // FIXME: We shouldn't need to do this, the target should be immutable once |
590 | | // created. This complexity should be lifted elsewhere. |
591 | 182 | Target->adjust(PP.getDiagnostics(), LangOpt); |
592 | | |
593 | | // Initialize the preprocessor. |
594 | 182 | PP.Initialize(*Target); |
595 | | |
596 | 182 | if (!Context) |
597 | 15 | return; |
598 | | |
599 | | // Initialize the ASTContext |
600 | 167 | Context->InitBuiltinTypes(*Target); |
601 | | |
602 | | // Adjust printing policy based on language options. |
603 | 167 | Context->setPrintingPolicy(PrintingPolicy(LangOpt)); |
604 | | |
605 | | // We didn't have access to the comment options when the ASTContext was |
606 | | // constructed, so register them now. |
607 | 167 | Context->getCommentCommandTraits().registerCommentOptions( |
608 | 167 | LangOpt.CommentOpts); |
609 | 167 | } |
610 | | }; |
611 | | |
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; |
619 | | |
620 | | public: |
621 | | FilterAndStoreDiagnosticConsumer( |
622 | | SmallVectorImpl<StoredDiagnostic> *StoredDiags, |
623 | | SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags, |
624 | | bool CaptureNonErrorsFromIncludes) |
625 | | : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags), |
626 | 2.86k | CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) { |
627 | 2.86k | assert((StoredDiags || StandaloneDiags) && |
628 | 2.86k | "No output collections were passed to StoredDiagnosticConsumer."); |
629 | 2.86k | } |
630 | | |
631 | | void BeginSourceFile(const LangOptions &LangOpts, |
632 | 2.68k | const Preprocessor *PP = nullptr) override { |
633 | 2.68k | this->LangOpts = &LangOpts; |
634 | 2.68k | if (PP) |
635 | 2.68k | SourceMgr = &PP->getSourceManager(); |
636 | 2.68k | } |
637 | | |
638 | | void HandleDiagnostic(DiagnosticsEngine::Level Level, |
639 | | const Diagnostic &Info) override; |
640 | | }; |
641 | | |
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; |
649 | | |
650 | | public: |
651 | | CaptureDroppedDiagnostics( |
652 | | CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags, |
653 | | SmallVectorImpl<StoredDiagnostic> *StoredDiags, |
654 | | SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags) |
655 | | : Diags(Diags), |
656 | | Client(StoredDiags, StandaloneDiags, |
657 | | CaptureDiagnostics != |
658 | 1.79k | CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) { |
659 | 1.79k | if (CaptureDiagnostics != CaptureDiagsKind::None || |
660 | 1.79k | Diags.getClient() == nullptr0 ) { |
661 | 1.79k | OwningPreviousClient = Diags.takeClient(); |
662 | 1.79k | PreviousClient = Diags.getClient(); |
663 | 1.79k | Diags.setClient(&Client, false); |
664 | 1.79k | } |
665 | 1.79k | } |
666 | | |
667 | 1.79k | ~CaptureDroppedDiagnostics() { |
668 | 1.79k | if (Diags.getClient() == &Client) |
669 | 1.79k | Diags.setClient(PreviousClient, !!OwningPreviousClient.release()); |
670 | 1.79k | } |
671 | | }; |
672 | | |
673 | | } // namespace |
674 | | |
675 | | static ASTUnit::StandaloneDiagnostic |
676 | | makeStandaloneDiagnostic(const LangOptions &LangOpts, |
677 | | const StoredDiagnostic &InDiag); |
678 | | |
679 | 2 | static bool isInMainFile(const clang::Diagnostic &D) { |
680 | 2 | if (!D.hasSourceManager() || !D.getLocation().isValid()) |
681 | 0 | return false; |
682 | | |
683 | 2 | auto &M = D.getSourceManager(); |
684 | 2 | return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation())); |
685 | 2 | } |
686 | | |
687 | | void FilterAndStoreDiagnosticConsumer::HandleDiagnostic( |
688 | 9.76k | DiagnosticsEngine::Level Level, const Diagnostic &Info) { |
689 | | // Default implementation (Warnings/errors count). |
690 | 9.76k | DiagnosticConsumer::HandleDiagnostic(Level, Info); |
691 | | |
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 | 9.76k | if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr9.74k ) { |
696 | 9.74k | if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning2 && |
697 | 9.74k | !isInMainFile(Info)2 ) { |
698 | 1 | return; |
699 | 1 | } |
700 | | |
701 | 9.74k | StoredDiagnostic *ResultDiag = nullptr; |
702 | 9.74k | if (StoredDiags) { |
703 | 9.74k | StoredDiags->emplace_back(Level, Info); |
704 | 9.74k | ResultDiag = &StoredDiags->back(); |
705 | 9.74k | } |
706 | | |
707 | 9.74k | if (StandaloneDiags) { |
708 | 25 | llvm::Optional<StoredDiagnostic> StoredDiag = None; |
709 | 25 | if (!ResultDiag) { |
710 | 0 | StoredDiag.emplace(Level, Info); |
711 | 0 | ResultDiag = StoredDiag.getPointer(); |
712 | 0 | } |
713 | 25 | StandaloneDiags->push_back( |
714 | 25 | makeStandaloneDiagnostic(*LangOpts, *ResultDiag)); |
715 | 25 | } |
716 | 9.74k | } |
717 | 9.76k | } |
718 | | |
719 | 27 | IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const { |
720 | 27 | return Reader; |
721 | 27 | } |
722 | | |
723 | 19.3k | ASTMutationListener *ASTUnit::getASTMutationListener() { |
724 | 19.3k | if (WriterData) |
725 | 60 | return &WriterData->Writer; |
726 | 19.2k | return nullptr; |
727 | 19.3k | } |
728 | | |
729 | 559 | ASTDeserializationListener *ASTUnit::getDeserializationListener() { |
730 | 559 | if (WriterData) |
731 | 7 | return &WriterData->Writer; |
732 | 552 | return nullptr; |
733 | 559 | } |
734 | | |
735 | | std::unique_ptr<llvm::MemoryBuffer> |
736 | 293 | ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) { |
737 | 293 | assert(FileMgr); |
738 | 0 | auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile); |
739 | 293 | if (Buffer) |
740 | 293 | return std::move(*Buffer); |
741 | 0 | if (ErrorStr) |
742 | 0 | *ErrorStr = Buffer.getError().message(); |
743 | 0 | return nullptr; |
744 | 293 | } |
745 | | |
746 | | /// Configure the diagnostics object for use with ASTUnit. |
747 | | void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags, |
748 | | ASTUnit &AST, |
749 | 8.68k | CaptureDiagsKind CaptureDiagnostics) { |
750 | 8.68k | assert(Diags.get() && "no DiagnosticsEngine was provided"); |
751 | 8.68k | if (CaptureDiagnostics != CaptureDiagsKind::None) |
752 | 1.06k | Diags->setClient(new FilterAndStoreDiagnosticConsumer( |
753 | 1.06k | &AST.StoredDiagnostics, nullptr, |
754 | 1.06k | CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes)); |
755 | 8.68k | } |
756 | | |
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 | 182 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { |
764 | 182 | std::unique_ptr<ASTUnit> AST(new ASTUnit(true)); |
765 | | |
766 | | // Recover resources if we crash before exiting this method. |
767 | 182 | llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> |
768 | 182 | ASTUnitCleanup(AST.get()); |
769 | 182 | llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, |
770 | 182 | llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> |
771 | 182 | DiagCleanup(Diags.get()); |
772 | | |
773 | 182 | ConfigureDiags(Diags, *AST, CaptureDiagnostics); |
774 | | |
775 | 182 | AST->LangOpts = std::make_shared<LangOptions>(); |
776 | 182 | AST->OnlyLocalDecls = OnlyLocalDecls; |
777 | 182 | AST->CaptureDiagnostics = CaptureDiagnostics; |
778 | 182 | AST->Diagnostics = Diags; |
779 | 182 | AST->FileMgr = new FileManager(FileSystemOpts, VFS); |
780 | 182 | AST->UserFilesAreVolatile = UserFilesAreVolatile; |
781 | 182 | AST->SourceMgr = new SourceManager(AST->getDiagnostics(), |
782 | 182 | AST->getFileManager(), |
783 | 182 | UserFilesAreVolatile); |
784 | 182 | AST->ModuleCache = new InMemoryModuleCache; |
785 | 182 | AST->HSOpts = std::make_shared<HeaderSearchOptions>(); |
786 | 182 | AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormat()); |
787 | 182 | AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts, |
788 | 182 | AST->getSourceManager(), |
789 | 182 | AST->getDiagnostics(), |
790 | 182 | AST->getLangOpts(), |
791 | 182 | /*Target=*/nullptr)); |
792 | 182 | AST->PPOpts = std::make_shared<PreprocessorOptions>(); |
793 | | |
794 | | // Gather Info for preprocessor construction later on. |
795 | | |
796 | 182 | HeaderSearch &HeaderInfo = *AST->HeaderInfo; |
797 | 182 | unsigned Counter; |
798 | | |
799 | 182 | AST->PP = std::make_shared<Preprocessor>( |
800 | 182 | AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts, |
801 | 182 | AST->getSourceManager(), HeaderInfo, AST->ModuleLoader, |
802 | 182 | /*IILookup=*/nullptr, |
803 | 182 | /*OwnsHeaderSearch=*/false); |
804 | 182 | Preprocessor &PP = *AST->PP; |
805 | | |
806 | 182 | if (ToLoad >= LoadASTOnly) |
807 | 167 | AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), |
808 | 167 | PP.getIdentifierTable(), PP.getSelectorTable(), |
809 | 167 | PP.getBuiltinInfo(), |
810 | 167 | AST->getTranslationUnitKind()); |
811 | | |
812 | 182 | DisableValidationForModuleKind disableValid = |
813 | 182 | DisableValidationForModuleKind::None; |
814 | 182 | if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) |
815 | 0 | disableValid = DisableValidationForModuleKind::All; |
816 | 182 | AST->Reader = new ASTReader( |
817 | 182 | PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {}, |
818 | 182 | /*isysroot=*/"", |
819 | 182 | /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors); |
820 | | |
821 | 182 | AST->Reader->setListener(std::make_unique<ASTInfoCollector>( |
822 | 182 | *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts, |
823 | 182 | AST->TargetOpts, AST->Target, Counter)); |
824 | | |
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. |
830 | 182 | if (AST->Ctx) |
831 | 167 | AST->Ctx->setExternalSource(AST->Reader); |
832 | | |
833 | 182 | switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile, |
834 | 182 | SourceLocation(), ASTReader::ARR_None)) { |
835 | 181 | case ASTReader::Success: |
836 | 181 | break; |
837 | | |
838 | 0 | case ASTReader::Failure: |
839 | 0 | case ASTReader::Missing: |
840 | 1 | case ASTReader::OutOfDate: |
841 | 1 | case ASTReader::VersionMismatch: |
842 | 1 | case ASTReader::ConfigurationMismatch: |
843 | 1 | case ASTReader::HadErrors: |
844 | 1 | AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); |
845 | 1 | return nullptr; |
846 | 182 | } |
847 | | |
848 | 181 | AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile()); |
849 | | |
850 | 181 | PP.setCounterValue(Counter); |
851 | | |
852 | | // Create an AST consumer, even though it isn't used. |
853 | 181 | if (ToLoad >= LoadASTOnly) |
854 | 166 | AST->Consumer.reset(new ASTConsumer); |
855 | | |
856 | | // Create a semantic analysis object and tell the AST reader about it. |
857 | 181 | if (ToLoad >= LoadEverything) { |
858 | 163 | AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer)); |
859 | 163 | AST->TheSema->Initialize(); |
860 | 163 | AST->Reader->InitializeSema(*AST->TheSema); |
861 | 163 | } |
862 | | |
863 | | // Tell the diagnostic client that we have started a source file. |
864 | 181 | AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP); |
865 | | |
866 | 181 | return AST; |
867 | 182 | } |
868 | | |
869 | | /// Add the given macro to the hash of all top-level entities. |
870 | 3.61M | static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) { |
871 | 3.61M | Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash); |
872 | 3.61M | } |
873 | | |
874 | | namespace { |
875 | | |
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 { |
879 | | unsigned &Hash; |
880 | | |
881 | | public: |
882 | 9.37k | explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {} |
883 | | |
884 | | void MacroDefined(const Token &MacroNameTok, |
885 | 3.61M | const MacroDirective *MD) override { |
886 | 3.61M | AddDefinedMacroToHash(MacroNameTok, Hash); |
887 | 3.61M | } |
888 | | }; |
889 | | |
890 | | } // namespace |
891 | | |
892 | | /// Add the given declaration to the hash of all top-level entities. |
893 | 32.5k | static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) { |
894 | 32.5k | if (!D) |
895 | 0 | return; |
896 | | |
897 | 32.5k | DeclContext *DC = D->getDeclContext(); |
898 | 32.5k | if (!DC) |
899 | 0 | return; |
900 | | |
901 | 32.5k | if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()800 )) |
902 | 194 | return; |
903 | | |
904 | 32.3k | if (const auto *ND = dyn_cast<NamedDecl>(D)) { |
905 | 32.0k | 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 | 449 | if (!EnumD->isScoped()) { |
909 | 430 | for (const auto *EI : EnumD->enumerators()) { |
910 | 430 | if (EI->getIdentifier()) |
911 | 430 | Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash); |
912 | 430 | } |
913 | 313 | } |
914 | 449 | } |
915 | | |
916 | 32.0k | if (ND->getIdentifier()) |
917 | 30.0k | Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash); |
918 | 1.91k | else if (DeclarationName Name = ND->getDeclName()) { |
919 | 947 | std::string NameStr = Name.getAsString(); |
920 | 947 | Hash = llvm::djbHash(NameStr, Hash); |
921 | 947 | } |
922 | 32.0k | return; |
923 | 32.0k | } |
924 | | |
925 | 333 | if (const auto *ImportD = dyn_cast<ImportDecl>(D)) { |
926 | 58 | if (const Module *Mod = ImportD->getImportedModule()) { |
927 | 58 | std::string ModName = Mod->getFullModuleName(); |
928 | 58 | Hash = llvm::djbHash(ModName, Hash); |
929 | 58 | } |
930 | 58 | return; |
931 | 58 | } |
932 | 333 | } |
933 | | |
934 | | namespace { |
935 | | |
936 | | class TopLevelDeclTrackerConsumer : public ASTConsumer { |
937 | | ASTUnit &Unit; |
938 | | unsigned &Hash; |
939 | | |
940 | | public: |
941 | | TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash) |
942 | 9.28k | : Unit(_Unit), Hash(Hash) { |
943 | 9.28k | Hash = 0; |
944 | 9.28k | } |
945 | | |
946 | 34.5k | void handleTopLevelDecl(Decl *D) { |
947 | 34.5k | if (!D) |
948 | 0 | return; |
949 | | |
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 | 34.5k | if (isa<ObjCMethodDecl>(D)) |
955 | 2.08k | return; |
956 | | |
957 | 32.4k | AddTopLevelDeclarationToHash(D, Hash); |
958 | 32.4k | Unit.addTopLevelDecl(D); |
959 | | |
960 | 32.4k | handleFileLevelDecl(D); |
961 | 32.4k | } |
962 | | |
963 | 74.6k | void handleFileLevelDecl(Decl *D) { |
964 | 74.6k | Unit.addFileLevelDecl(D); |
965 | 74.6k | if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { |
966 | 4.80k | for (auto *I : NSD->decls()) |
967 | 42.2k | handleFileLevelDecl(I); |
968 | 4.80k | } |
969 | 74.6k | } |
970 | | |
971 | 31.4k | bool HandleTopLevelDecl(DeclGroupRef D) override { |
972 | 31.4k | for (auto *TopLevelDecl : D) |
973 | 34.5k | handleTopLevelDecl(TopLevelDecl); |
974 | 31.4k | return true; |
975 | 31.4k | } |
976 | | |
977 | | // We're not interested in "interesting" decls. |
978 | 69 | void HandleInterestingDecl(DeclGroupRef) override {} |
979 | | |
980 | 17 | void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { |
981 | 17 | for (auto *TopLevelDecl : D) |
982 | 9 | handleTopLevelDecl(TopLevelDecl); |
983 | 17 | } |
984 | | |
985 | 19.3k | ASTMutationListener *GetASTMutationListener() override { |
986 | 19.3k | return Unit.getASTMutationListener(); |
987 | 19.3k | } |
988 | | |
989 | 559 | ASTDeserializationListener *GetASTDeserializationListener() override { |
990 | 559 | return Unit.getDeserializationListener(); |
991 | 559 | } |
992 | | }; |
993 | | |
994 | | class TopLevelDeclTrackerAction : public ASTFrontendAction { |
995 | | public: |
996 | | ASTUnit &Unit; |
997 | | |
998 | | std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, |
999 | 9.18k | StringRef InFile) override { |
1000 | 9.18k | CI.getPreprocessor().addPPCallbacks( |
1001 | 9.18k | std::make_unique<MacroDefinitionTrackerPPCallbacks>( |
1002 | 9.18k | Unit.getCurrentTopLevelHashValue())); |
1003 | 9.18k | return std::make_unique<TopLevelDeclTrackerConsumer>( |
1004 | 9.18k | Unit, Unit.getCurrentTopLevelHashValue()); |
1005 | 9.18k | } |
1006 | | |
1007 | | public: |
1008 | 9.18k | TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} |
1009 | | |
1010 | 9.18k | bool hasCodeCompletionSupport() const override { return false; } |
1011 | | |
1012 | 18.3k | TranslationUnitKind getTranslationUnitKind() override { |
1013 | 18.3k | return Unit.getTranslationUnitKind(); |
1014 | 18.3k | } |
1015 | | }; |
1016 | | |
1017 | | class ASTUnitPreambleCallbacks : public PreambleCallbacks { |
1018 | | public: |
1019 | 91 | unsigned getHash() const { return Hash; } |
1020 | | |
1021 | 0 | std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); } |
1022 | | |
1023 | 91 | std::vector<serialization::DeclID> takeTopLevelDeclIDs() { |
1024 | 91 | return std::move(TopLevelDeclIDs); |
1025 | 91 | } |
1026 | | |
1027 | 91 | void AfterPCHEmitted(ASTWriter &Writer) override { |
1028 | 91 | TopLevelDeclIDs.reserve(TopLevelDecls.size()); |
1029 | 92 | for (const auto *D : TopLevelDecls) { |
1030 | | // Invalid top-level decls may not have been serialized. |
1031 | 92 | if (D->isInvalidDecl()) |
1032 | 6 | continue; |
1033 | 86 | TopLevelDeclIDs.push_back(Writer.getDeclID(D)); |
1034 | 86 | } |
1035 | 91 | } |
1036 | | |
1037 | 87 | void HandleTopLevelDecl(DeclGroupRef DG) override { |
1038 | 92 | 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 | 92 | if (isa<ObjCMethodDecl>(D)) |
1044 | 0 | continue; |
1045 | 92 | AddTopLevelDeclarationToHash(D, Hash); |
1046 | 92 | TopLevelDecls.push_back(D); |
1047 | 92 | } |
1048 | 87 | } |
1049 | | |
1050 | 91 | std::unique_ptr<PPCallbacks> createPPCallbacks() override { |
1051 | 91 | return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash); |
1052 | 91 | } |
1053 | | |
1054 | | private: |
1055 | | unsigned Hash = 0; |
1056 | | std::vector<Decl *> TopLevelDecls; |
1057 | | std::vector<serialization::DeclID> TopLevelDeclIDs; |
1058 | | llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags; |
1059 | | }; |
1060 | | |
1061 | | } // namespace |
1062 | | |
1063 | 4.43k | static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) { |
1064 | 4.43k | return StoredDiag.getLocation().isValid(); |
1065 | 4.43k | } |
1066 | | |
1067 | | static void |
1068 | 8.96k | 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 | 8.96k | llvm::erase_if(StoredDiags, isNonDriverDiag); |
1072 | 8.96k | } |
1073 | | |
1074 | | static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> & |
1075 | | StoredDiagnostics, |
1076 | 263 | 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 |
1081 | | // location itself. |
1082 | 263 | for (auto &SD : StoredDiagnostics) { |
1083 | 97 | if (SD.getLocation().isValid()) { |
1084 | 97 | FullSourceLoc Loc(SD.getLocation(), SM); |
1085 | 97 | SD.setLocation(Loc); |
1086 | 97 | } |
1087 | 97 | } |
1088 | 263 | } |
1089 | | |
1090 | | /// Parse the source file into a translation unit using the given compiler |
1091 | | /// invocation, replacing the current translation unit. |
1092 | | /// |
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 | 9.13k | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { |
1098 | 9.13k | if (!Invocation) |
1099 | 0 | return true; |
1100 | | |
1101 | 9.13k | if (VFS && FileMgr) |
1102 | 8.31k | assert(VFS == &FileMgr->getVirtualFileSystem() && |
1103 | 9.13k | "VFS passed to Parse and VFS in FileMgr are different"); |
1104 | | |
1105 | 0 | auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation); |
1106 | 9.13k | if (OverrideMainBuffer) { |
1107 | 263 | assert(Preamble && |
1108 | 263 | "No preamble was built, but OverrideMainBuffer is not null"); |
1109 | 0 | Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get()); |
1110 | | // VFS may have changed... |
1111 | 263 | } |
1112 | | |
1113 | | // Create the compiler instance to use for building the AST. |
1114 | 0 | std::unique_ptr<CompilerInstance> Clang( |
1115 | 9.13k | new CompilerInstance(std::move(PCHContainerOps))); |
1116 | | |
1117 | | // Clean up on error, disengage it if the function returns successfully. |
1118 | 9.13k | auto CleanOnError = llvm::make_scope_exit([&]() { |
1119 | | // Remove the overridden buffer we used for the preamble. |
1120 | 3 | SavedMainFileBuffer = nullptr; |
1121 | | |
1122 | | // Keep the ownership of the data in the ASTUnit because the client may |
1123 | | // want to see the diagnostics. |
1124 | 3 | transferASTDataFromCompilerInstance(*Clang); |
1125 | 3 | FailedParseDiagnostics.swap(StoredDiagnostics); |
1126 | 3 | StoredDiagnostics.clear(); |
1127 | 3 | NumStoredDiagnosticsFromDriver = 0; |
1128 | 3 | }); |
1129 | | |
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 | 9.13k | if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS8.31k ) |
1134 | 8.30k | Clang->setFileManager(&*FileMgr); |
1135 | 832 | else |
1136 | 832 | FileMgr = Clang->createFileManager(std::move(VFS)); |
1137 | | |
1138 | | // Recover resources if we crash before exiting this method. |
1139 | 9.13k | llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> |
1140 | 9.13k | CICleanup(Clang.get()); |
1141 | | |
1142 | 9.13k | Clang->setInvocation(CCInvocation); |
1143 | 9.13k | OriginalSourceFile = |
1144 | 9.13k | std::string(Clang->getFrontendOpts().Inputs[0].getFile()); |
1145 | | |
1146 | | // Set up diagnostics, capturing any diagnostics that would |
1147 | | // otherwise be dropped. |
1148 | 9.13k | Clang->setDiagnostics(&getDiagnostics()); |
1149 | | |
1150 | | // Create the target instance. |
1151 | 9.13k | if (!Clang->createTarget()) |
1152 | 1 | return true; |
1153 | | |
1154 | 9.13k | assert(Clang->getFrontendOpts().Inputs.size() == 1 && |
1155 | 9.13k | "Invocation must have exactly one source file!"); |
1156 | 0 | assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == |
1157 | 9.13k | InputKind::Source && |
1158 | 9.13k | "FIXME: AST inputs not yet supported here!"); |
1159 | 0 | assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != |
1160 | 9.13k | Language::LLVM_IR && |
1161 | 9.13k | "IR inputs not support here!"); |
1162 | | |
1163 | | // Configure the various subsystems. |
1164 | 0 | LangOpts = Clang->getInvocation().LangOpts; |
1165 | 9.13k | FileSystemOpts = Clang->getFileSystemOpts(); |
1166 | | |
1167 | 9.13k | ResetForParse(); |
1168 | | |
1169 | 9.13k | SourceMgr = new SourceManager(getDiagnostics(), *FileMgr, |
1170 | 9.13k | UserFilesAreVolatile); |
1171 | 9.13k | if (!OverrideMainBuffer) { |
1172 | 8.87k | checkAndRemoveNonDriverDiags(StoredDiagnostics); |
1173 | 8.87k | TopLevelDeclsInPreamble.clear(); |
1174 | 8.87k | } |
1175 | | |
1176 | | // Create the source manager. |
1177 | 9.13k | Clang->setSourceManager(&getSourceManager()); |
1178 | | |
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 | 9.13k | 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 |
1186 | | // location itself. |
1187 | 263 | checkAndSanitizeDiags(StoredDiagnostics, getSourceManager()); |
1188 | | |
1189 | | // Keep track of the override buffer; |
1190 | 263 | SavedMainFileBuffer = std::move(OverrideMainBuffer); |
1191 | 263 | } |
1192 | | |
1193 | 9.13k | std::unique_ptr<TopLevelDeclTrackerAction> Act( |
1194 | 9.13k | new TopLevelDeclTrackerAction(*this)); |
1195 | | |
1196 | | // Recover resources if we crash before exiting this method. |
1197 | 9.13k | llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> |
1198 | 9.13k | ActCleanup(Act.get()); |
1199 | | |
1200 | 9.13k | if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) |
1201 | 2 | return true; |
1202 | | |
1203 | 9.13k | if (SavedMainFileBuffer) |
1204 | 263 | TranslateStoredDiagnostics(getFileManager(), getSourceManager(), |
1205 | 263 | PreambleDiagnostics, StoredDiagnostics); |
1206 | 8.87k | else |
1207 | 8.87k | PreambleSrcLocCache.clear(); |
1208 | | |
1209 | 9.13k | if (llvm::Error Err = Act->Execute()) { |
1210 | 0 | consumeError(std::move(Err)); // FIXME this drops errors on the floor. |
1211 | 0 | return true; |
1212 | 0 | } |
1213 | | |
1214 | 9.13k | transferASTDataFromCompilerInstance(*Clang); |
1215 | | |
1216 | 9.13k | Act->EndSourceFile(); |
1217 | | |
1218 | 9.13k | FailedParseDiagnostics.clear(); |
1219 | | |
1220 | 9.13k | CleanOnError.release(); |
1221 | | |
1222 | 9.13k | return false; |
1223 | 9.13k | } |
1224 | | |
1225 | | static std::pair<unsigned, unsigned> |
1226 | | makeStandaloneRange(CharSourceRange Range, const SourceManager &SM, |
1227 | 16 | const LangOptions &LangOpts) { |
1228 | 16 | CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts); |
1229 | 16 | unsigned Offset = SM.getFileOffset(FileRange.getBegin()); |
1230 | 16 | unsigned EndOffset = SM.getFileOffset(FileRange.getEnd()); |
1231 | 16 | return std::make_pair(Offset, EndOffset); |
1232 | 16 | } |
1233 | | |
1234 | | static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM, |
1235 | | const LangOptions &LangOpts, |
1236 | 3 | const FixItHint &InFix) { |
1237 | 3 | ASTUnit::StandaloneFixIt OutFix; |
1238 | 3 | OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts); |
1239 | 3 | OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM, |
1240 | 3 | LangOpts); |
1241 | 3 | OutFix.CodeToInsert = InFix.CodeToInsert; |
1242 | 3 | OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions; |
1243 | 3 | return OutFix; |
1244 | 3 | } |
1245 | | |
1246 | | static ASTUnit::StandaloneDiagnostic |
1247 | | makeStandaloneDiagnostic(const LangOptions &LangOpts, |
1248 | 25 | const StoredDiagnostic &InDiag) { |
1249 | 25 | ASTUnit::StandaloneDiagnostic OutDiag; |
1250 | 25 | OutDiag.ID = InDiag.getID(); |
1251 | 25 | OutDiag.Level = InDiag.getLevel(); |
1252 | 25 | OutDiag.Message = std::string(InDiag.getMessage()); |
1253 | 25 | OutDiag.LocOffset = 0; |
1254 | 25 | if (InDiag.getLocation().isInvalid()) |
1255 | 0 | return OutDiag; |
1256 | 25 | const SourceManager &SM = InDiag.getLocation().getManager(); |
1257 | 25 | SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation()); |
1258 | 25 | OutDiag.Filename = std::string(SM.getFilename(FileLoc)); |
1259 | 25 | if (OutDiag.Filename.empty()) |
1260 | 0 | return OutDiag; |
1261 | 25 | OutDiag.LocOffset = SM.getFileOffset(FileLoc); |
1262 | 25 | for (const auto &Range : InDiag.getRanges()) |
1263 | 10 | OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts)); |
1264 | 25 | for (const auto &FixIt : InDiag.getFixIts()) |
1265 | 3 | OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt)); |
1266 | | |
1267 | 25 | return OutDiag; |
1268 | 25 | } |
1269 | | |
1270 | | /// Attempt to build or re-use a precompiled preamble when (re-)parsing |
1271 | | /// the source file. |
1272 | | /// |
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. |
1279 | | /// |
1280 | | /// \param AllowRebuild When true (the default), this routine is |
1281 | | /// allowed to rebuild the precompiled preamble if it is found to be |
1282 | | /// out-of-date. |
1283 | | /// |
1284 | | /// \param MaxLines When non-zero, the maximum number of lines that |
1285 | | /// can occur within the preamble. |
1286 | | /// |
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 | 520 | unsigned MaxLines) { |
1296 | 520 | auto MainFilePath = |
1297 | 520 | PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile(); |
1298 | 520 | std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer = |
1299 | 520 | getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(), |
1300 | 520 | MainFilePath, UserFilesAreVolatile); |
1301 | 520 | if (!MainFileBuffer) |
1302 | 0 | return nullptr; |
1303 | | |
1304 | 520 | PreambleBounds Bounds = ComputePreambleBounds( |
1305 | 520 | *PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines); |
1306 | 520 | if (!Bounds.Size) |
1307 | 97 | return nullptr; |
1308 | | |
1309 | 423 | if (Preamble) { |
1310 | 257 | if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds, |
1311 | 257 | *VFS)) { |
1312 | | // Okay! We can re-use the precompiled preamble. |
1313 | | |
1314 | | // Set the state of the diagnostic object to mimic its state |
1315 | | // after parsing the preamble. |
1316 | 247 | getDiagnostics().Reset(); |
1317 | 247 | ProcessWarningOptions(getDiagnostics(), |
1318 | 247 | PreambleInvocationIn.getDiagnosticOpts()); |
1319 | 247 | getDiagnostics().setNumWarnings(NumWarningsInPreamble); |
1320 | | |
1321 | 247 | PreambleRebuildCountdown = 1; |
1322 | 247 | return MainFileBuffer; |
1323 | 247 | } else { |
1324 | 10 | Preamble.reset(); |
1325 | 10 | PreambleDiagnostics.clear(); |
1326 | 10 | TopLevelDeclsInPreamble.clear(); |
1327 | 10 | PreambleSrcLocCache.clear(); |
1328 | 10 | PreambleRebuildCountdown = 1; |
1329 | 10 | } |
1330 | 257 | } |
1331 | | |
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 | 176 | if (PreambleRebuildCountdown > 1) { |
1336 | 81 | --PreambleRebuildCountdown; |
1337 | 81 | return nullptr; |
1338 | 81 | } |
1339 | | |
1340 | 95 | assert(!Preamble && "No Preamble should be stored at that point"); |
1341 | | // If we aren't allowed to rebuild the precompiled preamble, just |
1342 | | // return now. |
1343 | 95 | if (!AllowRebuild) |
1344 | 4 | return nullptr; |
1345 | | |
1346 | 91 | ++PreambleCounter; |
1347 | | |
1348 | 91 | SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone; |
1349 | 91 | SmallVector<StoredDiagnostic, 4> NewPreambleDiags; |
1350 | 91 | ASTUnitPreambleCallbacks Callbacks; |
1351 | 91 | { |
1352 | 91 | llvm::Optional<CaptureDroppedDiagnostics> Capture; |
1353 | 91 | if (CaptureDiagnostics != CaptureDiagsKind::None) |
1354 | 83 | Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags, |
1355 | 83 | &NewPreambleDiagsStandalone); |
1356 | | |
1357 | | // We did not previously compute a preamble, or it can't be reused anyway. |
1358 | 91 | SimpleTimer PreambleTimer(WantTiming); |
1359 | 91 | PreambleTimer.setOutput("Precompiling preamble"); |
1360 | | |
1361 | 91 | const bool PreviousSkipFunctionBodies = |
1362 | 91 | PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies; |
1363 | 91 | if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble) |
1364 | 1 | PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true; |
1365 | | |
1366 | 91 | llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build( |
1367 | 91 | PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS, |
1368 | 91 | PCHContainerOps, /*StoreInMemory=*/false, Callbacks); |
1369 | | |
1370 | 91 | PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = |
1371 | 91 | PreviousSkipFunctionBodies; |
1372 | | |
1373 | 91 | if (NewPreamble) { |
1374 | 91 | Preamble = std::move(*NewPreamble); |
1375 | 91 | PreambleRebuildCountdown = 1; |
1376 | 91 | } else { |
1377 | 0 | switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) { |
1378 | 0 | case BuildPreambleError::CouldntCreateTempFile: |
1379 | | // Try again next time. |
1380 | 0 | PreambleRebuildCountdown = 1; |
1381 | 0 | return nullptr; |
1382 | 0 | case BuildPreambleError::CouldntCreateTargetInfo: |
1383 | 0 | case BuildPreambleError::BeginSourceFileFailed: |
1384 | 0 | case BuildPreambleError::CouldntEmitPCH: |
1385 | 0 | case BuildPreambleError::BadInputs: |
1386 | | // These erros are more likely to repeat, retry after some period. |
1387 | 0 | PreambleRebuildCountdown = DefaultPreambleRebuildInterval; |
1388 | 0 | return nullptr; |
1389 | 0 | } |
1390 | 0 | llvm_unreachable("unexpected BuildPreambleError"); |
1391 | 0 | } |
1392 | 91 | } |
1393 | | |
1394 | 91 | assert(Preamble && "Preamble wasn't built"); |
1395 | | |
1396 | 0 | TopLevelDecls.clear(); |
1397 | 91 | TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs(); |
1398 | 91 | PreambleTopLevelHashValue = Callbacks.getHash(); |
1399 | | |
1400 | 91 | NumWarningsInPreamble = getDiagnostics().getNumWarnings(); |
1401 | | |
1402 | 91 | checkAndRemoveNonDriverDiags(NewPreambleDiags); |
1403 | 91 | StoredDiagnostics = std::move(NewPreambleDiags); |
1404 | 91 | PreambleDiagnostics = std::move(NewPreambleDiagsStandalone); |
1405 | | |
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 |
1408 | | // cache. |
1409 | 91 | if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) { |
1410 | 80 | CompletionCacheTopLevelHashValue = 0; |
1411 | 80 | PreambleTopLevelHashValue = CurrentTopLevelHashValue; |
1412 | 80 | } |
1413 | | |
1414 | 91 | return MainFileBuffer; |
1415 | 91 | } |
1416 | | |
1417 | 5 | void ASTUnit::RealizeTopLevelDeclsFromPreamble() { |
1418 | 5 | assert(Preamble && "Should only be called when preamble was built"); |
1419 | | |
1420 | 0 | std::vector<Decl *> Resolved; |
1421 | 5 | Resolved.reserve(TopLevelDeclsInPreamble.size()); |
1422 | 5 | ExternalASTSource &Source = *getASTContext().getExternalSource(); |
1423 | 9 | for (const auto TopLevelDecl : TopLevelDeclsInPreamble) { |
1424 | | // Resolve the declaration ID to an actual declaration, possibly |
1425 | | // deserializing the declaration in the process. |
1426 | 9 | if (Decl *D = Source.GetExternalDecl(TopLevelDecl)) |
1427 | 9 | Resolved.push_back(D); |
1428 | 9 | } |
1429 | 5 | TopLevelDeclsInPreamble.clear(); |
1430 | 5 | TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); |
1431 | 5 | } |
1432 | | |
1433 | 9.31k | void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) { |
1434 | | // Steal the created target, context, and preprocessor if they have been |
1435 | | // created. |
1436 | 9.31k | assert(CI.hasInvocation() && "missing invocation"); |
1437 | 0 | LangOpts = CI.getInvocation().LangOpts; |
1438 | 9.31k | TheSema = CI.takeSema(); |
1439 | 9.31k | Consumer = CI.takeASTConsumer(); |
1440 | 9.31k | if (CI.hasASTContext()) |
1441 | 9.31k | Ctx = &CI.getASTContext(); |
1442 | 9.31k | if (CI.hasPreprocessor()) |
1443 | 9.31k | PP = CI.getPreprocessorPtr(); |
1444 | 9.31k | CI.setSourceManager(nullptr); |
1445 | 9.31k | CI.setFileManager(nullptr); |
1446 | 9.31k | if (CI.hasTarget()) |
1447 | 9.31k | Target = &CI.getTarget(); |
1448 | 9.31k | Reader = CI.getASTReader(); |
1449 | 9.31k | HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure(); |
1450 | 9.31k | } |
1451 | | |
1452 | 9.53k | StringRef ASTUnit::getMainFileName() const { |
1453 | 9.53k | if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()9.53k ) { |
1454 | 9.53k | const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0]; |
1455 | 9.53k | if (Input.isFile()) |
1456 | 9.53k | return Input.getFile(); |
1457 | 0 | else |
1458 | 0 | return Input.getBuffer().getBufferIdentifier(); |
1459 | 9.53k | } |
1460 | | |
1461 | 1 | if (SourceMgr) { |
1462 | 1 | if (const FileEntry * |
1463 | 1 | FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID())) |
1464 | 1 | return FE->getName(); |
1465 | 1 | } |
1466 | | |
1467 | 0 | return {}; |
1468 | 1 | } |
1469 | | |
1470 | 0 | StringRef ASTUnit::getASTFileName() const { |
1471 | 0 | if (!isMainFileAST()) |
1472 | 0 | return {}; |
1473 | | |
1474 | 0 | serialization::ModuleFile & |
1475 | 0 | Mod = Reader->getModuleManager().getPrimaryModule(); |
1476 | 0 | return Mod.FileName; |
1477 | 0 | } |
1478 | | |
1479 | | std::unique_ptr<ASTUnit> |
1480 | | ASTUnit::create(std::shared_ptr<CompilerInvocation> CI, |
1481 | | IntrusiveRefCntPtr<DiagnosticsEngine> Diags, |
1482 | | CaptureDiagsKind CaptureDiagnostics, |
1483 | 185 | bool UserFilesAreVolatile) { |
1484 | 185 | std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); |
1485 | 185 | ConfigureDiags(Diags, *AST, CaptureDiagnostics); |
1486 | 185 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = |
1487 | 185 | createVFSFromCompilerInvocation(*CI, *Diags); |
1488 | 185 | AST->Diagnostics = Diags; |
1489 | 185 | AST->FileSystemOpts = CI->getFileSystemOpts(); |
1490 | 185 | AST->Invocation = std::move(CI); |
1491 | 185 | AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); |
1492 | 185 | AST->UserFilesAreVolatile = UserFilesAreVolatile; |
1493 | 185 | AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr, |
1494 | 185 | UserFilesAreVolatile); |
1495 | 185 | AST->ModuleCache = new InMemoryModuleCache; |
1496 | | |
1497 | 185 | return AST; |
1498 | 185 | } |
1499 | | |
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 | 185 | bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) { |
1508 | 185 | assert(CI && "A CompilerInvocation is required"); |
1509 | | |
1510 | 0 | std::unique_ptr<ASTUnit> OwnAST; |
1511 | 185 | ASTUnit *AST = Unit; |
1512 | 185 | if (!AST) { |
1513 | | // Create the AST unit. |
1514 | 145 | OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile); |
1515 | 145 | AST = OwnAST.get(); |
1516 | 145 | if (!AST) |
1517 | 0 | return nullptr; |
1518 | 145 | } |
1519 | | |
1520 | 185 | if (!ResourceFilesPath.empty()) { |
1521 | | // Override the resources path. |
1522 | 40 | CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath); |
1523 | 40 | } |
1524 | 185 | AST->OnlyLocalDecls = OnlyLocalDecls; |
1525 | 185 | AST->CaptureDiagnostics = CaptureDiagnostics; |
1526 | 185 | if (PrecompilePreambleAfterNParses > 0) |
1527 | 0 | AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses; |
1528 | 185 | AST->TUKind = Action ? Action->getTranslationUnitKind()135 : TU_Complete50 ; |
1529 | 185 | AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; |
1530 | 185 | AST->IncludeBriefCommentsInCodeCompletion = false; |
1531 | | |
1532 | | // Recover resources if we crash before exiting this method. |
1533 | 185 | llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> |
1534 | 185 | ASTUnitCleanup(OwnAST.get()); |
1535 | 185 | llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, |
1536 | 185 | llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> |
1537 | 185 | DiagCleanup(Diags.get()); |
1538 | | |
1539 | | // We'll manage file buffers ourselves. |
1540 | 185 | CI->getPreprocessorOpts().RetainRemappedFileBuffers = true; |
1541 | 185 | CI->getFrontendOpts().DisableFree = false; |
1542 | 185 | ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts()); |
1543 | | |
1544 | | // Create the compiler instance to use for building the AST. |
1545 | 185 | std::unique_ptr<CompilerInstance> Clang( |
1546 | 185 | new CompilerInstance(std::move(PCHContainerOps))); |
1547 | | |
1548 | | // Recover resources if we crash before exiting this method. |
1549 | 185 | llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> |
1550 | 185 | CICleanup(Clang.get()); |
1551 | | |
1552 | 185 | Clang->setInvocation(std::move(CI)); |
1553 | 185 | AST->OriginalSourceFile = |
1554 | 185 | std::string(Clang->getFrontendOpts().Inputs[0].getFile()); |
1555 | | |
1556 | | // Set up diagnostics, capturing any diagnostics that would |
1557 | | // otherwise be dropped. |
1558 | 185 | Clang->setDiagnostics(&AST->getDiagnostics()); |
1559 | | |
1560 | | // Create the target instance. |
1561 | 185 | if (!Clang->createTarget()) |
1562 | 0 | return nullptr; |
1563 | | |
1564 | 185 | assert(Clang->getFrontendOpts().Inputs.size() == 1 && |
1565 | 185 | "Invocation must have exactly one source file!"); |
1566 | 0 | assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == |
1567 | 185 | InputKind::Source && |
1568 | 185 | "FIXME: AST inputs not yet supported here!"); |
1569 | 0 | assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != |
1570 | 185 | Language::LLVM_IR && |
1571 | 185 | "IR inputs not support here!"); |
1572 | | |
1573 | | // Configure the various subsystems. |
1574 | 0 | AST->TheSema.reset(); |
1575 | 185 | AST->Ctx = nullptr; |
1576 | 185 | AST->PP = nullptr; |
1577 | 185 | AST->Reader = nullptr; |
1578 | | |
1579 | | // Create a file manager object to provide access to and cache the filesystem. |
1580 | 185 | Clang->setFileManager(&AST->getFileManager()); |
1581 | | |
1582 | | // Create the source manager. |
1583 | 185 | Clang->setSourceManager(&AST->getSourceManager()); |
1584 | | |
1585 | 185 | FrontendAction *Act = Action; |
1586 | | |
1587 | 185 | std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct; |
1588 | 185 | if (!Act) { |
1589 | 50 | TrackerAct.reset(new TopLevelDeclTrackerAction(*AST)); |
1590 | 50 | Act = TrackerAct.get(); |
1591 | 50 | } |
1592 | | |
1593 | | // Recover resources if we crash before exiting this method. |
1594 | 185 | llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction> |
1595 | 185 | ActCleanup(TrackerAct.get()); |
1596 | | |
1597 | 185 | if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) { |
1598 | 0 | AST->transferASTDataFromCompilerInstance(*Clang); |
1599 | 0 | if (OwnAST && ErrAST) |
1600 | 0 | ErrAST->swap(OwnAST); |
1601 | |
|
1602 | 0 | return nullptr; |
1603 | 0 | } |
1604 | | |
1605 | 185 | if (Persistent && !TrackerAct145 ) { |
1606 | 95 | Clang->getPreprocessor().addPPCallbacks( |
1607 | 95 | std::make_unique<MacroDefinitionTrackerPPCallbacks>( |
1608 | 95 | AST->getCurrentTopLevelHashValue())); |
1609 | 95 | std::vector<std::unique_ptr<ASTConsumer>> Consumers; |
1610 | 95 | if (Clang->hasASTConsumer()) |
1611 | 95 | Consumers.push_back(Clang->takeASTConsumer()); |
1612 | 95 | Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>( |
1613 | 95 | *AST, AST->getCurrentTopLevelHashValue())); |
1614 | 95 | Clang->setASTConsumer( |
1615 | 95 | std::make_unique<MultiplexConsumer>(std::move(Consumers))); |
1616 | 95 | } |
1617 | 185 | if (llvm::Error Err = Act->Execute()) { |
1618 | 0 | consumeError(std::move(Err)); // FIXME this drops errors on the floor. |
1619 | 0 | AST->transferASTDataFromCompilerInstance(*Clang); |
1620 | 0 | if (OwnAST && ErrAST) |
1621 | 0 | ErrAST->swap(OwnAST); |
1622 | |
|
1623 | 0 | return nullptr; |
1624 | 0 | } |
1625 | | |
1626 | | // Steal the created target, context, and preprocessor. |
1627 | 185 | AST->transferASTDataFromCompilerInstance(*Clang); |
1628 | | |
1629 | 185 | Act->EndSourceFile(); |
1630 | | |
1631 | 185 | if (OwnAST) |
1632 | 145 | return OwnAST.release(); |
1633 | 40 | else |
1634 | 40 | return AST; |
1635 | 185 | } |
1636 | | |
1637 | | bool ASTUnit::LoadFromCompilerInvocation( |
1638 | | std::shared_ptr<PCHContainerOperations> PCHContainerOps, |
1639 | | unsigned PrecompilePreambleAfterNParses, |
1640 | 8.31k | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { |
1641 | 8.31k | if (!Invocation) |
1642 | 0 | return true; |
1643 | | |
1644 | 8.31k | assert(VFS && "VFS is null"); |
1645 | | |
1646 | | // We'll manage file buffers ourselves. |
1647 | 0 | Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true; |
1648 | 8.31k | Invocation->getFrontendOpts().DisableFree = false; |
1649 | 8.31k | getDiagnostics().Reset(); |
1650 | 8.31k | ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); |
1651 | | |
1652 | 8.31k | std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; |
1653 | 8.31k | if (PrecompilePreambleAfterNParses > 0) { |
1654 | 133 | PreambleRebuildCountdown = PrecompilePreambleAfterNParses; |
1655 | 133 | OverrideMainBuffer = |
1656 | 133 | getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS); |
1657 | 133 | getDiagnostics().Reset(); |
1658 | 133 | ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); |
1659 | 133 | } |
1660 | | |
1661 | 8.31k | SimpleTimer ParsingTimer(WantTiming); |
1662 | 8.31k | ParsingTimer.setOutput("Parsing " + getMainFileName()); |
1663 | | |
1664 | | // Recover resources if we crash before exiting this method. |
1665 | 8.31k | llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer> |
1666 | 8.31k | MemBufferCleanup(OverrideMainBuffer.get()); |
1667 | | |
1668 | 8.31k | return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS); |
1669 | 8.31k | } |
1670 | | |
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 | 7.31k | bool UserFilesAreVolatile) { |
1679 | | // Create the AST unit. |
1680 | 7.31k | std::unique_ptr<ASTUnit> AST(new ASTUnit(false)); |
1681 | 7.31k | ConfigureDiags(Diags, *AST, CaptureDiagnostics); |
1682 | 7.31k | AST->Diagnostics = Diags; |
1683 | 7.31k | AST->OnlyLocalDecls = OnlyLocalDecls; |
1684 | 7.31k | AST->CaptureDiagnostics = CaptureDiagnostics; |
1685 | 7.31k | AST->TUKind = TUKind; |
1686 | 7.31k | AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; |
1687 | 7.31k | AST->IncludeBriefCommentsInCodeCompletion |
1688 | 7.31k | = IncludeBriefCommentsInCodeCompletion; |
1689 | 7.31k | AST->Invocation = std::move(CI); |
1690 | 7.31k | AST->FileSystemOpts = FileMgr->getFileSystemOpts(); |
1691 | 7.31k | AST->FileMgr = FileMgr; |
1692 | 7.31k | AST->UserFilesAreVolatile = UserFilesAreVolatile; |
1693 | | |
1694 | | // Recover resources if we crash before exiting this method. |
1695 | 7.31k | llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> |
1696 | 7.31k | ASTUnitCleanup(AST.get()); |
1697 | 7.31k | llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine, |
1698 | 7.31k | llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>> |
1699 | 7.31k | DiagCleanup(Diags.get()); |
1700 | | |
1701 | 7.31k | if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), |
1702 | 7.31k | PrecompilePreambleAfterNParses, |
1703 | 7.31k | &AST->FileMgr->getVirtualFileSystem())) |
1704 | 0 | return nullptr; |
1705 | 7.31k | return AST; |
1706 | 7.31k | } |
1707 | | |
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 | 994 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { |
1721 | 994 | assert(Diags.get() && "no DiagnosticsEngine was provided"); |
1722 | | |
1723 | 0 | SmallVector<StoredDiagnostic, 4> StoredDiagnostics; |
1724 | | |
1725 | 994 | std::shared_ptr<CompilerInvocation> CI; |
1726 | | |
1727 | 994 | { |
1728 | 994 | CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, |
1729 | 994 | &StoredDiagnostics, nullptr); |
1730 | | |
1731 | 994 | CreateInvocationOptions CIOpts; |
1732 | 994 | CIOpts.VFS = VFS; |
1733 | 994 | CIOpts.Diags = Diags; |
1734 | 994 | CIOpts.ProbePrecompiled = true; // FIXME: historical default. Needed? |
1735 | 994 | CI = createInvocation(llvm::makeArrayRef(ArgBegin, ArgEnd), |
1736 | 994 | std::move(CIOpts)); |
1737 | 994 | if (!CI) |
1738 | 0 | return nullptr; |
1739 | 994 | } |
1740 | | |
1741 | | // Override any files that need remapping |
1742 | 994 | for (const auto &RemappedFile : RemappedFiles) { |
1743 | 4 | CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first, |
1744 | 4 | RemappedFile.second); |
1745 | 4 | } |
1746 | 994 | PreprocessorOptions &PPOpts = CI->getPreprocessorOpts(); |
1747 | 994 | PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName; |
1748 | 994 | PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors; |
1749 | 994 | PPOpts.SingleFileParseMode = SingleFileParse; |
1750 | 994 | PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks; |
1751 | | |
1752 | | // Override the resources path. |
1753 | 994 | CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath); |
1754 | | |
1755 | 994 | CI->getFrontendOpts().SkipFunctionBodies = |
1756 | 994 | SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile; |
1757 | | |
1758 | 994 | if (ModuleFormat) |
1759 | 993 | CI->getHeaderSearchOpts().ModuleFormat = std::string(*ModuleFormat); |
1760 | | |
1761 | | // Create the AST unit. |
1762 | 994 | std::unique_ptr<ASTUnit> AST; |
1763 | 994 | AST.reset(new ASTUnit(false)); |
1764 | 994 | AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size(); |
1765 | 994 | AST->StoredDiagnostics.swap(StoredDiagnostics); |
1766 | 994 | ConfigureDiags(Diags, *AST, CaptureDiagnostics); |
1767 | 994 | AST->Diagnostics = Diags; |
1768 | 994 | AST->FileSystemOpts = CI->getFileSystemOpts(); |
1769 | 994 | if (!VFS) |
1770 | 994 | VFS = llvm::vfs::getRealFileSystem(); |
1771 | 994 | VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); |
1772 | 994 | AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); |
1773 | 994 | AST->ModuleCache = new InMemoryModuleCache; |
1774 | 994 | AST->OnlyLocalDecls = OnlyLocalDecls; |
1775 | 994 | AST->CaptureDiagnostics = CaptureDiagnostics; |
1776 | 994 | AST->TUKind = TUKind; |
1777 | 994 | AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; |
1778 | 994 | AST->IncludeBriefCommentsInCodeCompletion |
1779 | 994 | = IncludeBriefCommentsInCodeCompletion; |
1780 | 994 | AST->UserFilesAreVolatile = UserFilesAreVolatile; |
1781 | 994 | AST->Invocation = CI; |
1782 | 994 | AST->SkipFunctionBodies = SkipFunctionBodies; |
1783 | 994 | if (ForSerialization) |
1784 | 60 | AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache)); |
1785 | | // Zero out now to ease cleanup during crash recovery. |
1786 | 994 | CI = nullptr; |
1787 | 994 | Diags = nullptr; |
1788 | | |
1789 | | // Recover resources if we crash before exiting this method. |
1790 | 994 | llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> |
1791 | 994 | ASTUnitCleanup(AST.get()); |
1792 | | |
1793 | 994 | if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps), |
1794 | 994 | PrecompilePreambleAfterNParses, |
1795 | 994 | VFS)) { |
1796 | | // Some error occurred, if caller wants to examine diagnostics, pass it the |
1797 | | // ASTUnit. |
1798 | 3 | if (ErrAST) { |
1799 | 3 | AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics); |
1800 | 3 | ErrAST->swap(AST); |
1801 | 3 | } |
1802 | 3 | return nullptr; |
1803 | 3 | } |
1804 | | |
1805 | 991 | return AST.release(); |
1806 | 994 | } |
1807 | | |
1808 | | bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, |
1809 | | ArrayRef<RemappedFile> RemappedFiles, |
1810 | 826 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { |
1811 | 826 | if (!Invocation) |
1812 | 0 | return true; |
1813 | | |
1814 | 826 | if (!VFS) { |
1815 | 819 | assert(FileMgr && "FileMgr is null on Reparse call"); |
1816 | 0 | VFS = &FileMgr->getVirtualFileSystem(); |
1817 | 819 | } |
1818 | | |
1819 | 0 | clearFileLevelDecls(); |
1820 | | |
1821 | 826 | SimpleTimer ParsingTimer(WantTiming); |
1822 | 826 | ParsingTimer.setOutput("Reparsing " + getMainFileName()); |
1823 | | |
1824 | | // Remap files. |
1825 | 826 | PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); |
1826 | 826 | for (const auto &RB : PPOpts.RemappedFileBuffers) |
1827 | 12 | delete RB.second; |
1828 | | |
1829 | 826 | Invocation->getPreprocessorOpts().clearRemappedFiles(); |
1830 | 826 | for (const auto &RemappedFile : RemappedFiles) { |
1831 | 18 | Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first, |
1832 | 18 | RemappedFile.second); |
1833 | 18 | } |
1834 | | |
1835 | | // If we have a preamble file lying around, or if we might try to |
1836 | | // build a precompiled preamble, do so now. |
1837 | 826 | std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; |
1838 | 826 | if (Preamble || PreambleRebuildCountdown > 0648 ) |
1839 | 303 | OverrideMainBuffer = |
1840 | 303 | getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS); |
1841 | | |
1842 | | // Clear out the diagnostics state. |
1843 | 826 | FileMgr.reset(); |
1844 | 826 | getDiagnostics().Reset(); |
1845 | 826 | ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); |
1846 | 826 | if (OverrideMainBuffer) |
1847 | 254 | getDiagnostics().setNumWarnings(NumWarningsInPreamble); |
1848 | | |
1849 | | // Parse the sources |
1850 | 826 | bool Result = |
1851 | 826 | Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS); |
1852 | | |
1853 | | // If we're caching global code-completion results, and the top-level |
1854 | | // declarations have changed, clear out the code-completion cache. |
1855 | 826 | if (!Result && ShouldCacheCodeCompletionResults825 && |
1856 | 826 | CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue238 ) |
1857 | 104 | CacheCodeCompletionResults(); |
1858 | | |
1859 | | // We now need to clear out the completion info related to this translation |
1860 | | // unit; it'll be recreated if necessary. |
1861 | 826 | CCTUInfo.reset(); |
1862 | | |
1863 | 826 | return Result; |
1864 | 826 | } |
1865 | | |
1866 | 9.16k | void ASTUnit::ResetForParse() { |
1867 | 9.16k | SavedMainFileBuffer.reset(); |
1868 | | |
1869 | 9.16k | SourceMgr.reset(); |
1870 | 9.16k | TheSema.reset(); |
1871 | 9.16k | Ctx.reset(); |
1872 | 9.16k | PP.reset(); |
1873 | 9.16k | Reader.reset(); |
1874 | | |
1875 | 9.16k | TopLevelDecls.clear(); |
1876 | 9.16k | clearFileLevelDecls(); |
1877 | 9.16k | } |
1878 | | |
1879 | | //----------------------------------------------------------------------------// |
1880 | | // Code completion |
1881 | | //----------------------------------------------------------------------------// |
1882 | | |
1883 | | namespace { |
1884 | | |
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; |
1890 | | ASTUnit &AST; |
1891 | | CodeCompleteConsumer &Next; |
1892 | | |
1893 | | public: |
1894 | | AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next, |
1895 | | const CodeCompleteOptions &CodeCompleteOpts) |
1896 | 721 | : 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. |
1899 | 721 | NormalContexts |
1900 | 721 | = (1LL << CodeCompletionContext::CCC_TopLevel) |
1901 | 721 | | (1LL << CodeCompletionContext::CCC_ObjCInterface) |
1902 | 721 | | (1LL << CodeCompletionContext::CCC_ObjCImplementation) |
1903 | 721 | | (1LL << CodeCompletionContext::CCC_ObjCIvarList) |
1904 | 721 | | (1LL << CodeCompletionContext::CCC_Statement) |
1905 | 721 | | (1LL << CodeCompletionContext::CCC_Expression) |
1906 | 721 | | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver) |
1907 | 721 | | (1LL << CodeCompletionContext::CCC_DotMemberAccess) |
1908 | 721 | | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess) |
1909 | 721 | | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess) |
1910 | 721 | | (1LL << CodeCompletionContext::CCC_ObjCProtocolName) |
1911 | 721 | | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) |
1912 | 721 | | (1LL << CodeCompletionContext::CCC_Recovery); |
1913 | | |
1914 | 721 | if (AST.getASTContext().getLangOpts().CPlusPlus) |
1915 | 257 | NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag) |
1916 | 257 | | (1LL << CodeCompletionContext::CCC_UnionTag) |
1917 | 257 | | (1LL << CodeCompletionContext::CCC_ClassOrStructTag); |
1918 | 721 | } |
1919 | | |
1920 | | void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, |
1921 | | CodeCompletionResult *Results, |
1922 | | unsigned NumResults) override; |
1923 | | |
1924 | | void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
1925 | | OverloadCandidate *Candidates, |
1926 | | unsigned NumCandidates, |
1927 | | SourceLocation OpenParLoc, |
1928 | 101 | bool Braced) override { |
1929 | 101 | Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates, |
1930 | 101 | OpenParLoc, Braced); |
1931 | 101 | } |
1932 | | |
1933 | 2.79k | CodeCompletionAllocator &getAllocator() override { |
1934 | 2.79k | return Next.getAllocator(); |
1935 | 2.79k | } |
1936 | | |
1937 | 2.79k | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { |
1938 | 2.79k | return Next.getCodeCompletionTUInfo(); |
1939 | 2.79k | } |
1940 | | }; |
1941 | | |
1942 | | } // namespace |
1943 | | |
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, |
1949 | | ASTContext &Ctx, |
1950 | 156 | llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){ |
1951 | 156 | bool OnlyTagNames = false; |
1952 | 156 | switch (Context.getKind()) { |
1953 | 0 | case CodeCompletionContext::CCC_Recovery: |
1954 | 25 | case CodeCompletionContext::CCC_TopLevel: |
1955 | 25 | case CodeCompletionContext::CCC_ObjCInterface: |
1956 | 25 | case CodeCompletionContext::CCC_ObjCImplementation: |
1957 | 25 | case CodeCompletionContext::CCC_ObjCIvarList: |
1958 | 25 | case CodeCompletionContext::CCC_ClassStructUnion: |
1959 | 66 | case CodeCompletionContext::CCC_Statement: |
1960 | 111 | case CodeCompletionContext::CCC_Expression: |
1961 | 111 | case CodeCompletionContext::CCC_ObjCMessageReceiver: |
1962 | 111 | case CodeCompletionContext::CCC_DotMemberAccess: |
1963 | 111 | case CodeCompletionContext::CCC_ArrowMemberAccess: |
1964 | 111 | case CodeCompletionContext::CCC_ObjCPropertyAccess: |
1965 | 111 | case CodeCompletionContext::CCC_Namespace: |
1966 | 111 | case CodeCompletionContext::CCC_Type: |
1967 | 111 | case CodeCompletionContext::CCC_Symbol: |
1968 | 121 | case CodeCompletionContext::CCC_SymbolOrNewName: |
1969 | 131 | case CodeCompletionContext::CCC_ParenthesizedExpression: |
1970 | 136 | case CodeCompletionContext::CCC_ObjCInterfaceName: |
1971 | 136 | break; |
1972 | | |
1973 | 0 | case CodeCompletionContext::CCC_EnumTag: |
1974 | 0 | case CodeCompletionContext::CCC_UnionTag: |
1975 | 5 | case CodeCompletionContext::CCC_ClassOrStructTag: |
1976 | 5 | OnlyTagNames = true; |
1977 | 5 | break; |
1978 | | |
1979 | 5 | case CodeCompletionContext::CCC_ObjCProtocolName: |
1980 | 5 | case CodeCompletionContext::CCC_MacroName: |
1981 | 10 | case CodeCompletionContext::CCC_MacroNameUse: |
1982 | 15 | case CodeCompletionContext::CCC_PreprocessorExpression: |
1983 | 15 | case CodeCompletionContext::CCC_PreprocessorDirective: |
1984 | 15 | case CodeCompletionContext::CCC_NaturalLanguage: |
1985 | 15 | case CodeCompletionContext::CCC_SelectorName: |
1986 | 15 | case CodeCompletionContext::CCC_TypeQualifiers: |
1987 | 15 | case CodeCompletionContext::CCC_Other: |
1988 | 15 | case CodeCompletionContext::CCC_OtherWithMacros: |
1989 | 15 | case CodeCompletionContext::CCC_ObjCInstanceMessage: |
1990 | 15 | case CodeCompletionContext::CCC_ObjCClassMessage: |
1991 | 15 | case CodeCompletionContext::CCC_ObjCCategoryName: |
1992 | 15 | case CodeCompletionContext::CCC_IncludedFile: |
1993 | 15 | case CodeCompletionContext::CCC_Attribute: |
1994 | 15 | case CodeCompletionContext::CCC_NewName: |
1995 | | // We're looking for nothing, or we're looking for names that cannot |
1996 | | // be hidden. |
1997 | 15 | return; |
1998 | 156 | } |
1999 | | |
2000 | 141 | using Result = CodeCompletionResult; |
2001 | 3.70k | for (unsigned I = 0; I != NumResults; ++I3.55k ) { |
2002 | 3.55k | if (Results[I].Kind != Result::RK_Declaration) |
2003 | 3.40k | continue; |
2004 | | |
2005 | 155 | unsigned IDNS |
2006 | 155 | = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace(); |
2007 | | |
2008 | 155 | bool Hiding = false; |
2009 | 155 | if (OnlyTagNames) |
2010 | 5 | Hiding = (IDNS & Decl::IDNS_Tag); |
2011 | 150 | else { |
2012 | 150 | unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | |
2013 | 150 | Decl::IDNS_Namespace | Decl::IDNS_Ordinary | |
2014 | 150 | Decl::IDNS_NonMemberOperator); |
2015 | 150 | if (Ctx.getLangOpts().CPlusPlus) |
2016 | 5 | HiddenIDNS |= Decl::IDNS_Tag; |
2017 | 150 | Hiding = (IDNS & HiddenIDNS); |
2018 | 150 | } |
2019 | | |
2020 | 155 | if (!Hiding) |
2021 | 10 | continue; |
2022 | | |
2023 | 145 | DeclarationName Name = Results[I].Declaration->getDeclName(); |
2024 | 145 | if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo()) |
2025 | 145 | HiddenNames.insert(Identifier->getName()); |
2026 | 0 | else |
2027 | 0 | HiddenNames.insert(Name.getAsString()); |
2028 | 145 | } |
2029 | 141 | } |
2030 | | |
2031 | | void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, |
2032 | | CodeCompletionContext Context, |
2033 | | CodeCompletionResult *Results, |
2034 | 716 | unsigned NumResults) { |
2035 | | // Merge the results we were given with the results we cached. |
2036 | 716 | bool AddedResult = false; |
2037 | 716 | uint64_t InContexts = |
2038 | 716 | Context.getKind() == CodeCompletionContext::CCC_Recovery |
2039 | 716 | ? NormalContexts1 : (1LL << Context.getKind())715 ; |
2040 | | // Contains the set of names that are hidden by "local" completion results. |
2041 | 716 | llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames; |
2042 | 716 | using Result = CodeCompletionResult; |
2043 | 716 | SmallVector<Result, 8> AllResults; |
2044 | 716 | for (ASTUnit::cached_completion_iterator |
2045 | 716 | C = AST.cached_completion_begin(), |
2046 | 716 | CEnd = AST.cached_completion_end(); |
2047 | 100k | C != CEnd; ++C99.7k ) { |
2048 | | // If the context we are in matches any of the contexts we are |
2049 | | // interested in, we'll add this result. |
2050 | 99.7k | if ((C->ShowInContexts & InContexts) == 0) |
2051 | 43.7k | continue; |
2052 | | |
2053 | | // If we haven't added any results previously, do so now. |
2054 | 56.0k | if (!AddedResult) { |
2055 | 156 | CalculateHiddenNames(Context, Results, NumResults, S.Context, |
2056 | 156 | HiddenNames); |
2057 | 156 | AllResults.insert(AllResults.end(), Results, Results + NumResults); |
2058 | 156 | AddedResult = true; |
2059 | 156 | } |
2060 | | |
2061 | | // Determine whether this global completion result is hidden by a local |
2062 | | // completion result. If so, skip it. |
2063 | 56.0k | if (C->Kind != CXCursor_MacroDefinition && |
2064 | 56.0k | HiddenNames.count(C->Completion->getTypedText())743 ) |
2065 | 20 | continue; |
2066 | | |
2067 | | // Adjust priority based on similar type classes. |
2068 | 56.0k | unsigned Priority = C->Priority; |
2069 | 56.0k | CodeCompletionString *Completion = C->Completion; |
2070 | 56.0k | if (!Context.getPreferredType().isNull()) { |
2071 | 14.7k | if (C->Kind == CXCursor_MacroDefinition) { |
2072 | 14.5k | Priority = getMacroUsagePriority(C->Completion->getTypedText(), |
2073 | 14.5k | S.getLangOpts(), |
2074 | 14.5k | Context.getPreferredType()->isAnyPointerType()); |
2075 | 14.5k | } else if (200 C->Type200 ) { |
2076 | 200 | CanQualType Expected |
2077 | 200 | = S.Context.getCanonicalType( |
2078 | 200 | Context.getPreferredType().getUnqualifiedType()); |
2079 | 200 | SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected); |
2080 | 200 | if (ExpectedSTC == C->TypeClass) { |
2081 | | // We know this type is similar; check for an exact match. |
2082 | 60 | llvm::StringMap<unsigned> &CachedCompletionTypes |
2083 | 60 | = AST.getCachedCompletionTypes(); |
2084 | 60 | llvm::StringMap<unsigned>::iterator Pos |
2085 | 60 | = CachedCompletionTypes.find(QualType(Expected).getAsString()); |
2086 | 60 | if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type) |
2087 | 60 | Priority /= CCF_ExactTypeMatch; |
2088 | 0 | else |
2089 | 0 | Priority /= CCF_SimilarTypeMatch; |
2090 | 60 | } |
2091 | 200 | } |
2092 | 14.7k | } |
2093 | | |
2094 | | // Adjust the completion string, if required. |
2095 | 56.0k | if (C->Kind == CXCursor_MacroDefinition && |
2096 | 56.0k | Context.getKind() == CodeCompletionContext::CCC_MacroNameUse55.3k ) { |
2097 | | // Create a new code-completion string that just contains the |
2098 | | // macro name, without its arguments. |
2099 | 2.11k | CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(), |
2100 | 2.11k | CCP_CodePattern, C->Availability); |
2101 | 2.11k | Builder.AddTypedTextChunk(C->Completion->getTypedText()); |
2102 | 2.11k | Priority = CCP_CodePattern; |
2103 | 2.11k | Completion = Builder.TakeString(); |
2104 | 2.11k | } |
2105 | | |
2106 | 56.0k | AllResults.push_back(Result(Completion, Priority, C->Kind, |
2107 | 56.0k | C->Availability)); |
2108 | 56.0k | } |
2109 | | |
2110 | | // If we did not add any cached completion results, just forward the |
2111 | | // results we were given to the next consumer. |
2112 | 716 | if (!AddedResult) { |
2113 | 560 | Next.ProcessCodeCompleteResults(S, Context, Results, NumResults); |
2114 | 560 | return; |
2115 | 560 | } |
2116 | | |
2117 | 156 | Next.ProcessCodeCompleteResults(S, Context, AllResults.data(), |
2118 | 156 | AllResults.size()); |
2119 | 156 | } |
2120 | | |
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 | 721 | SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { |
2130 | 721 | if (!Invocation) |
2131 | 0 | return; |
2132 | | |
2133 | 721 | SimpleTimer CompletionTimer(WantTiming); |
2134 | 721 | CompletionTimer.setOutput("Code completion @ " + File + ":" + |
2135 | 721 | Twine(Line) + ":" + Twine(Column)); |
2136 | | |
2137 | 721 | auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation); |
2138 | | |
2139 | 721 | FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts(); |
2140 | 721 | CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts; |
2141 | 721 | PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts(); |
2142 | | |
2143 | 721 | CodeCompleteOpts.IncludeMacros = IncludeMacros && |
2144 | 721 | CachedCompletionResults.empty(); |
2145 | 721 | CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns; |
2146 | 721 | CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty(); |
2147 | 721 | CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments; |
2148 | 721 | CodeCompleteOpts.LoadExternal = Consumer.loadExternal(); |
2149 | 721 | CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts(); |
2150 | | |
2151 | 721 | assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion); |
2152 | | |
2153 | 0 | FrontendOpts.CodeCompletionAt.FileName = std::string(File); |
2154 | 721 | FrontendOpts.CodeCompletionAt.Line = Line; |
2155 | 721 | FrontendOpts.CodeCompletionAt.Column = Column; |
2156 | | |
2157 | | // Set the language options appropriately. |
2158 | 721 | LangOpts = *CCInvocation->getLangOpts(); |
2159 | | |
2160 | | // Spell-checking and warnings are wasteful during code-completion. |
2161 | 721 | LangOpts.SpellChecking = false; |
2162 | 721 | CCInvocation->getDiagnosticOpts().IgnoreWarnings = true; |
2163 | | |
2164 | 721 | std::unique_ptr<CompilerInstance> Clang( |
2165 | 721 | new CompilerInstance(PCHContainerOps)); |
2166 | | |
2167 | | // Recover resources if we crash before exiting this method. |
2168 | 721 | llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> |
2169 | 721 | CICleanup(Clang.get()); |
2170 | | |
2171 | 721 | auto &Inv = *CCInvocation; |
2172 | 721 | Clang->setInvocation(std::move(CCInvocation)); |
2173 | 721 | OriginalSourceFile = |
2174 | 721 | std::string(Clang->getFrontendOpts().Inputs[0].getFile()); |
2175 | | |
2176 | | // Set up diagnostics, capturing any diagnostics produced. |
2177 | 721 | Clang->setDiagnostics(&Diag); |
2178 | 721 | CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All, |
2179 | 721 | Clang->getDiagnostics(), |
2180 | 721 | &StoredDiagnostics, nullptr); |
2181 | 721 | ProcessWarningOptions(Diag, Inv.getDiagnosticOpts()); |
2182 | | |
2183 | | // Create the target instance. |
2184 | 721 | if (!Clang->createTarget()) { |
2185 | 0 | Clang->setInvocation(nullptr); |
2186 | 0 | return; |
2187 | 0 | } |
2188 | | |
2189 | 721 | assert(Clang->getFrontendOpts().Inputs.size() == 1 && |
2190 | 721 | "Invocation must have exactly one source file!"); |
2191 | 0 | assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() == |
2192 | 721 | InputKind::Source && |
2193 | 721 | "FIXME: AST inputs not yet supported here!"); |
2194 | 0 | assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() != |
2195 | 721 | Language::LLVM_IR && |
2196 | 721 | "IR inputs not support here!"); |
2197 | | |
2198 | | // Use the source and file managers that we were given. |
2199 | 0 | Clang->setFileManager(&FileMgr); |
2200 | 721 | Clang->setSourceManager(&SourceMgr); |
2201 | | |
2202 | | // Remap files. |
2203 | 721 | PreprocessorOpts.clearRemappedFiles(); |
2204 | 721 | PreprocessorOpts.RetainRemappedFileBuffers = true; |
2205 | 721 | for (const auto &RemappedFile : RemappedFiles) { |
2206 | 4 | PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second); |
2207 | 4 | OwnedBuffers.push_back(RemappedFile.second); |
2208 | 4 | } |
2209 | | |
2210 | | // Use the code completion consumer we were given, but adding any cached |
2211 | | // code-completion results. |
2212 | 721 | AugmentedCodeCompleteConsumer *AugmentedConsumer |
2213 | 721 | = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts); |
2214 | 721 | Clang->setCodeCompletionConsumer(AugmentedConsumer); |
2215 | | |
2216 | 721 | auto getUniqueID = |
2217 | 721 | [&FileMgr](StringRef Filename) -> Optional<llvm::sys::fs::UniqueID> { |
2218 | 0 | if (auto Status = FileMgr.getVirtualFileSystem().status(Filename)) |
2219 | 0 | return Status->getUniqueID(); |
2220 | 0 | return None; |
2221 | 0 | }; |
2222 | | |
2223 | 721 | auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) { |
2224 | 84 | if (LHS == RHS) |
2225 | 84 | return true; |
2226 | 0 | if (auto LHSID = getUniqueID(LHS)) |
2227 | 0 | if (auto RHSID = getUniqueID(RHS)) |
2228 | 0 | return *LHSID == *RHSID; |
2229 | 0 | return false; |
2230 | 0 | }; |
2231 | | |
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 |
2235 | | // preamble. |
2236 | 721 | std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; |
2237 | 721 | if (Preamble && Line > 184 && hasSameUniqueID(File, OriginalSourceFile)84 ) { |
2238 | 84 | OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( |
2239 | 84 | PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1); |
2240 | 84 | } |
2241 | | |
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 | 721 | if (OverrideMainBuffer) { |
2245 | 75 | assert(Preamble && |
2246 | 75 | "No preamble was built, but OverrideMainBuffer is not null"); |
2247 | | |
2248 | 0 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = |
2249 | 75 | &FileMgr.getVirtualFileSystem(); |
2250 | 75 | Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS, |
2251 | 75 | 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 | 75 | OwnedBuffers.push_back(OverrideMainBuffer.release()); |
2257 | 646 | } else { |
2258 | 646 | PreprocessorOpts.PrecompiledPreambleBytes.first = 0; |
2259 | 646 | PreprocessorOpts.PrecompiledPreambleBytes.second = false; |
2260 | 646 | } |
2261 | | |
2262 | | // Disable the preprocessing record if modules are not enabled. |
2263 | 721 | if (!Clang->getLangOpts().Modules) |
2264 | 707 | PreprocessorOpts.DetailedRecord = false; |
2265 | | |
2266 | 721 | std::unique_ptr<SyntaxOnlyAction> Act; |
2267 | 721 | Act.reset(new SyntaxOnlyAction); |
2268 | 721 | if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) { |
2269 | 721 | if (llvm::Error Err = Act->Execute()) { |
2270 | 0 | consumeError(std::move(Err)); // FIXME this drops errors on the floor. |
2271 | 0 | } |
2272 | 721 | Act->EndSourceFile(); |
2273 | 721 | } |
2274 | 721 | } |
2275 | | |
2276 | 62 | bool ASTUnit::Save(StringRef File) { |
2277 | 62 | if (HadModuleLoaderFatalFailure) |
2278 | 0 | return true; |
2279 | | |
2280 | | // Write to a temporary file and later rename it to the actual file, to avoid |
2281 | | // possible race conditions. |
2282 | 62 | SmallString<128> TempPath; |
2283 | 62 | TempPath = File; |
2284 | 62 | 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? |
2287 | | |
2288 | 62 | if (llvm::Error Err = llvm::writeFileAtomically( |
2289 | 62 | TempPath, File, [this](llvm::raw_ostream &Out) { |
2290 | 62 | return serialize(Out) ? llvm::make_error<llvm::StringError>( |
2291 | 0 | "ASTUnit serialization failed", |
2292 | 0 | llvm::inconvertibleErrorCode()) |
2293 | 62 | : llvm::Error::success(); |
2294 | 62 | })) { |
2295 | 0 | consumeError(std::move(Err)); |
2296 | 0 | return true; |
2297 | 0 | } |
2298 | 62 | return false; |
2299 | 62 | } |
2300 | | |
2301 | | static bool serializeUnit(ASTWriter &Writer, |
2302 | | SmallVectorImpl<char> &Buffer, |
2303 | | Sema &S, |
2304 | | bool hasErrors, |
2305 | 62 | raw_ostream &OS) { |
2306 | 62 | Writer.WriteAST(S, std::string(), nullptr, "", hasErrors); |
2307 | | |
2308 | | // Write the generated bitstream to "Out". |
2309 | 62 | if (!Buffer.empty()) |
2310 | 62 | OS.write(Buffer.data(), Buffer.size()); |
2311 | | |
2312 | 62 | return false; |
2313 | 62 | } |
2314 | | |
2315 | 62 | bool ASTUnit::serialize(raw_ostream &OS) { |
2316 | | // For serialization we are lenient if the errors were only warn-as-error kind. |
2317 | 62 | bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred(); |
2318 | | |
2319 | 62 | if (WriterData) |
2320 | 58 | return serializeUnit(WriterData->Writer, WriterData->Buffer, |
2321 | 58 | getSema(), hasErrors, OS); |
2322 | | |
2323 | 4 | SmallString<128> Buffer; |
2324 | 4 | llvm::BitstreamWriter Stream(Buffer); |
2325 | 4 | InMemoryModuleCache ModuleCache; |
2326 | 4 | ASTWriter Writer(Stream, Buffer, ModuleCache, {}); |
2327 | 4 | return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS); |
2328 | 62 | } |
2329 | | |
2330 | | using SLocRemap = ContinuousRangeMap<unsigned, int, 2>; |
2331 | | |
2332 | | void ASTUnit::TranslateStoredDiagnostics( |
2333 | | FileManager &FileMgr, |
2334 | | SourceManager &SrcMgr, |
2335 | | const SmallVectorImpl<StandaloneDiagnostic> &Diags, |
2336 | 263 | 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 | 263 | SmallVector<StoredDiagnostic, 4> Result; |
2342 | 263 | Result.reserve(Diags.size()); |
2343 | | |
2344 | 263 | for (const auto &SD : Diags) { |
2345 | | // Rebuild the StoredDiagnostic. |
2346 | 85 | if (SD.Filename.empty()) |
2347 | 0 | continue; |
2348 | 85 | auto FE = FileMgr.getFile(SD.Filename); |
2349 | 85 | if (!FE) |
2350 | 0 | continue; |
2351 | 85 | SourceLocation FileLoc; |
2352 | 85 | auto ItFileID = PreambleSrcLocCache.find(SD.Filename); |
2353 | 85 | if (ItFileID == PreambleSrcLocCache.end()) { |
2354 | 15 | FileID FID = SrcMgr.translateFile(*FE); |
2355 | 15 | FileLoc = SrcMgr.getLocForStartOfFile(FID); |
2356 | 15 | PreambleSrcLocCache[SD.Filename] = FileLoc; |
2357 | 70 | } else { |
2358 | 70 | FileLoc = ItFileID->getValue(); |
2359 | 70 | } |
2360 | | |
2361 | 85 | if (FileLoc.isInvalid()) |
2362 | 0 | continue; |
2363 | 85 | SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset); |
2364 | 85 | FullSourceLoc Loc(L, SrcMgr); |
2365 | | |
2366 | 85 | SmallVector<CharSourceRange, 4> Ranges; |
2367 | 85 | Ranges.reserve(SD.Ranges.size()); |
2368 | 85 | for (const auto &Range : SD.Ranges) { |
2369 | 38 | SourceLocation BL = FileLoc.getLocWithOffset(Range.first); |
2370 | 38 | SourceLocation EL = FileLoc.getLocWithOffset(Range.second); |
2371 | 38 | Ranges.push_back(CharSourceRange::getCharRange(BL, EL)); |
2372 | 38 | } |
2373 | | |
2374 | 85 | SmallVector<FixItHint, 2> FixIts; |
2375 | 85 | FixIts.reserve(SD.FixIts.size()); |
2376 | 85 | for (const auto &FixIt : SD.FixIts) { |
2377 | 9 | FixIts.push_back(FixItHint()); |
2378 | 9 | FixItHint &FH = FixIts.back(); |
2379 | 9 | FH.CodeToInsert = FixIt.CodeToInsert; |
2380 | 9 | SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first); |
2381 | 9 | SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second); |
2382 | 9 | FH.RemoveRange = CharSourceRange::getCharRange(BL, EL); |
2383 | 9 | } |
2384 | | |
2385 | 85 | Result.push_back(StoredDiagnostic(SD.Level, SD.ID, |
2386 | 85 | SD.Message, Loc, Ranges, FixIts)); |
2387 | 85 | } |
2388 | 263 | Result.swap(Out); |
2389 | 263 | } |
2390 | | |
2391 | 74.6k | void ASTUnit::addFileLevelDecl(Decl *D) { |
2392 | 74.6k | assert(D); |
2393 | | |
2394 | | // We only care about local declarations. |
2395 | 74.6k | if (D->isFromASTFile()) |
2396 | 6 | return; |
2397 | | |
2398 | 74.6k | SourceManager &SM = *SourceMgr; |
2399 | 74.6k | SourceLocation Loc = D->getLocation(); |
2400 | 74.6k | if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc)74.1k ) |
2401 | 573 | return; |
2402 | | |
2403 | | // We only keep track of the file-level declarations of each file. |
2404 | 74.1k | if (!D->getLexicalDeclContext()->isFileContext()) |
2405 | 405 | return; |
2406 | | |
2407 | 73.7k | SourceLocation FileLoc = SM.getFileLoc(Loc); |
2408 | 73.7k | assert(SM.isLocalSourceLocation(FileLoc)); |
2409 | 0 | FileID FID; |
2410 | 73.7k | unsigned Offset; |
2411 | 73.7k | std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); |
2412 | 73.7k | if (FID.isInvalid()) |
2413 | 0 | return; |
2414 | | |
2415 | 73.7k | std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID]; |
2416 | 73.7k | if (!Decls) |
2417 | 10.1k | Decls = std::make_unique<LocDeclsTy>(); |
2418 | | |
2419 | 73.7k | std::pair<unsigned, Decl *> LocDecl(Offset, D); |
2420 | | |
2421 | 73.7k | if (Decls->empty() || Decls->back().first <= Offset63.5k ) { |
2422 | 73.5k | Decls->push_back(LocDecl); |
2423 | 73.5k | return; |
2424 | 73.5k | } |
2425 | | |
2426 | 186 | LocDeclsTy::iterator I = |
2427 | 186 | llvm::upper_bound(*Decls, LocDecl, llvm::less_first()); |
2428 | | |
2429 | 186 | Decls->insert(I, LocDecl); |
2430 | 186 | } |
2431 | | |
2432 | | void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length, |
2433 | 9.54k | SmallVectorImpl<Decl *> &Decls) { |
2434 | 9.54k | if (File.isInvalid()) |
2435 | 0 | return; |
2436 | | |
2437 | 9.54k | if (SourceMgr->isLoadedFileID(File)) { |
2438 | 9.16k | assert(Ctx->getExternalSource() && "No external source!"); |
2439 | 0 | return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length, |
2440 | 9.16k | Decls); |
2441 | 9.16k | } |
2442 | | |
2443 | 385 | FileDeclsTy::iterator I = FileDecls.find(File); |
2444 | 385 | if (I == FileDecls.end()) |
2445 | 20 | return; |
2446 | | |
2447 | 365 | LocDeclsTy &LocDecls = *I->second; |
2448 | 365 | if (LocDecls.empty()) |
2449 | 0 | return; |
2450 | | |
2451 | 365 | LocDeclsTy::iterator BeginIt = |
2452 | 1.25k | llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) { |
2453 | 1.25k | return LD.first < Offset; |
2454 | 1.25k | }); |
2455 | 365 | if (BeginIt != LocDecls.begin()) |
2456 | 293 | --BeginIt; |
2457 | | |
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 | 373 | while (BeginIt != LocDecls.begin() && |
2462 | 373 | BeginIt->second->isTopLevelDeclInObjCContainer()272 ) |
2463 | 8 | --BeginIt; |
2464 | | |
2465 | 365 | LocDeclsTy::iterator EndIt = llvm::upper_bound( |
2466 | 365 | LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr), |
2467 | 365 | llvm::less_first()); |
2468 | 365 | if (EndIt != LocDecls.end()) |
2469 | 257 | ++EndIt; |
2470 | | |
2471 | 1.30k | for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt938 ) |
2472 | 938 | Decls.push_back(DIt->second); |
2473 | 365 | } |
2474 | | |
2475 | | SourceLocation ASTUnit::getLocation(const FileEntry *File, |
2476 | 9.58k | unsigned Line, unsigned Col) const { |
2477 | 9.58k | const SourceManager &SM = getSourceManager(); |
2478 | 9.58k | SourceLocation Loc = SM.translateFileLineCol(File, Line, Col); |
2479 | 9.58k | return SM.getMacroArgExpandedLocation(Loc); |
2480 | 9.58k | } |
2481 | | |
2482 | | SourceLocation ASTUnit::getLocation(const FileEntry *File, |
2483 | 0 | unsigned Offset) const { |
2484 | 0 | const SourceManager &SM = getSourceManager(); |
2485 | 0 | SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1); |
2486 | 0 | return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset)); |
2487 | 0 | } |
2488 | | |
2489 | | /// If \arg Loc is a loaded location from the preamble, returns |
2490 | | /// the corresponding local location of the main file, otherwise it returns |
2491 | | /// \arg Loc. |
2492 | 500k | SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const { |
2493 | 500k | FileID PreambleID; |
2494 | 500k | if (SourceMgr) |
2495 | 500k | PreambleID = SourceMgr->getPreambleFileID(); |
2496 | | |
2497 | 500k | if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid()16.8k ) |
2498 | 483k | return Loc; |
2499 | | |
2500 | 16.8k | unsigned Offs; |
2501 | 16.8k | if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size314 ) { |
2502 | 314 | SourceLocation FileLoc |
2503 | 314 | = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID()); |
2504 | 314 | return FileLoc.getLocWithOffset(Offs); |
2505 | 314 | } |
2506 | | |
2507 | 16.4k | return Loc; |
2508 | 16.8k | } |
2509 | | |
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 | 86.8k | SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const { |
2514 | 86.8k | FileID PreambleID; |
2515 | 86.8k | if (SourceMgr) |
2516 | 86.8k | PreambleID = SourceMgr->getPreambleFileID(); |
2517 | | |
2518 | 86.8k | if (Loc.isInvalid() || !Preamble19.3k || PreambleID.isInvalid()363 ) |
2519 | 86.4k | return Loc; |
2520 | | |
2521 | 363 | unsigned Offs; |
2522 | 363 | if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) && |
2523 | 363 | Offs < Preamble->getBounds().Size225 ) { |
2524 | 72 | SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID); |
2525 | 72 | return FileLoc.getLocWithOffset(Offs); |
2526 | 72 | } |
2527 | | |
2528 | 291 | return Loc; |
2529 | 363 | } |
2530 | | |
2531 | 9.59k | bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const { |
2532 | 9.59k | FileID FID; |
2533 | 9.59k | if (SourceMgr) |
2534 | 9.59k | FID = SourceMgr->getPreambleFileID(); |
2535 | | |
2536 | 9.59k | if (Loc.isInvalid() || FID.isInvalid()) |
2537 | 9.45k | return false; |
2538 | | |
2539 | 141 | return SourceMgr->isInFileID(Loc, FID); |
2540 | 9.59k | } |
2541 | | |
2542 | 29 | bool ASTUnit::isInMainFileID(SourceLocation Loc) const { |
2543 | 29 | FileID FID; |
2544 | 29 | if (SourceMgr) |
2545 | 29 | FID = SourceMgr->getMainFileID(); |
2546 | | |
2547 | 29 | if (Loc.isInvalid() || FID.isInvalid()28 ) |
2548 | 1 | return false; |
2549 | | |
2550 | 28 | return SourceMgr->isInFileID(Loc, FID); |
2551 | 29 | } |
2552 | | |
2553 | 7 | SourceLocation ASTUnit::getEndOfPreambleFileID() const { |
2554 | 7 | FileID FID; |
2555 | 7 | if (SourceMgr) |
2556 | 7 | FID = SourceMgr->getPreambleFileID(); |
2557 | | |
2558 | 7 | if (FID.isInvalid()) |
2559 | 0 | return {}; |
2560 | | |
2561 | 7 | return SourceMgr->getLocForEndOfFile(FID); |
2562 | 7 | } |
2563 | | |
2564 | 9 | SourceLocation ASTUnit::getStartOfMainFileID() const { |
2565 | 9 | FileID FID; |
2566 | 9 | if (SourceMgr) |
2567 | 9 | FID = SourceMgr->getMainFileID(); |
2568 | | |
2569 | 9 | if (FID.isInvalid()) |
2570 | 0 | return {}; |
2571 | | |
2572 | 9 | return SourceMgr->getLocForStartOfFile(FID); |
2573 | 9 | } |
2574 | | |
2575 | | llvm::iterator_range<PreprocessingRecord::iterator> |
2576 | 9 | ASTUnit::getLocalPreprocessingEntities() const { |
2577 | 9 | if (isMainFileAST()) { |
2578 | 9 | serialization::ModuleFile & |
2579 | 9 | Mod = Reader->getModuleManager().getPrimaryModule(); |
2580 | 9 | return Reader->getModulePreprocessedEntities(Mod); |
2581 | 9 | } |
2582 | | |
2583 | 0 | if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) |
2584 | 0 | return llvm::make_range(PPRec->local_begin(), PPRec->local_end()); |
2585 | | |
2586 | 0 | return llvm::make_range(PreprocessingRecord::iterator(), |
2587 | 0 | PreprocessingRecord::iterator()); |
2588 | 0 | } |
2589 | | |
2590 | 11 | bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) { |
2591 | 11 | if (isMainFileAST()) { |
2592 | 11 | serialization::ModuleFile & |
2593 | 11 | Mod = Reader->getModuleManager().getPrimaryModule(); |
2594 | 66 | for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) { |
2595 | 66 | if (!Fn(context, D)) |
2596 | 0 | return false; |
2597 | 66 | } |
2598 | | |
2599 | 11 | return true; |
2600 | 11 | } |
2601 | | |
2602 | 0 | for (ASTUnit::top_level_iterator TL = top_level_begin(), |
2603 | 0 | TLEnd = top_level_end(); |
2604 | 0 | TL != TLEnd; ++TL) { |
2605 | 0 | if (!Fn(context, *TL)) |
2606 | 0 | return false; |
2607 | 0 | } |
2608 | | |
2609 | 0 | return true; |
2610 | 0 | } |
2611 | | |
2612 | 9 | const FileEntry *ASTUnit::getPCHFile() { |
2613 | 9 | if (!Reader) |
2614 | 0 | return nullptr; |
2615 | | |
2616 | 9 | serialization::ModuleFile *Mod = nullptr; |
2617 | 13 | Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) { |
2618 | 13 | switch (M.Kind) { |
2619 | 4 | case serialization::MK_ImplicitModule: |
2620 | 4 | case serialization::MK_ExplicitModule: |
2621 | 4 | case serialization::MK_PrebuiltModule: |
2622 | 4 | return true; // skip dependencies. |
2623 | 0 | case serialization::MK_PCH: |
2624 | 0 | Mod = &M; |
2625 | 0 | return true; // found it. |
2626 | 0 | case serialization::MK_Preamble: |
2627 | 0 | return false; // look in dependencies. |
2628 | 9 | case serialization::MK_MainFile: |
2629 | 9 | return false; // look in dependencies. |
2630 | 13 | } |
2631 | | |
2632 | 0 | return true; |
2633 | 13 | }); |
2634 | 9 | if (Mod) |
2635 | 0 | return Mod->File; |
2636 | | |
2637 | 9 | return nullptr; |
2638 | 9 | } |
2639 | | |
2640 | 9 | bool ASTUnit::isModuleFile() const { |
2641 | 9 | return isMainFileAST() && getLangOpts().isCompilingModule(); |
2642 | 9 | } |
2643 | | |
2644 | 15 | InputKind ASTUnit::getInputKind() const { |
2645 | 15 | auto &LangOpts = getLangOpts(); |
2646 | | |
2647 | 15 | Language Lang; |
2648 | 15 | if (LangOpts.OpenCL) |
2649 | 0 | Lang = Language::OpenCL; |
2650 | 15 | else if (LangOpts.CUDA) |
2651 | 0 | Lang = Language::CUDA; |
2652 | 15 | else if (LangOpts.RenderScript) |
2653 | 0 | Lang = Language::RenderScript; |
2654 | 15 | else if (LangOpts.CPlusPlus) |
2655 | 11 | Lang = LangOpts.ObjC ? Language::ObjCXX0 : Language::CXX; |
2656 | 4 | else |
2657 | 4 | Lang = LangOpts.ObjC ? Language::ObjC : Language::C0 ; |
2658 | | |
2659 | 15 | InputKind::Format Fmt = InputKind::Source; |
2660 | 15 | if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap) |
2661 | 13 | Fmt = InputKind::ModuleMap; |
2662 | | |
2663 | | // We don't know if input was preprocessed. Assume not. |
2664 | 15 | bool PP = false; |
2665 | | |
2666 | 15 | return InputKind(Lang, Fmt, PP); |
2667 | 15 | } |
2668 | | |
2669 | | #ifndef NDEBUG |
2670 | 8.68k | ASTUnit::ConcurrencyState::ConcurrencyState() { |
2671 | 8.68k | Mutex = new std::recursive_mutex; |
2672 | 8.68k | } |
2673 | | |
2674 | 8.66k | ASTUnit::ConcurrencyState::~ConcurrencyState() { |
2675 | 8.66k | delete static_cast<std::recursive_mutex *>(Mutex); |
2676 | 8.66k | } |
2677 | | |
2678 | 20.8k | void ASTUnit::ConcurrencyState::start() { |
2679 | 20.8k | bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock(); |
2680 | 20.8k | assert(acquired && "Concurrent access to ASTUnit!"); |
2681 | 20.8k | } |
2682 | | |
2683 | 20.8k | void ASTUnit::ConcurrencyState::finish() { |
2684 | 20.8k | static_cast<std::recursive_mutex *>(Mutex)->unlock(); |
2685 | 20.8k | } |
2686 | | |
2687 | | #else // NDEBUG |
2688 | | |
2689 | | ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; } |
2690 | | ASTUnit::ConcurrencyState::~ConcurrencyState() {} |
2691 | | void ASTUnit::ConcurrencyState::start() {} |
2692 | | void ASTUnit::ConcurrencyState::finish() {} |
2693 | | |
2694 | | #endif // NDEBUG |