blob: 701f07f22e37f1017e465ccb6bbd547334047a11 [file] [log] [blame]
Eugene Zelenko4f233182018-03-22 00:53:26 +00001//===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000017#include "clang/AST/CommentCommandTraits.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclGroup.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/PrettyPrinter.h"
27#include "clang/AST/Type.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/AST/TypeOrdering.h"
29#include "clang/Basic/Diagnostic.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000030#include "clang/Basic/FileManager.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000034#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000035#include "clang/Basic/Module.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Basic/TargetInfo.h"
39#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000040#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000041#include "clang/Frontend/CompilerInstance.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000042#include "clang/Frontend/CompilerInvocation.h"
43#include "clang/Frontend/FrontendAction.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000044#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000045#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000046#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000047#include "clang/Frontend/MultiplexConsumer.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000048#include "clang/Frontend/PCHContainerOperations.h"
49#include "clang/Frontend/PrecompiledPreamble.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000050#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051#include "clang/Lex/HeaderSearch.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000052#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/Lexer.h"
54#include "clang/Lex/PPCallbacks.h"
55#include "clang/Lex/PreprocessingRecord.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000056#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000057#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000058#include "clang/Lex/Token.h"
59#include "clang/Sema/CodeCompleteConsumer.h"
60#include "clang/Sema/CodeCompleteOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000061#include "clang/Sema/Sema.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000062#include "clang/Serialization/ASTBitCodes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000063#include "clang/Serialization/ASTReader.h"
64#include "clang/Serialization/ASTWriter.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000065#include "clang/Serialization/ContinuousRangeMap.h"
66#include "clang/Serialization/Module.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000067#include "llvm/ADT/ArrayRef.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000068#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/IntrusiveRefCntPtr.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/STLExtras.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"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000077#include "llvm/ADT/StringSet.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000078#include "llvm/ADT/Twine.h"
79#include "llvm/ADT/iterator_range.h"
80#include "llvm/Bitcode/BitstreamWriter.h"
81#include "llvm/Support/Allocator.h"
82#include "llvm/Support/Casting.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000083#include "llvm/Support/CrashRecoveryContext.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000084#include "llvm/Support/DJB.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000085#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/ErrorOr.h"
87#include "llvm/Support/FileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000089#include "llvm/Support/Mutex.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000090#include "llvm/Support/Timer.h"
91#include "llvm/Support/raw_ostream.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000092#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000093#include <atomic>
Eugene Zelenko4f233182018-03-22 00:53:26 +000094#include <cassert>
95#include <cstdint>
Zhongxing Xu318e4032010-07-23 02:15:08 +000096#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000097#include <cstdlib>
Eugene Zelenko4f233182018-03-22 00:53:26 +000098#include <memory>
99#include <string>
100#include <tuple>
101#include <utility>
102#include <vector>
Hans Wennborgdcfba332015-10-06 23:40:43 +0000103
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000104using namespace clang;
105
Douglas Gregor16896c42010-10-28 15:44:59 +0000106using llvm::TimeRecord;
107
108namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000109
Douglas Gregor16896c42010-10-28 15:44:59 +0000110 class SimpleTimer {
111 bool WantTiming;
112 TimeRecord Start;
113 std::string Output;
114
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000115 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +0000116 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +0000117 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000118 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +0000119 }
120
Douglas Gregor16896c42010-10-28 15:44:59 +0000121 ~SimpleTimer() {
122 if (WantTiming) {
123 TimeRecord Elapsed = TimeRecord::getCurrentTime();
124 Elapsed -= Start;
125 llvm::errs() << Output << ':';
126 Elapsed.print(Elapsed, llvm::errs());
127 llvm::errs() << '\n';
128 }
129 }
Eugene Zelenko4f233182018-03-22 00:53:26 +0000130
131 void setOutput(const Twine &Output) {
132 if (WantTiming)
133 this->Output = Output.str();
134 }
Douglas Gregor16896c42010-10-28 15:44:59 +0000135 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +0000136
Eugene Zelenko4f233182018-03-22 00:53:26 +0000137} // namespace
Ilya Biryukovaf69e402017-05-23 11:37:52 +0000138
Eugene Zelenko4f233182018-03-22 00:53:26 +0000139template <class T>
140static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
141 if (!Val)
142 return nullptr;
143 return std::move(*Val);
144}
145
146template <class T>
147static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
148 if (!Val)
149 return false;
150 Output = std::move(*Val);
151 return true;
152}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000154/// Get a source buffer for \p MainFilePath, handling all file-to-file
Ilya Biryukov200b3282017-06-21 10:24:58 +0000155/// and file-to-buffer remappings inside \p Invocation.
156static std::unique_ptr<llvm::MemoryBuffer>
157getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
158 vfs::FileSystem *VFS,
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000159 StringRef FilePath,
160 bool isVolatile) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000161 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
Ted Kremenekbd307a52011-10-27 19:44:25 +0000162
Ilya Biryukov200b3282017-06-21 10:24:58 +0000163 // Try to determine if the main file has been remapped, either from the
164 // command line (to another file) or directly through the compiler
165 // invocation (to a memory buffer).
166 llvm::MemoryBuffer *Buffer = nullptr;
167 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
168 auto FileStatus = VFS->status(FilePath);
169 if (FileStatus) {
170 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000171
Ilya Biryukov200b3282017-06-21 10:24:58 +0000172 // Check whether there is a file-file remapping of the main file
173 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
174 std::string MPath(RF.first);
175 auto MPathStatus = VFS->status(MPath);
176 if (MPathStatus) {
177 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
178 if (MainFileID == MID) {
179 // We found a remapping. Try to load the resulting, remapped source.
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000180 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000181 if (!BufferOwner)
182 return nullptr;
183 }
184 }
185 }
186
187 // Check whether there is a file-buffer remapping. It supercedes the
188 // file-file remapping.
189 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
190 std::string MPath(RB.first);
191 auto MPathStatus = VFS->status(MPath);
192 if (MPathStatus) {
193 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
194 if (MainFileID == MID) {
195 // We found a remapping.
196 BufferOwner.reset();
197 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
198 }
199 }
200 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000201 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000202
Ilya Biryukov200b3282017-06-21 10:24:58 +0000203 // If the main source file was not remapped, load it now.
204 if (!Buffer && !BufferOwner) {
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000205 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000206 if (!BufferOwner)
207 return nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000208 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000209
Ilya Biryukov200b3282017-06-21 10:24:58 +0000210 if (BufferOwner)
211 return BufferOwner;
212 if (!Buffer)
213 return nullptr;
214 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000215}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000216
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000217struct ASTUnit::ASTWriterData {
218 SmallString<128> Buffer;
219 llvm::BitstreamWriter Stream;
220 ASTWriter Writer;
221
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000222 ASTWriterData(MemoryBufferCache &PCMCache)
223 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000224};
225
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000226void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000227 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000228}
229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000230/// After failing to build a precompiled preamble (due to
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000231/// errors in the source that occurs in the preamble), the number of
232/// reparses during which we'll skip even trying to precompile the
233/// preamble.
234const unsigned DefaultPreambleRebuildInterval = 5;
235
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000236/// Tracks the number of ASTUnit objects that are currently active.
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000237///
238/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000239static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000240
Douglas Gregord03e8232010-04-05 21:10:19 +0000241ASTUnit::ASTUnit(bool _MainFileIsAST)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000242 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
243 ShouldCacheCodeCompletionResults(false),
244 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
245 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000246 if (getenv("LIBCLANG_OBJTRACKING"))
247 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000248}
Douglas Gregord03e8232010-04-05 21:10:19 +0000249
Daniel Dunbar764c0822009-12-01 09:51:01 +0000250ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000251 // If we loaded from an AST file, balance out the BeginSourceFile call.
252 if (MainFileIsAST && getDiagnostics().getClient()) {
253 getDiagnostics().getClient()->EndSourceFile();
254 }
255
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000256 clearFileLevelDecls();
257
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000258 // Free the buffers associated with remapped files. We are required to
259 // perform this operation here because we explicitly request that the
260 // compiler instance *not* free these buffers for each invocation of the
261 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000262 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000263 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000264 for (const auto &RB : PPOpts.RemappedFileBuffers)
265 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000266 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000267
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000268 ClearCachedCompletionResults();
269
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000270 if (getenv("LIBCLANG_OBJTRACKING"))
271 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000272}
273
David Blaikie41565462017-01-05 19:48:07 +0000274void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
275 this->PP = std::move(PP);
276}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000277
Adam Baloghe4192a82018-06-15 06:45:39 +0000278void ASTUnit::enableSourceFileDiagnostics() {
279 assert(getDiagnostics().getClient() && Ctx &&
280 "Bad context for source file");
281 getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
282}
283
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000284/// Determine the set of code-completion contexts in which this
Douglas Gregor39982192010-08-15 06:18:01 +0000285/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000286static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000287 const LangOptions &LangOpts,
288 bool &IsNestedNameSpecifier) {
289 IsNestedNameSpecifier = false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000290
Douglas Gregor39982192010-08-15 06:18:01 +0000291 if (isa<UsingShadowDecl>(ND))
George Burgess IV00f70bd2018-03-01 05:43:23 +0000292 ND = ND->getUnderlyingDecl();
Douglas Gregor39982192010-08-15 06:18:01 +0000293 if (!ND)
294 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000295
Richard Smith697cc9e2012-08-14 03:13:00 +0000296 uint64_t Contexts = 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000297 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
Erik Verbruggen51ee12a2017-09-08 09:31:13 +0000298 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
299 isa<TypeAliasTemplateDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000300 // Types can appear in these contexts.
301 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
303 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
304 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
305 | (1LL << CodeCompletionContext::CCC_Statement)
306 | (1LL << CodeCompletionContext::CCC_Type)
307 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000308
309 // In C++, types can appear in expressions contexts (for functional casts).
310 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000312
Douglas Gregor39982192010-08-15 06:18:01 +0000313 // In Objective-C, message sends can send interfaces. In Objective-C++,
314 // all types are available due to functional casts.
315 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000316 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000317
Douglas Gregor21325842011-07-07 16:03:39 +0000318 // In Objective-C, you can only be a subclass of another Objective-C class
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000319 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
320 // Objective-C interfaces can be used in a class property expression.
321 if (ID->getDefinition())
322 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Richard Smith697cc9e2012-08-14 03:13:00 +0000323 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000324 }
Douglas Gregor39982192010-08-15 06:18:01 +0000325
326 // Deal with tag names.
327 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000328 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000329
Douglas Gregor59cab552010-08-16 23:05:20 +0000330 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000331 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000332 IsNestedNameSpecifier = true;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000333 } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000334 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000335 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000336 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000337 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000338
Douglas Gregor39982192010-08-15 06:18:01 +0000339 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000340 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000341 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000342 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000343 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
344 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000345 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
346 | (1LL << CodeCompletionContext::CCC_Expression)
347 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
348 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000349 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000350 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000351 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000352 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000353 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000354 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000355
Douglas Gregor39982192010-08-15 06:18:01 +0000356 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000357 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000358 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000359
Douglas Gregor39982192010-08-15 06:18:01 +0000360 return Contexts;
361}
362
Douglas Gregorb14904c2010-08-13 22:48:40 +0000363void ASTUnit::CacheCodeCompletionResults() {
364 if (!TheSema)
365 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000366
Douglas Gregor16896c42010-10-28 15:44:59 +0000367 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000368 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000369
370 // Clear out the previous results.
371 ClearCachedCompletionResults();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000372
Douglas Gregorb14904c2010-08-13 22:48:40 +0000373 // Gather the set of global code completions.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000374 using Result = CodeCompletionResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000375 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000376 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000377 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000378 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000379 CCTUInfo, Results);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000380
Douglas Gregorb14904c2010-08-13 22:48:40 +0000381 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000382 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000383 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000384
Eugene Zelenko4f233182018-03-22 00:53:26 +0000385 for (auto &R : Results) {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000386 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000387 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000388 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000389 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000390 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000391 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000392 IncludeBriefCommentsInCodeCompletion);
393 CachedResult.ShowInContexts = getDeclShowContexts(
394 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
395 CachedResult.Priority = R.Priority;
396 CachedResult.Kind = R.CursorKind;
397 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000398
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000399 // Keep track of the type of this completion in an ASTContext-agnostic
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000400 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000401 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000402 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000403 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000404 CachedResult.Type = 0;
405 } else {
406 CanQualType CanUsageType
407 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
408 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
409
410 // Determine whether we have already seen this type. If so, we save
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000411 // ourselves the work of formatting the type string by using the
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000412 // temporary, CanQualType-based hash table to find the associated value.
413 unsigned &TypeValue = CompletionTypes[CanUsageType];
414 if (TypeValue == 0) {
415 TypeValue = CompletionTypes.size();
416 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
417 = TypeValue;
418 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000419
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000420 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000421 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000422
Douglas Gregor39982192010-08-15 06:18:01 +0000423 CachedCompletionResults.push_back(CachedResult);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000424
Douglas Gregor59cab552010-08-16 23:05:20 +0000425 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000426 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
427 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000428 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000429 uint64_t NNSContexts
430 = (1LL << CodeCompletionContext::CCC_TopLevel)
431 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
432 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
433 | (1LL << CodeCompletionContext::CCC_Statement)
434 | (1LL << CodeCompletionContext::CCC_Expression)
435 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
436 | (1LL << CodeCompletionContext::CCC_EnumTag)
437 | (1LL << CodeCompletionContext::CCC_UnionTag)
438 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
439 | (1LL << CodeCompletionContext::CCC_Type)
440 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
441 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000442
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000443 if (isa<NamespaceDecl>(R.Declaration) ||
444 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000445 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000446
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000447 if (unsigned RemainingContexts
Douglas Gregor59cab552010-08-16 23:05:20 +0000448 = NNSContexts & ~CachedResult.ShowInContexts) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000449 // If there any contexts where this completion can be a
450 // nested-name-specifier but isn't already an option, create a
Douglas Gregor59cab552010-08-16 23:05:20 +0000451 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000452 R.StartsNestedNameSpecifier = true;
453 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000454 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000455 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000456 CachedResult.ShowInContexts = RemainingContexts;
457 CachedResult.Priority = CCP_NestedNameSpecifier;
458 CachedResult.TypeClass = STC_Void;
459 CachedResult.Type = 0;
460 CachedCompletionResults.push_back(CachedResult);
461 }
462 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000463 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000464 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000465
Douglas Gregorb14904c2010-08-13 22:48:40 +0000466 case Result::RK_Keyword:
467 case Result::RK_Pattern:
468 // Ignore keywords and patterns; we don't care, since they are so
469 // easily regenerated.
470 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000471
Douglas Gregorb14904c2010-08-13 22:48:40 +0000472 case Result::RK_Macro: {
473 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000474 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000475 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000476 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000477 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000478 = (1LL << CodeCompletionContext::CCC_TopLevel)
479 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
480 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
481 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
482 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
483 | (1LL << CodeCompletionContext::CCC_Statement)
484 | (1LL << CodeCompletionContext::CCC_Expression)
485 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
486 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
487 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
488 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
489 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000490
491 CachedResult.Priority = R.Priority;
492 CachedResult.Kind = R.CursorKind;
493 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000494 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000495 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000496 CachedCompletionResults.push_back(CachedResult);
497 break;
498 }
499 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000500 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000501
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000502 // Save the current top-level hash value.
503 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000504}
505
506void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000507 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000508 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000509 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000510}
511
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000512namespace {
513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514/// Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000515/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000516class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000517 Preprocessor &PP;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000518 ASTContext *Context;
Richard Smith18934752017-06-06 00:32:01 +0000519 HeaderSearchOptions &HSOpts;
520 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000521 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000522 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000523 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000524 unsigned &Counter;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000525 bool InitializedLanguage = false;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000527public:
Richard Smithdbafb6c2017-06-29 23:23:46 +0000528 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
Richard Smith18934752017-06-06 00:32:01 +0000529 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
530 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000531 std::shared_ptr<TargetOptions> &TargetOpts,
532 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000533 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
534 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
Eugene Zelenko4f233182018-03-22 00:53:26 +0000535 Counter(Counter) {}
Mike Stump11289f42009-09-09 15:08:12 +0000536
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000537 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
538 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000539 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000540 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000541
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000542 LangOpt = LangOpts;
543 InitializedLanguage = true;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000544
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000545 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000546 return false;
547 }
Mike Stump11289f42009-09-09 15:08:12 +0000548
Eugene Zelenko4f233182018-03-22 00:53:26 +0000549 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
550 StringRef SpecificModuleCachePath,
551 bool Complain) override {
Richard Smith18934752017-06-06 00:32:01 +0000552 this->HSOpts = HSOpts;
553 return false;
554 }
555
Eugene Zelenko4f233182018-03-22 00:53:26 +0000556 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
557 std::string &SuggestedPredefines) override {
Richard Smith18934752017-06-06 00:32:01 +0000558 this->PPOpts = PPOpts;
559 return false;
560 }
561
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000562 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
563 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000564 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000565 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000566 return false;
Alp Toker80758082014-07-06 05:26:44 +0000567
568 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
569 Target =
570 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000571
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000572 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000573 return false;
574 }
Mike Stump11289f42009-09-09 15:08:12 +0000575
Craig Topperafa7cb32014-03-13 06:07:04 +0000576 void ReadCounter(const serialization::ModuleFile &M,
577 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000578 Counter = Value;
579 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000580
581private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000582 void updated() {
583 if (!Target || !InitializedLanguage)
584 return;
585
586 // Inform the target of the language options.
587 //
588 // FIXME: We shouldn't need to do this, the target should be immutable once
589 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000590 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000591
592 // Initialize the preprocessor.
593 PP.Initialize(*Target);
594
Richard Smithdbafb6c2017-06-29 23:23:46 +0000595 if (!Context)
596 return;
597
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000598 // Initialize the ASTContext
Richard Smithdbafb6c2017-06-29 23:23:46 +0000599 Context->InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000600
Vedant Kumarfd9fad92017-08-25 18:07:03 +0000601 // Adjust printing policy based on language options.
602 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
603
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000604 // We didn't have access to the comment options when the ASTContext was
605 // constructed, so register them now.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000606 Context->getCommentCommandTraits().registerCommentOptions(
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000607 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000608 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000609};
610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000611/// Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000612class StoredDiagnosticConsumer : public DiagnosticConsumer {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000613 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
614 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000615 const LangOptions *LangOpts = nullptr;
616 SourceManager *SourceMgr = nullptr;
Douglas Gregor6b930962013-05-03 22:58:43 +0000617
Douglas Gregor33cdd812010-02-18 18:08:43 +0000618public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000619 StoredDiagnosticConsumer(
620 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
621 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000622 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000623 assert((StoredDiags || StandaloneDiags) &&
624 "No output collections were passed to StoredDiagnosticConsumer.");
625 }
Douglas Gregor6b930962013-05-03 22:58:43 +0000626
Craig Topperafa7cb32014-03-13 06:07:04 +0000627 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000628 const Preprocessor *PP = nullptr) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000629 this->LangOpts = &LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000630 if (PP)
631 SourceMgr = &PP->getSourceManager();
632 }
633
Craig Topperafa7cb32014-03-13 06:07:04 +0000634 void HandleDiagnostic(DiagnosticsEngine::Level Level,
635 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000636};
637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000638/// RAII object that optionally captures diagnostics, if
Douglas Gregor33cdd812010-02-18 18:08:43 +0000639/// there is no diagnostic client to capture them already.
640class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000641 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000642 StoredDiagnosticConsumer Client;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000643 DiagnosticConsumer *PreviousClient = nullptr;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000644 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000645
646public:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000647 CaptureDroppedDiagnostics(
648 bool RequestCapture, DiagnosticsEngine &Diags,
649 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
650 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
651 : Diags(Diags), Client(StoredDiags, StandaloneDiags) {
Craig Topper49a27902014-05-22 04:46:25 +0000652 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000653 OwningPreviousClient = Diags.takeClient();
654 PreviousClient = Diags.getClient();
655 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000656 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000657 }
658
659 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000660 if (Diags.getClient() == &Client)
661 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000662 }
663};
664
Eugene Zelenko4f233182018-03-22 00:53:26 +0000665} // namespace
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000666
Ilya Biryukov200b3282017-06-21 10:24:58 +0000667static ASTUnit::StandaloneDiagnostic
668makeStandaloneDiagnostic(const LangOptions &LangOpts,
669 const StoredDiagnostic &InDiag);
670
David Blaikief18d91a2011-09-26 00:01:39 +0000671void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000672 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000673 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000674 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000675
Douglas Gregor6b930962013-05-03 22:58:43 +0000676 // Only record the diagnostic if it's part of the source manager we know
677 // about. This effectively drops diagnostics from modules we're building.
678 // FIXME: In the long run, ee don't want to drop source managers from modules.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000679 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
680 StoredDiagnostic *ResultDiag = nullptr;
681 if (StoredDiags) {
682 StoredDiags->emplace_back(Level, Info);
683 ResultDiag = &StoredDiags->back();
684 }
685
686 if (StandaloneDiags) {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000687 llvm::Optional<StoredDiagnostic> StoredDiag = None;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000688 if (!ResultDiag) {
689 StoredDiag.emplace(Level, Info);
690 ResultDiag = StoredDiag.getPointer();
691 }
692 StandaloneDiags->push_back(
693 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
694 }
695 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000696}
697
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000698IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
699 return Reader;
700}
701
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000702ASTMutationListener *ASTUnit::getASTMutationListener() {
703 if (WriterData)
704 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000705 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000706}
707
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000708ASTDeserializationListener *ASTUnit::getDeserializationListener() {
709 if (WriterData)
710 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000711 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000712}
713
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000714std::unique_ptr<llvm::MemoryBuffer>
715ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000716 assert(FileMgr);
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000717 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
Benjamin Kramera8857962014-10-26 22:44:13 +0000718 if (Buffer)
719 return std::move(*Buffer);
720 if (ErrorStr)
721 *ErrorStr = Buffer.getError().message();
722 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000723}
724
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000725/// Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000726void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000727 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000728 assert(Diags.get() && "no DiagnosticsEngine was provided");
729 if (CaptureDiagnostics)
Ilya Biryukov200b3282017-06-21 10:24:58 +0000730 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000731}
732
David Blaikie6f7382d2014-08-10 19:08:04 +0000733std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000734 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Richard Smithdbafb6c2017-06-29 23:23:46 +0000735 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000736 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
737 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
738 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
739 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000740 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000741
742 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000743 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
744 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000745 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +0000746 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +0000747 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000748
Justin Bognerdbbcb112014-10-14 23:36:06 +0000749 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000750
Richard Smithab755972017-06-05 18:10:11 +0000751 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000752 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000753 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000754 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000755 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
756 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000757 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000758 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000759 AST->getFileManager(),
760 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000761 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000762 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000763 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000764 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000765 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000766 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000767 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000768 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000769 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000770
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000771 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000772 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000773
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000774 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000775
David Blaikie6f7382d2014-08-10 19:08:04 +0000776 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000777 unsigned Counter;
778
David Blaikie41565462017-01-05 19:48:07 +0000779 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000780 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Richard Smith5d2ed482017-06-09 19:22:32 +0000781 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000782 /*IILookup=*/nullptr,
783 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000784 Preprocessor &PP = *AST->PP;
785
Richard Smithdbafb6c2017-06-29 23:23:46 +0000786 if (ToLoad >= LoadASTOnly)
787 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
788 PP.getIdentifierTable(), PP.getSelectorTable(),
789 PP.getBuiltinInfo());
Douglas Gregor83297df2011-09-01 23:39:15 +0000790
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000791 bool disableValid = false;
792 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
793 disableValid = true;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000794 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, {},
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000795 /*isysroot=*/"",
796 /*DisableValidation=*/disableValid,
797 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000798
David Blaikie2721c322014-08-10 16:54:39 +0000799 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000800 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
Richard Smith18934752017-06-06 00:32:01 +0000801 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000802
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000803 // Attach the AST reader to the AST context as an external AST
804 // source, so that declarations will be deserialized from the
805 // AST file as needed.
806 // We need the external source to be set up before we read the AST, because
807 // eagerly-deserialized declarations may use it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000808 if (AST->Ctx)
809 AST->Ctx->setExternalSource(AST->Reader);
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000810
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000811 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000812 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000813 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000814 break;
Mike Stump11289f42009-09-09 15:08:12 +0000815
Sebastian Redl2c499f62010-08-18 23:56:43 +0000816 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000817 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000818 case ASTReader::OutOfDate:
819 case ASTReader::VersionMismatch:
820 case ASTReader::ConfigurationMismatch:
821 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000822 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000823 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000824 }
Mike Stump11289f42009-09-09 15:08:12 +0000825
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000826 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000827
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000828 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000830 // Create an AST consumer, even though it isn't used.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000831 if (ToLoad >= LoadASTOnly)
832 AST->Consumer.reset(new ASTConsumer);
833
Sebastian Redl2c499f62010-08-18 23:56:43 +0000834 // Create a semantic analysis object and tell the AST reader about it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000835 if (ToLoad >= LoadEverything) {
836 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
837 AST->TheSema->Initialize();
838 AST->Reader->InitializeSema(*AST->TheSema);
839 }
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000840
Douglas Gregor6b930962013-05-03 22:58:43 +0000841 // Tell the diagnostic client that we have started a source file.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000842 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
Douglas Gregor6b930962013-05-03 22:58:43 +0000843
David Blaikie6f7382d2014-08-10 19:08:04 +0000844 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000845}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000847/// Add the given macro to the hash of all top-level entities.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000848static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000849 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000850}
851
Eugene Zelenko4f233182018-03-22 00:53:26 +0000852namespace {
853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000854/// Preprocessor callback class that updates a hash value with the names
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000855/// of all macros that have been defined by the translation unit.
856class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
857 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000858
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000859public:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000860 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000861
862 void MacroDefined(const Token &MacroNameTok,
863 const MacroDirective *MD) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000864 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000865 }
866};
867
Eugene Zelenko4f233182018-03-22 00:53:26 +0000868} // namespace
869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000870/// Add the given declaration to the hash of all top-level entities.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000871static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000872 if (!D)
873 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000874
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000875 DeclContext *DC = D->getDeclContext();
876 if (!DC)
877 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000878
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000879 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
880 return;
881
Eugene Zelenko4f233182018-03-22 00:53:26 +0000882 if (const auto *ND = dyn_cast<NamedDecl>(D)) {
883 if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000884 // For an unscoped enum include the enumerators in the hash since they
885 // enter the top-level namespace.
886 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000887 for (const auto *EI : EnumD->enumerators()) {
888 if (EI->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000889 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000890 }
891 }
892 }
893
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000894 if (ND->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000895 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000896 else if (DeclarationName Name = ND->getDeclName()) {
897 std::string NameStr = Name.getAsString();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000898 Hash = llvm::djbHash(NameStr, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000899 }
900 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000901 }
902
Eugene Zelenko4f233182018-03-22 00:53:26 +0000903 if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
904 if (const Module *Mod = ImportD->getImportedModule()) {
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000905 std::string ModName = Mod->getFullModuleName();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000906 Hash = llvm::djbHash(ModName, Hash);
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000907 }
908 return;
909 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000910}
911
Eugene Zelenko4f233182018-03-22 00:53:26 +0000912namespace {
913
Daniel Dunbar644dca02009-12-04 08:17:33 +0000914class TopLevelDeclTrackerConsumer : public ASTConsumer {
915 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000916 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000917
Daniel Dunbar644dca02009-12-04 08:17:33 +0000918public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000919 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000920 : Unit(_Unit), Hash(Hash) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000921 Hash = 0;
922 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000923
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000924 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000925 if (!D)
926 return;
927
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000928 // FIXME: Currently ObjC method declarations are incorrectly being
929 // reported as top-level declarations, even though their DeclContext
930 // is the containing ObjC @interface/@implementation. This is a
931 // fundamental problem in the parser right now.
932 if (isa<ObjCMethodDecl>(D))
933 return;
934
935 AddTopLevelDeclarationToHash(D, Hash);
936 Unit.addTopLevelDecl(D);
937
938 handleFileLevelDecl(D);
939 }
940
941 void handleFileLevelDecl(Decl *D) {
942 Unit.addFileLevelDecl(D);
Eugene Zelenko4f233182018-03-22 00:53:26 +0000943 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000944 for (auto *I : NSD->decls())
945 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000946 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000947 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000948
Craig Topperafa7cb32014-03-13 06:07:04 +0000949 bool HandleTopLevelDecl(DeclGroupRef D) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000950 for (auto *TopLevelDecl : D)
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000951 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000952 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000953 }
954
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000955 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000956 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000957
Craig Topperafa7cb32014-03-13 06:07:04 +0000958 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000959 for (auto *TopLevelDecl : D)
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000960 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000961 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000962
Craig Topperafa7cb32014-03-13 06:07:04 +0000963 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000964 return Unit.getASTMutationListener();
965 }
966
Craig Topperafa7cb32014-03-13 06:07:04 +0000967 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000968 return Unit.getDeserializationListener();
969 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000970};
971
972class TopLevelDeclTrackerAction : public ASTFrontendAction {
973public:
974 ASTUnit &Unit;
975
David Blaikie6beb6aa2014-08-10 19:56:51 +0000976 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
977 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000978 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000979 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
980 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000981 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
982 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000983 }
984
985public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000986 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
987
Craig Topperafa7cb32014-03-13 06:07:04 +0000988 bool hasCodeCompletionSupport() const override { return false; }
Eugene Zelenko4f233182018-03-22 00:53:26 +0000989
Craig Topperafa7cb32014-03-13 06:07:04 +0000990 TranslationUnitKind getTranslationUnitKind() override {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000991 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000992 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000993};
994
Ilya Biryukov200b3282017-06-21 10:24:58 +0000995class ASTUnitPreambleCallbacks : public PreambleCallbacks {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000996public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000997 unsigned getHash() const { return Hash; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000998
Ilya Biryukov200b3282017-06-21 10:24:58 +0000999 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001000
Ilya Biryukov200b3282017-06-21 10:24:58 +00001001 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1002 return std::move(TopLevelDeclIDs);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001003 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001004
Ilya Biryukov200b3282017-06-21 10:24:58 +00001005 void AfterPCHEmitted(ASTWriter &Writer) override {
1006 TopLevelDeclIDs.reserve(TopLevelDecls.size());
Eugene Zelenko4f233182018-03-22 00:53:26 +00001007 for (const auto *D : TopLevelDecls) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001008 // Invalid top-level decls may not have been serialized.
1009 if (D->isInvalidDecl())
1010 continue;
1011 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1012 }
1013 }
1014
1015 void HandleTopLevelDecl(DeclGroupRef DG) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +00001016 for (auto *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001017 // FIXME: Currently ObjC method declarations are incorrectly being
1018 // reported as top-level declarations, even though their DeclContext
1019 // is the containing ObjC @interface/@implementation. This is a
1020 // fundamental problem in the parser right now.
1021 if (isa<ObjCMethodDecl>(D))
1022 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001023 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001024 TopLevelDecls.push_back(D);
1025 }
1026 }
1027
Ilya Biryukov41e90bc2017-12-15 11:27:51 +00001028 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1029 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001030 }
Ilya Biryukov200b3282017-06-21 10:24:58 +00001031
1032private:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001033 unsigned Hash = 0;
1034 std::vector<Decl *> TopLevelDecls;
1035 std::vector<serialization::DeclID> TopLevelDeclIDs;
1036 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001037};
1038
Eugene Zelenko4f233182018-03-22 00:53:26 +00001039} // namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001040
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001041static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1042 return StoredDiag.getLocation().isValid();
1043}
1044
1045static void
1046checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001047 // Get rid of stored diagnostics except the ones from the driver which do not
1048 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001049 StoredDiags.erase(
1050 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1051 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001052}
1053
1054static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1055 StoredDiagnostics,
1056 SourceManager &SM) {
1057 // The stored diagnostic has the old source manager in it; update
1058 // the locations to refer into the new source manager. Since we've
1059 // been careful to make sure that the source manager's state
1060 // before and after are identical, so that we can reuse the source
1061 // location itself.
Eugene Zelenko4f233182018-03-22 00:53:26 +00001062 for (auto &SD : StoredDiagnostics) {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001063 if (SD.getLocation().isValid()) {
1064 FullSourceLoc Loc(SD.getLocation(), SM);
1065 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001066 }
1067 }
1068}
1069
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070/// Parse the source file into a translation unit using the given compiler
1071/// invocation, replacing the current translation unit.
1072///
1073/// \returns True if a failure occurred that causes the ASTUnit not to
1074/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001075bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001076 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1077 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001078 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001079 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001080
Ilya Biryukov417085a2017-11-16 16:25:01 +00001081 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1082 if (OverrideMainBuffer) {
1083 assert(Preamble &&
1084 "No preamble was built, but OverrideMainBuffer is not null");
1085 IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS;
1086 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1087 if (OldVFS != VFS && FileMgr) {
1088 assert(OldVFS == FileMgr->getVirtualFileSystem() &&
1089 "VFS passed to Parse and VFS in FileMgr are different");
1090 FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
1091 }
1092 }
1093
Daniel Dunbar764c0822009-12-01 09:51:01 +00001094 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001095 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001096 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001097 if (FileMgr && VFS) {
1098 assert(VFS == FileMgr->getVirtualFileSystem() &&
1099 "VFS passed to Parse and VFS in FileMgr are different");
1100 } else if (VFS) {
1101 Clang->setVirtualFileSystem(VFS);
1102 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103
1104 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001105 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1106 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001107
Ilya Biryukov417085a2017-11-16 16:25:01 +00001108 Clang->setInvocation(CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001109 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001110
Douglas Gregor8e984da2010-08-04 16:47:14 +00001111 // Set up diagnostics, capturing any diagnostics that would
1112 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001113 Clang->setDiagnostics(&getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001114
Daniel Dunbar764c0822009-12-01 09:51:01 +00001115 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001116 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001117 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001118 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001119 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001120
Daniel Dunbar764c0822009-12-01 09:51:01 +00001121 // Inform the target of the language options.
1122 //
1123 // FIXME: We shouldn't need to do this, the target should be immutable once
1124 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001125 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001126
Ted Kremenek84de4a12011-03-21 18:40:07 +00001127 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001128 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001129 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1130 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001131 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001132 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1133 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001134 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001135
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001136 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001137 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001138 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001139 if (!FileMgr) {
1140 Clang->createFileManager();
1141 FileMgr = &Clang->getFileManager();
1142 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001143
1144 ResetForParse();
1145
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001146 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1147 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001148 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001149 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001150 TopLevelDeclsInPreamble.clear();
1151 }
1152
Daniel Dunbar764c0822009-12-01 09:51:01 +00001153 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001154 Clang->setFileManager(&getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001155
Daniel Dunbar764c0822009-12-01 09:51:01 +00001156 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001157 Clang->setSourceManager(&getSourceManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001158
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001159 // If the main file has been overridden due to the use of a preamble,
1160 // make that override happen and introduce the preamble.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001161 if (OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001162 // The stored diagnostic has the old source manager in it; update
1163 // the locations to refer into the new source manager. Since we've
1164 // been careful to make sure that the source manager's state
1165 // before and after are identical, so that we can reuse the source
1166 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001167 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001168
1169 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001170 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001171 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001172
1173 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1174 new TopLevelDeclTrackerAction(*this));
1175
Ted Kremenek022a4902011-03-22 01:15:24 +00001176 // Recover resources if we crash before exiting this method.
1177 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1178 ActCleanup(Act.get());
1179
Douglas Gregor32fbe312012-01-20 16:28:04 +00001180 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001181 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001182
Richard Smith26b8f782016-03-25 21:46:44 +00001183 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001184 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1185 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001186 else
1187 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001188
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001189 if (!Act->Execute())
1190 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001191
1192 transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001193
Daniel Dunbar644dca02009-12-04 08:17:33 +00001194 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001195
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001196 FailedParseDiagnostics.clear();
1197
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001198 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001199
Daniel Dunbar764c0822009-12-01 09:51:01 +00001200error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001201 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001202 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001203
1204 // Keep the ownership of the data in the ASTUnit because the client may
1205 // want to see the diagnostics.
1206 transferASTDataFromCompilerInstance(*Clang);
1207 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001208 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001209 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001210 return true;
1211}
1212
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001213static std::pair<unsigned, unsigned>
1214makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1215 const LangOptions &LangOpts) {
1216 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1217 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1218 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1219 return std::make_pair(Offset, EndOffset);
1220}
1221
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001222static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1223 const LangOptions &LangOpts,
1224 const FixItHint &InFix) {
1225 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001226 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1227 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1228 LangOpts);
1229 OutFix.CodeToInsert = InFix.CodeToInsert;
1230 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001231 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001232}
1233
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001234static ASTUnit::StandaloneDiagnostic
1235makeStandaloneDiagnostic(const LangOptions &LangOpts,
1236 const StoredDiagnostic &InDiag) {
1237 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001238 OutDiag.ID = InDiag.getID();
1239 OutDiag.Level = InDiag.getLevel();
1240 OutDiag.Message = InDiag.getMessage();
1241 OutDiag.LocOffset = 0;
1242 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001243 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001244 const SourceManager &SM = InDiag.getLocation().getManager();
1245 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1246 OutDiag.Filename = SM.getFilename(FileLoc);
1247 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001248 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001249 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Eugene Zelenko4f233182018-03-22 00:53:26 +00001250 for (const auto &Range : InDiag.getRanges())
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001251 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
Eugene Zelenko4f233182018-03-22 00:53:26 +00001252 for (const auto &FixIt : InDiag.getFixIts())
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001253 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001254
1255 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001256}
1257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001258/// Attempt to build or re-use a precompiled preamble when (re-)parsing
Douglas Gregor4dde7492010-07-23 23:58:40 +00001259/// the source file.
1260///
1261/// This routine will compute the preamble of the main source file. If a
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001262/// non-trivial preamble is found, it will precompile that preamble into a
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263/// precompiled header so that the precompiled preamble can be used to reduce
1264/// reparsing time. If a precompiled preamble has already been constructed,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001265/// this routine will determine if it is still valid and, if so, avoid
Douglas Gregor4dde7492010-07-23 23:58:40 +00001266/// rebuilding the precompiled preamble.
1267///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001268/// \param AllowRebuild When true (the default), this routine is
1269/// allowed to rebuild the precompiled preamble if it is found to be
1270/// out-of-date.
1271///
1272/// \param MaxLines When non-zero, the maximum number of lines that
1273/// can occur within the preamble.
1274///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001275/// \returns If the precompiled preamble can be used, returns a newly-allocated
1276/// buffer that should be used in place of the main file when doing so.
1277/// Otherwise, returns a NULL pointer.
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001278std::unique_ptr<llvm::MemoryBuffer>
1279ASTUnit::getMainBufferWithPrecompiledPreamble(
1280 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001281 CompilerInvocation &PreambleInvocationIn,
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001282 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
1283 unsigned MaxLines) {
1284 auto MainFilePath =
Ilya Biryukov200b3282017-06-21 10:24:58 +00001285 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1286 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1287 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +00001288 MainFilePath, UserFilesAreVolatile);
Ilya Biryukov200b3282017-06-21 10:24:58 +00001289 if (!MainFileBuffer)
Craig Topper49a27902014-05-22 04:46:25 +00001290 return nullptr;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001291
Ilya Biryukov200b3282017-06-21 10:24:58 +00001292 PreambleBounds Bounds =
1293 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1294 MainFileBuffer.get(), MaxLines);
1295 if (!Bounds.Size)
1296 return nullptr;
Alp Toker1b070d22014-07-07 07:47:20 +00001297
Ilya Biryukov200b3282017-06-21 10:24:58 +00001298 if (Preamble) {
1299 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1300 VFS.get())) {
1301 // Okay! We can re-use the precompiled preamble.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001302
Ilya Biryukov200b3282017-06-21 10:24:58 +00001303 // Set the state of the diagnostic object to mimic its state
1304 // after parsing the preamble.
1305 getDiagnostics().Reset();
1306 ProcessWarningOptions(getDiagnostics(),
1307 PreambleInvocationIn.getDiagnosticOpts());
1308 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Alp Toker1b070d22014-07-07 07:47:20 +00001309
Ilya Biryukov200b3282017-06-21 10:24:58 +00001310 PreambleRebuildCounter = 1;
1311 return MainFileBuffer;
1312 } else {
1313 Preamble.reset();
1314 PreambleDiagnostics.clear();
1315 TopLevelDeclsInPreamble.clear();
Alex Lorenza44c4322018-03-12 19:36:29 +00001316 PreambleSrcLocCache.clear();
Ilya Biryukov200b3282017-06-21 10:24:58 +00001317 PreambleRebuildCounter = 1;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001318 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001319 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001320
1321 // If the preamble rebuild counter > 1, it's because we previously
1322 // failed to build a preamble and we're not yet ready to try
1323 // again. Decrement the counter and return a failure.
1324 if (PreambleRebuildCounter > 1) {
1325 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001326 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001327 }
1328
Ilya Biryukov200b3282017-06-21 10:24:58 +00001329 assert(!Preamble && "No Preamble should be stored at that point");
1330 // If we aren't allowed to rebuild the precompiled preamble, just
1331 // return now.
1332 if (!AllowRebuild)
Ben Langmuir8832c062014-04-15 18:16:25 +00001333 return nullptr;
1334
Ilya Biryukov200b3282017-06-21 10:24:58 +00001335 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1336 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001337 ASTUnitPreambleCallbacks Callbacks;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001338 {
1339 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1340 if (CaptureDiagnostics)
1341 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1342 &NewPreambleDiagsStandalone);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001343
Ilya Biryukov200b3282017-06-21 10:24:58 +00001344 // We did not previously compute a preamble, or it can't be reused anyway.
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001345 SimpleTimer PreambleTimer(WantTiming);
1346 PreambleTimer.setOutput("Precompiling preamble");
1347
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001348 const bool PreviousSkipFunctionBodies =
1349 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1350 if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1351 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1352
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001353 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1354 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1355 PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001356
1357 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1358 PreviousSkipFunctionBodies;
1359
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001360 if (NewPreamble) {
1361 Preamble = std::move(*NewPreamble);
1362 PreambleRebuildCounter = 1;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001363 } else {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001364 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1365 case BuildPreambleError::CouldntCreateTempFile:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001366 // Try again next time.
1367 PreambleRebuildCounter = 1;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001368 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001369 case BuildPreambleError::CouldntCreateTargetInfo:
1370 case BuildPreambleError::BeginSourceFileFailed:
1371 case BuildPreambleError::CouldntEmitPCH:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001372 // These erros are more likely to repeat, retry after some period.
1373 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001374 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001375 }
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001376 llvm_unreachable("unexpected BuildPreambleError");
Dmitri Gribenko47652522013-12-20 00:16:25 +00001377 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001378 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001379
Ilya Biryukov200b3282017-06-21 10:24:58 +00001380 assert(Preamble && "Preamble wasn't built");
1381
1382 TopLevelDecls.clear();
1383 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1384 PreambleTopLevelHashValue = Callbacks.getHash();
1385
1386 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1387
1388 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1389 StoredDiagnostics = std::move(NewPreambleDiags);
1390 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
Alp Toker1b070d22014-07-07 07:47:20 +00001391
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001392 // If the hash of top-level entities differs from the hash of the top-level
1393 // entities the last time we rebuilt the preamble, clear out the completion
1394 // cache.
1395 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1396 CompletionCacheTopLevelHashValue = 0;
1397 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1398 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001399
Ilya Biryukov200b3282017-06-21 10:24:58 +00001400 return MainFileBuffer;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001401}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001402
Douglas Gregore9db88f2010-08-03 19:06:41 +00001403void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001404 assert(Preamble && "Should only be called when preamble was built");
1405
Douglas Gregore9db88f2010-08-03 19:06:41 +00001406 std::vector<Decl *> Resolved;
1407 Resolved.reserve(TopLevelDeclsInPreamble.size());
1408 ExternalASTSource &Source = *getASTContext().getExternalSource();
Eugene Zelenko4f233182018-03-22 00:53:26 +00001409 for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001410 // Resolve the declaration ID to an actual declaration, possibly
1411 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001412 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001413 Resolved.push_back(D);
1414 }
1415 TopLevelDeclsInPreamble.clear();
1416 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1417}
1418
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001419void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001420 // Steal the created target, context, and preprocessor if they have been
1421 // created.
1422 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001423 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001424 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001425 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001426 if (CI.hasASTContext())
1427 Ctx = &CI.getASTContext();
1428 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001429 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001430 CI.setSourceManager(nullptr);
1431 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001432 if (CI.hasTarget())
1433 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001434 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001435 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001436}
1437
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001438StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001439 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1440 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1441 if (Input.isFile())
1442 return Input.getFile();
1443 else
1444 return Input.getBuffer()->getBufferIdentifier();
1445 }
1446
1447 if (SourceMgr) {
1448 if (const FileEntry *
1449 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1450 return FE->getName();
1451 }
1452
Eugene Zelenko4f233182018-03-22 00:53:26 +00001453 return {};
Douglas Gregor16896c42010-10-28 15:44:59 +00001454}
1455
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001456StringRef ASTUnit::getASTFileName() const {
1457 if (!isMainFileAST())
Eugene Zelenko4f233182018-03-22 00:53:26 +00001458 return {};
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001459
1460 serialization::ModuleFile &
1461 Mod = Reader->getModuleManager().getPrimaryModule();
1462 return Mod.FileName;
1463}
1464
David Blaikieea4395e2017-01-06 19:49:01 +00001465std::unique_ptr<ASTUnit>
1466ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1467 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1468 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1469 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001470 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001471 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1472 createVFSFromCompilerInvocation(*CI, *Diags);
David Blaikieea4395e2017-01-06 19:49:01 +00001473 AST->Diagnostics = Diags;
1474 AST->FileSystemOpts = CI->getFileSystemOpts();
1475 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001476 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001477 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1478 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1479 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001480 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001481
David Blaikieea4395e2017-01-06 19:49:01 +00001482 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001483}
1484
Ahmed Charlesb8984322014-03-07 20:03:18 +00001485ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001486 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001487 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001488 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001489 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001490 bool OnlyLocalDecls, bool CaptureDiagnostics,
1491 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1492 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1493 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001494 assert(CI && "A CompilerInvocation is required");
1495
Ahmed Charlesb8984322014-03-07 20:03:18 +00001496 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001497 ASTUnit *AST = Unit;
1498 if (!AST) {
1499 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001500 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001501 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001502 if (!AST)
1503 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001504 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001505
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001506 if (!ResourceFilesPath.empty()) {
1507 // Override the resources path.
1508 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1509 }
1510 AST->OnlyLocalDecls = OnlyLocalDecls;
1511 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001512 if (PrecompilePreambleAfterNParses > 0)
1513 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001514 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001515 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001516 AST->IncludeBriefCommentsInCodeCompletion
1517 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001518
1519 // Recover resources if we crash before exiting this method.
1520 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001521 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001522 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +00001523 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +00001524 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001525
1526 // We'll manage file buffers ourselves.
1527 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1528 CI->getFrontendOpts().DisableFree = false;
1529 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1530
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001531 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001532 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001533 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001534
1535 // Recover resources if we crash before exiting this method.
1536 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1537 CICleanup(Clang.get());
1538
David Blaikieea4395e2017-01-06 19:49:01 +00001539 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001540 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001541
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001542 // Set up diagnostics, capturing any diagnostics that would
1543 // otherwise be dropped.
1544 Clang->setDiagnostics(&AST->getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001545
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001546 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001547 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001548 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001549 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001550 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001551
1552 // Inform the target of the language options.
1553 //
1554 // FIXME: We shouldn't need to do this, the target should be immutable once
1555 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001556 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001557
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001558 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1559 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001560 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1561 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001562 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001563 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1564 InputKind::LLVM_IR &&
1565 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001566
1567 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001568 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001569 AST->Ctx = nullptr;
1570 AST->PP = nullptr;
1571 AST->Reader = nullptr;
1572
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001573 // Create a file manager object to provide access to and cache the filesystem.
1574 Clang->setFileManager(&AST->getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001575
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001576 // Create the source manager.
1577 Clang->setSourceManager(&AST->getSourceManager());
1578
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001579 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001580
Ahmed Charlesb8984322014-03-07 20:03:18 +00001581 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001582 if (!Act) {
1583 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1584 Act = TrackerAct.get();
1585 }
1586
1587 // Recover resources if we crash before exiting this method.
1588 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1589 ActCleanup(TrackerAct.get());
1590
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001591 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1592 AST->transferASTDataFromCompilerInstance(*Clang);
1593 if (OwnAST && ErrAST)
1594 ErrAST->swap(OwnAST);
1595
Craig Topper49a27902014-05-22 04:46:25 +00001596 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001597 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001598
1599 if (Persistent && !TrackerAct) {
1600 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001601 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1602 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001603 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001604 if (Clang->hasASTConsumer())
1605 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001606 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1607 *AST, AST->getCurrentTopLevelHashValue()));
1608 Clang->setASTConsumer(
1609 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001610 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001611 if (!Act->Execute()) {
1612 AST->transferASTDataFromCompilerInstance(*Clang);
1613 if (OwnAST && ErrAST)
1614 ErrAST->swap(OwnAST);
1615
Craig Topper49a27902014-05-22 04:46:25 +00001616 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001617 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001618
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001619 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001620 AST->transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001621
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001622 Act->EndSourceFile();
1623
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001624 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001625 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001626 else
1627 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001628}
1629
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001630bool ASTUnit::LoadFromCompilerInvocation(
1631 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001632 unsigned PrecompilePreambleAfterNParses,
1633 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001634 if (!Invocation)
1635 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001636
1637 assert(VFS && "VFS is null");
1638
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001639 // We'll manage file buffers ourselves.
1640 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1641 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001642 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001643 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001644
Rafael Espindola32482082014-08-18 16:23:45 +00001645 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001646 if (PrecompilePreambleAfterNParses > 0) {
1647 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001648 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001649 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001650 getDiagnostics().Reset();
1651 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001652 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001653
Douglas Gregor16896c42010-10-28 15:44:59 +00001654 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001655 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001656
Ted Kremenek022a4902011-03-22 01:15:24 +00001657 // Recover resources if we crash before exiting this method.
1658 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001659 MemBufferCleanup(OverrideMainBuffer.get());
1660
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001661 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001662}
1663
David Blaikie103a2de2014-04-25 17:01:33 +00001664std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001665 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001666 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001667 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001668 bool OnlyLocalDecls, bool CaptureDiagnostics,
1669 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1670 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1671 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001672 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001673 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001674 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001675 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001676 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001677 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001678 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001679 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001680 AST->IncludeBriefCommentsInCodeCompletion
1681 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001682 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001683 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1684 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001685 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001686
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001687 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001688 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1689 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001690 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +00001691 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +00001692 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001693
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001694 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001695 PrecompilePreambleAfterNParses,
1696 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001697 return nullptr;
1698 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001699}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001700
Ahmed Charlesb8984322014-03-07 20:03:18 +00001701ASTUnit *ASTUnit::LoadFromCommandLine(
1702 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001703 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001704 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1705 bool OnlyLocalDecls, bool CaptureDiagnostics,
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001706 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1707 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1708 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001709 bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001710 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1711 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1712 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001713 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001714
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001715 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001716
1717 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001718
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001719 {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001720 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1721 &StoredDiagnostics, nullptr);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001722
Eugene Zelenko4f233182018-03-22 00:53:26 +00001723 CI = createInvocationFromCommandLine(
Ilya Biryukovafdadf52017-06-28 15:06:34 +00001724 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001725 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001726 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001727 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001728
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001729 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001730 for (const auto &RemappedFile : RemappedFiles) {
1731 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1732 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001733 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001734 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1735 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1736 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001737 PPOpts.SingleFileParseMode = SingleFileParse;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001738
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001739 // Override the resources path.
1740 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1741
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001742 CI->getFrontendOpts().SkipFunctionBodies =
1743 SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001744
1745 if (ModuleFormat)
1746 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001747
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001748 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001749 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001750 AST.reset(new ASTUnit(false));
Ben Langmuir005c2e52018-03-23 17:37:27 +00001751 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1752 AST->StoredDiagnostics.swap(StoredDiagnostics);
Justin Bognerdbbcb112014-10-14 23:36:06 +00001753 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001754 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001755 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001756 if (!VFS)
1757 VFS = vfs::getRealFileSystem();
1758 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001759 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001760 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001761 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001762 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001763 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001764 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001765 AST->IncludeBriefCommentsInCodeCompletion
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001766 = IncludeBriefCommentsInCodeCompletion;
1767 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1768 AST->Invocation = CI;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001769 AST->SkipFunctionBodies = SkipFunctionBodies;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001770 if (ForSerialization)
1771 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
1772 // Zero out now to ease cleanup during crash recovery.
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001773 CI = nullptr;
1774 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001775
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001776 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001777 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1778 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001779
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001780 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001781 PrecompilePreambleAfterNParses,
1782 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001783 // Some error occurred, if caller wants to examine diagnostics, pass it the
1784 // ASTUnit.
1785 if (ErrAST) {
1786 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1787 ErrAST->swap(AST);
1788 }
Craig Topper49a27902014-05-22 04:46:25 +00001789 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001790 }
1791
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001792 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001793}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001794
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001795bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001796 ArrayRef<RemappedFile> RemappedFiles,
1797 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001798 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001799 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001800
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001801 if (!VFS) {
1802 assert(FileMgr && "FileMgr is null on Reparse call");
1803 VFS = FileMgr->getVirtualFileSystem();
1804 }
1805
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001806 clearFileLevelDecls();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001807
Douglas Gregor16896c42010-10-28 15:44:59 +00001808 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001809 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001810
Douglas Gregor0e119552010-07-31 00:40:00 +00001811 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001812 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00001813 for (const auto &RB : PPOpts.RemappedFileBuffers)
1814 delete RB.second;
1815
Douglas Gregor0e119552010-07-31 00:40:00 +00001816 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001817 for (const auto &RemappedFile : RemappedFiles) {
1818 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1819 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001820 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001821
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001822 // If we have a preamble file lying around, or if we might try to
1823 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00001824 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001825 if (Preamble || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001826 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001827 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1828
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001829 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00001830 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001831 getDiagnostics().Reset();
1832 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001833 if (OverrideMainBuffer)
1834 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001835
Douglas Gregor4dde7492010-07-23 23:58:40 +00001836 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001837 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001838 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00001839
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001840 // If we're caching global code-completion results, and the top-level
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001841 // declarations have changed, clear out the code-completion cache.
1842 if (!Result && ShouldCacheCodeCompletionResults &&
1843 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1844 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001845
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001846 // We now need to clear out the completion info related to this translation
1847 // unit; it'll be recreated if necessary.
1848 CCTUInfo.reset();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001849
Douglas Gregor4dde7492010-07-23 23:58:40 +00001850 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001851}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001852
Erik Verbruggen346066b2017-05-30 14:25:54 +00001853void ASTUnit::ResetForParse() {
1854 SavedMainFileBuffer.reset();
1855
1856 SourceMgr.reset();
1857 TheSema.reset();
1858 Ctx.reset();
1859 PP.reset();
1860 Reader.reset();
1861
1862 TopLevelDecls.clear();
1863 clearFileLevelDecls();
1864}
1865
Douglas Gregorb14904c2010-08-13 22:48:40 +00001866//----------------------------------------------------------------------------//
1867// Code completion
1868//----------------------------------------------------------------------------//
1869
1870namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +00001871
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001872 /// Code completion consumer that combines the cached code-completion
Douglas Gregorb14904c2010-08-13 22:48:40 +00001873 /// results from an ASTUnit with the code-completion results provided to it,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001874 /// then passes the result on to
Douglas Gregorb14904c2010-08-13 22:48:40 +00001875 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00001876 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001877 ASTUnit &AST;
1878 CodeCompleteConsumer &Next;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001879
Douglas Gregorb14904c2010-08-13 22:48:40 +00001880 public:
1881 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001882 const CodeCompleteOptions &CodeCompleteOpts)
Eugene Zelenko4f233182018-03-22 00:53:26 +00001883 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1884 AST(AST), Next(Next) {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001885 // Compute the set of contexts in which we will look when we don't have
1886 // any information about the specific context.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001887 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00001888 = (1LL << CodeCompletionContext::CCC_TopLevel)
1889 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1890 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1891 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1892 | (1LL << CodeCompletionContext::CCC_Statement)
1893 | (1LL << CodeCompletionContext::CCC_Expression)
1894 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1895 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1896 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1897 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1898 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1899 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1900 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00001901
David Blaikiebbafb8a2012-03-11 07:00:24 +00001902 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00001903 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1904 | (1LL << CodeCompletionContext::CCC_UnionTag)
1905 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001906 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001907
1908 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1909 CodeCompletionResult *Results,
1910 unsigned NumResults) override;
1911
1912 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1913 OverloadCandidate *Candidates,
1914 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001915 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1916 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001917
1918 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001919 return Next.getAllocator();
1920 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001921
Craig Topperafa7cb32014-03-13 06:07:04 +00001922 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001923 return Next.getCodeCompletionTUInfo();
1924 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001925 };
Eugene Zelenko4f233182018-03-22 00:53:26 +00001926
1927} // namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00001928
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001929/// Helper function that computes which global names are hidden by the
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001930/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001931static void CalculateHiddenNames(const CodeCompletionContext &Context,
1932 CodeCompletionResult *Results,
1933 unsigned NumResults,
1934 ASTContext &Ctx,
1935 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001936 bool OnlyTagNames = false;
1937 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001938 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001939 case CodeCompletionContext::CCC_TopLevel:
1940 case CodeCompletionContext::CCC_ObjCInterface:
1941 case CodeCompletionContext::CCC_ObjCImplementation:
1942 case CodeCompletionContext::CCC_ObjCIvarList:
1943 case CodeCompletionContext::CCC_ClassStructUnion:
1944 case CodeCompletionContext::CCC_Statement:
1945 case CodeCompletionContext::CCC_Expression:
1946 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001947 case CodeCompletionContext::CCC_DotMemberAccess:
1948 case CodeCompletionContext::CCC_ArrowMemberAccess:
1949 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001950 case CodeCompletionContext::CCC_Namespace:
1951 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001952 case CodeCompletionContext::CCC_Name:
1953 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001954 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001955 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001956 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001957
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001958 case CodeCompletionContext::CCC_EnumTag:
1959 case CodeCompletionContext::CCC_UnionTag:
1960 case CodeCompletionContext::CCC_ClassOrStructTag:
1961 OnlyTagNames = true;
1962 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001963
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001964 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001965 case CodeCompletionContext::CCC_MacroName:
1966 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001967 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001968 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001969 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001970 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001971 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001972 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001973 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00001974 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1975 case CodeCompletionContext::CCC_ObjCClassMessage:
1976 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001977 // We're looking for nothing, or we're looking for names that cannot
1978 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001979 return;
1980 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001981
Eugene Zelenko4f233182018-03-22 00:53:26 +00001982 using Result = CodeCompletionResult;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001983 for (unsigned I = 0; I != NumResults; ++I) {
1984 if (Results[I].Kind != Result::RK_Declaration)
1985 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001986
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001987 unsigned IDNS
1988 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1989
1990 bool Hiding = false;
1991 if (OnlyTagNames)
1992 Hiding = (IDNS & Decl::IDNS_Tag);
1993 else {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001994 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001995 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1996 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001997 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001998 HiddenIDNS |= Decl::IDNS_Tag;
1999 Hiding = (IDNS & HiddenIDNS);
2000 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002001
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002002 if (!Hiding)
2003 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002004
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002005 DeclarationName Name = Results[I].Declaration->getDeclName();
2006 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2007 HiddenNames.insert(Identifier->getName());
2008 else
2009 HiddenNames.insert(Name.getAsString());
2010 }
2011}
2012
Douglas Gregord46cf182010-08-16 20:01:48 +00002013void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2014 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002015 CodeCompletionResult *Results,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002016 unsigned NumResults) {
Douglas Gregord46cf182010-08-16 20:01:48 +00002017 // Merge the results we were given with the results we cached.
2018 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002019 uint64_t InContexts =
2020 Context.getKind() == CodeCompletionContext::CCC_Recovery
2021 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002022 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002023 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Eugene Zelenko4f233182018-03-22 00:53:26 +00002024 using Result = CodeCompletionResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002025 SmallVector<Result, 8> AllResults;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002026 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002027 C = AST.cached_completion_begin(),
2028 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002029 C != CEnd; ++C) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002030 // If the context we are in matches any of the contexts we are
Douglas Gregord46cf182010-08-16 20:01:48 +00002031 // interested in, we'll add this result.
2032 if ((C->ShowInContexts & InContexts) == 0)
2033 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002034
Douglas Gregord46cf182010-08-16 20:01:48 +00002035 // If we haven't added any results previously, do so now.
2036 if (!AddedResult) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002037 CalculateHiddenNames(Context, Results, NumResults, S.Context,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002038 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002039 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2040 AddedResult = true;
2041 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002042
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002043 // Determine whether this global completion result is hidden by a local
2044 // completion result. If so, skip it.
2045 if (C->Kind != CXCursor_MacroDefinition &&
2046 HiddenNames.count(C->Completion->getTypedText()))
2047 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002048
Douglas Gregord46cf182010-08-16 20:01:48 +00002049 // Adjust priority based on similar type classes.
2050 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002051 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002052 if (!Context.getPreferredType().isNull()) {
2053 if (C->Kind == CXCursor_MacroDefinition) {
2054 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002055 S.getLangOpts(),
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002056 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002057 } else if (C->Type) {
2058 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002059 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002060 Context.getPreferredType().getUnqualifiedType());
2061 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2062 if (ExpectedSTC == C->TypeClass) {
2063 // We know this type is similar; check for an exact match.
2064 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002065 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002066 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002067 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002068 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2069 Priority /= CCF_ExactTypeMatch;
2070 else
2071 Priority /= CCF_SimilarTypeMatch;
2072 }
2073 }
2074 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002075
Douglas Gregor12785102010-08-24 20:21:13 +00002076 // Adjust the completion string, if required.
2077 if (C->Kind == CXCursor_MacroDefinition &&
2078 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2079 // Create a new code-completion string that just contains the
2080 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002081 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2082 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002083 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002084 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002085 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002086 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002087
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002088 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002089 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002090 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002091
Douglas Gregord46cf182010-08-16 20:01:48 +00002092 // If we did not add any cached completion results, just forward the
2093 // results we were given to the next consumer.
2094 if (!AddedResult) {
2095 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2096 return;
2097 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002098
Douglas Gregord46cf182010-08-16 20:01:48 +00002099 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2100 AllResults.size());
2101}
2102
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002103void ASTUnit::CodeComplete(
2104 StringRef File, unsigned Line, unsigned Column,
2105 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2106 bool IncludeCodePatterns, bool IncludeBriefComments,
2107 CodeCompleteConsumer &Consumer,
2108 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2109 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2110 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2111 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002112 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002113 return;
2114
Douglas Gregor16896c42010-10-28 15:44:59 +00002115 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002116 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002117 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002118
David Blaikieea4395e2017-01-06 19:49:01 +00002119 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002120
2121 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002122 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002123 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002124
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002125 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2126 CachedCompletionResults.empty();
2127 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2128 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2129 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
Sam McCallbb2cf632018-01-12 14:51:47 +00002130 CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +00002131 CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002132
2133 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2134
Douglas Gregor8e984da2010-08-04 16:47:14 +00002135 FrontendOpts.CodeCompletionAt.FileName = File;
2136 FrontendOpts.CodeCompletionAt.Line = Line;
2137 FrontendOpts.CodeCompletionAt.Column = Column;
2138
2139 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002140 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002141
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002142 // Spell-checking and warnings are wasteful during code-completion.
2143 LangOpts.SpellChecking = false;
2144 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2145
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002146 std::unique_ptr<CompilerInstance> Clang(
2147 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002148
2149 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002150 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2151 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002152
David Blaikieea4395e2017-01-06 19:49:01 +00002153 auto &Inv = *CCInvocation;
2154 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002155 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002156
Douglas Gregor8e984da2010-08-04 16:47:14 +00002157 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002158 Clang->setDiagnostics(&Diag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002159 CaptureDroppedDiagnostics Capture(true,
2160 Clang->getDiagnostics(),
Ilya Biryukov200b3282017-06-21 10:24:58 +00002161 &StoredDiagnostics, nullptr);
David Blaikieea4395e2017-01-06 19:49:01 +00002162 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2163
Douglas Gregor8e984da2010-08-04 16:47:14 +00002164 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002165 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002166 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002167 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002168 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002169 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002170 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002171
Douglas Gregor8e984da2010-08-04 16:47:14 +00002172 // Inform the target of the language options.
2173 //
2174 // FIXME: We shouldn't need to do this, the target should be immutable once
2175 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002176 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002177
Ted Kremenek84de4a12011-03-21 18:40:07 +00002178 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002179 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002180 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2181 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002182 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002183 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2184 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002185 "IR inputs not support here!");
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002186
Douglas Gregor8e984da2010-08-04 16:47:14 +00002187 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002188 Clang->setFileManager(&FileMgr);
2189 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002190
2191 // Remap files.
2192 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002193 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002194 for (const auto &RemappedFile : RemappedFiles) {
2195 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2196 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002197 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002198
Douglas Gregorb14904c2010-08-13 22:48:40 +00002199 // Use the code completion consumer we were given, but adding any cached
2200 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002201 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002202 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002203 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002204
Douglas Gregor028d3e42010-08-09 20:45:32 +00002205 // If we have a precompiled preamble, try to use it. We only allow
2206 // the use of the precompiled preamble if we're if the completion
2207 // point is within the main file, after the end of the precompiled
2208 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002209 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002210 if (Preamble) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002211 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002212
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002213 auto VFS = FileMgr.getVirtualFileSystem();
2214 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2215 if (CompleteFileStatus) {
2216 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2217
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002218 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002219 auto MainStatus = VFS->status(MainPath);
2220 if (MainStatus) {
2221 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002222 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002223 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002224 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002225 }
2226 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002227 }
2228
2229 // If the main file has been overridden due to the use of a preamble,
2230 // make that override happen and introduce the preamble.
2231 if (OverrideMainBuffer) {
Ilya Biryukov417085a2017-11-16 16:25:01 +00002232 assert(Preamble &&
2233 "No preamble was built, but OverrideMainBuffer is not null");
2234
2235 auto VFS = FileMgr.getVirtualFileSystem();
2236 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2237 OverrideMainBuffer.get());
2238 // FIXME: there is no way to update VFS if it was changed by
2239 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2240 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2241 // PCH files are always readable.
Rafael Espindola2346a372014-08-18 18:47:08 +00002242 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002243 } else {
2244 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2245 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002246 }
2247
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002248 // Disable the preprocessing record if modules are not enabled.
2249 if (!Clang->getLangOpts().Modules)
2250 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002251
2252 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002253 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002254 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002255 Act->Execute();
2256 Act->EndSourceFile();
2257 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002258}
Douglas Gregore9386682010-08-13 05:36:37 +00002259
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002260bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002261 if (HadModuleLoaderFatalFailure)
2262 return true;
2263
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002264 // Write to a temporary file and later rename it to the actual file, to avoid
2265 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002266 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002267 TempPath = File;
2268 TempPath += "-%%%%%%%%";
2269 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002270 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002271 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002272
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002273 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
Douglas Gregore9386682010-08-13 05:36:37 +00002274 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002275 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002276
2277 serialize(Out);
2278 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002279 if (Out.has_error()) {
2280 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002281 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002282 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002283
Yaron Keren92e1b622015-03-18 10:17:07 +00002284 if (llvm::sys::fs::rename(TempPath, File)) {
2285 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002286 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002287 }
2288
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002289 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002290}
2291
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002292static bool serializeUnit(ASTWriter &Writer,
2293 SmallVectorImpl<char> &Buffer,
2294 Sema &S,
2295 bool hasErrors,
2296 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002297 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002298
2299 // Write the generated bitstream to "Out".
2300 if (!Buffer.empty())
2301 OS.write(Buffer.data(), Buffer.size());
2302
2303 return false;
2304}
2305
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002306bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002307 // For serialization we are lenient if the errors were only warn-as-error kind.
2308 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002309
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002310 if (WriterData)
2311 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2312 getSema(), hasErrors, OS);
2313
Daniel Dunbar9a963862012-02-29 20:31:23 +00002314 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002315 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002316 MemoryBufferCache PCMCache;
2317 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002318 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002319}
Douglas Gregor925296b2011-07-19 16:10:42 +00002320
Eugene Zelenko4f233182018-03-22 00:53:26 +00002321using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
Douglas Gregor925296b2011-07-19 16:10:42 +00002322
Douglas Gregor925296b2011-07-19 16:10:42 +00002323void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002324 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002325 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002326 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002327 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002328 // Map the standalone diagnostic into the new source manager. We also need to
2329 // remap all the locations to the new view. This includes the diag location,
2330 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002331 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002332 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002333 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002334
Eugene Zelenko4f233182018-03-22 00:53:26 +00002335 for (const auto &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002336 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002337 if (SD.Filename.empty())
2338 continue;
2339 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2340 if (!FE)
2341 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002342 SourceLocation FileLoc;
2343 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2344 if (ItFileID == PreambleSrcLocCache.end()) {
2345 FileID FID = SrcMgr.translateFile(FE);
2346 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2347 PreambleSrcLocCache[SD.Filename] = FileLoc;
2348 } else {
2349 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002350 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002351
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002352 if (FileLoc.isInvalid())
2353 continue;
2354 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002355 FullSourceLoc Loc(L, SrcMgr);
2356
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002357 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002358 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002359 for (const auto &Range : SD.Ranges) {
2360 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2361 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002362 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002363 }
2364
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002365 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002366 FixIts.reserve(SD.FixIts.size());
Eugene Zelenko4f233182018-03-22 00:53:26 +00002367 for (const auto &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002368 FixIts.push_back(FixItHint());
2369 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002370 FH.CodeToInsert = FixIt.CodeToInsert;
2371 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2372 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002373 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002374 }
2375
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002376 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002377 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002378 }
2379 Result.swap(Out);
2380}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002381
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002382void ASTUnit::addFileLevelDecl(Decl *D) {
2383 assert(D);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002384
Douglas Gregor61d63d02011-11-07 18:53:57 +00002385 // We only care about local declarations.
2386 if (D->isFromASTFile())
2387 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002388
2389 SourceManager &SM = *SourceMgr;
2390 SourceLocation Loc = D->getLocation();
2391 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2392 return;
2393
2394 // We only keep track of the file-level declarations of each file.
2395 if (!D->getLexicalDeclContext()->isFileContext())
2396 return;
2397
2398 SourceLocation FileLoc = SM.getFileLoc(Loc);
2399 assert(SM.isLocalSourceLocation(FileLoc));
2400 FileID FID;
2401 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002402 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002403 if (FID.isInvalid())
2404 return;
2405
2406 LocDeclsTy *&Decls = FileDecls[FID];
2407 if (!Decls)
2408 Decls = new LocDeclsTy();
2409
2410 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2411
2412 if (Decls->empty() || Decls->back().first <= Offset) {
2413 Decls->push_back(LocDecl);
2414 return;
2415 }
2416
Benjamin Kramer45025c02013-08-24 13:22:59 +00002417 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2418 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002419
2420 Decls->insert(I, LocDecl);
2421}
2422
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002423void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2424 SmallVectorImpl<Decl *> &Decls) {
2425 if (File.isInvalid())
2426 return;
2427
2428 if (SourceMgr->isLoadedFileID(File)) {
2429 assert(Ctx->getExternalSource() && "No external source!");
2430 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2431 Decls);
2432 }
2433
2434 FileDeclsTy::iterator I = FileDecls.find(File);
2435 if (I == FileDecls.end())
2436 return;
2437
2438 LocDeclsTy &LocDecls = *I->second;
2439 if (LocDecls.empty())
2440 return;
2441
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002442 LocDeclsTy::iterator BeginIt =
2443 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002444 std::make_pair(Offset, (Decl *)nullptr),
2445 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002446 if (BeginIt != LocDecls.begin())
2447 --BeginIt;
2448
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002449 // If we are pointing at a top-level decl inside an objc container, we need
2450 // to backtrack until we find it otherwise we will fail to report that the
2451 // region overlaps with an objc container.
2452 while (BeginIt != LocDecls.begin() &&
2453 BeginIt->second->isTopLevelDeclInObjCContainer())
2454 --BeginIt;
2455
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002456 LocDeclsTy::iterator EndIt = std::upper_bound(
2457 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002458 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002459 if (EndIt != LocDecls.end())
2460 ++EndIt;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002461
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002462 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2463 Decls.push_back(DIt->second);
2464}
2465
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002466SourceLocation ASTUnit::getLocation(const FileEntry *File,
2467 unsigned Line, unsigned Col) const {
2468 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002469 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002470 return SM.getMacroArgExpandedLocation(Loc);
2471}
2472
2473SourceLocation ASTUnit::getLocation(const FileEntry *File,
2474 unsigned Offset) const {
2475 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002476 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002477 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2478}
2479
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002480/// If \arg Loc is a loaded location from the preamble, returns
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002481/// the corresponding local location of the main file, otherwise it returns
2482/// \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002483SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002484 FileID PreambleID;
2485 if (SourceMgr)
2486 PreambleID = SourceMgr->getPreambleFileID();
2487
Ilya Biryukov200b3282017-06-21 10:24:58 +00002488 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002489 return Loc;
2490
2491 unsigned Offs;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002492 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002493 SourceLocation FileLoc
2494 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2495 return FileLoc.getLocWithOffset(Offs);
2496 }
2497
2498 return Loc;
2499}
2500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002501/// If \arg Loc is a local location of the main file but inside the
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002502/// preamble chunk, returns the corresponding loaded location from the
2503/// preamble, otherwise it returns \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002504SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002505 FileID PreambleID;
2506 if (SourceMgr)
2507 PreambleID = SourceMgr->getPreambleFileID();
2508
Ilya Biryukov200b3282017-06-21 10:24:58 +00002509 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002510 return Loc;
2511
2512 unsigned Offs;
2513 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Ilya Biryukov200b3282017-06-21 10:24:58 +00002514 Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002515 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2516 return FileLoc.getLocWithOffset(Offs);
2517 }
2518
2519 return Loc;
2520}
2521
Vedant Kumar525a7f62017-07-25 19:53:27 +00002522bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002523 FileID FID;
2524 if (SourceMgr)
2525 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002526
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002527 if (Loc.isInvalid() || FID.isInvalid())
2528 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002529
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002530 return SourceMgr->isInFileID(Loc, FID);
2531}
2532
Vedant Kumar525a7f62017-07-25 19:53:27 +00002533bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002534 FileID FID;
2535 if (SourceMgr)
2536 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002537
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002538 if (Loc.isInvalid() || FID.isInvalid())
2539 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002540
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002541 return SourceMgr->isInFileID(Loc, FID);
2542}
2543
Vedant Kumar525a7f62017-07-25 19:53:27 +00002544SourceLocation ASTUnit::getEndOfPreambleFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002545 FileID FID;
2546 if (SourceMgr)
2547 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002548
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002549 if (FID.isInvalid())
Eugene Zelenko4f233182018-03-22 00:53:26 +00002550 return {};
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002551
2552 return SourceMgr->getLocForEndOfFile(FID);
2553}
2554
Vedant Kumar525a7f62017-07-25 19:53:27 +00002555SourceLocation ASTUnit::getStartOfMainFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002556 FileID FID;
2557 if (SourceMgr)
2558 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002559
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002560 if (FID.isInvalid())
Eugene Zelenko4f233182018-03-22 00:53:26 +00002561 return {};
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002562
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002563 return SourceMgr->getLocForStartOfFile(FID);
2564}
2565
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002566llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002567ASTUnit::getLocalPreprocessingEntities() const {
2568 if (isMainFileAST()) {
2569 serialization::ModuleFile &
2570 Mod = Reader->getModuleManager().getPrimaryModule();
2571 return Reader->getModulePreprocessedEntities(Mod);
2572 }
2573
2574 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002575 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002576
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002577 return llvm::make_range(PreprocessingRecord::iterator(),
2578 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002579}
2580
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002581bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002582 if (isMainFileAST()) {
2583 serialization::ModuleFile &
2584 Mod = Reader->getModuleManager().getPrimaryModule();
Eugene Zelenko4f233182018-03-22 00:53:26 +00002585 for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002586 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002587 return false;
2588 }
2589
2590 return true;
2591 }
2592
2593 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2594 TLEnd = top_level_end();
2595 TL != TLEnd; ++TL) {
2596 if (!Fn(context, *TL))
2597 return false;
2598 }
2599
2600 return true;
2601}
2602
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002603const FileEntry *ASTUnit::getPCHFile() {
2604 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002605 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002606
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002607 serialization::ModuleFile *Mod = nullptr;
2608 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2609 switch (M.Kind) {
2610 case serialization::MK_ImplicitModule:
2611 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002612 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002613 return true; // skip dependencies.
2614 case serialization::MK_PCH:
2615 Mod = &M;
2616 return true; // found it.
2617 case serialization::MK_Preamble:
2618 return false; // look in dependencies.
2619 case serialization::MK_MainFile:
2620 return false; // look in dependencies.
2621 }
2622
2623 return true;
2624 });
2625 if (Mod)
2626 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002627
Craig Topper49a27902014-05-22 04:46:25 +00002628 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002629}
2630
Vedant Kumar525a7f62017-07-25 19:53:27 +00002631bool ASTUnit::isModuleFile() const {
Richard Smithab755972017-06-05 18:10:11 +00002632 return isMainFileAST() && getLangOpts().isCompilingModule();
2633}
2634
2635InputKind ASTUnit::getInputKind() const {
2636 auto &LangOpts = getLangOpts();
2637
2638 InputKind::Language Lang;
2639 if (LangOpts.OpenCL)
2640 Lang = InputKind::OpenCL;
2641 else if (LangOpts.CUDA)
2642 Lang = InputKind::CUDA;
2643 else if (LangOpts.RenderScript)
2644 Lang = InputKind::RenderScript;
2645 else if (LangOpts.CPlusPlus)
2646 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2647 else
2648 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2649
2650 InputKind::Format Fmt = InputKind::Source;
2651 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2652 Fmt = InputKind::ModuleMap;
2653
2654 // We don't know if input was preprocessed. Assume not.
2655 bool PP = false;
2656
2657 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002658}
2659
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002660#ifndef NDEBUG
2661ASTUnit::ConcurrencyState::ConcurrencyState() {
2662 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2663}
2664
2665ASTUnit::ConcurrencyState::~ConcurrencyState() {
2666 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2667}
2668
2669void ASTUnit::ConcurrencyState::start() {
2670 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2671 assert(acquired && "Concurrent access to ASTUnit!");
2672}
2673
2674void ASTUnit::ConcurrencyState::finish() {
2675 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2676}
2677
2678#else // NDEBUG
2679
Hans Wennborgdcfba332015-10-06 23:40:43 +00002680ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002681ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002682void ASTUnit::ConcurrencyState::start() {}
2683void ASTUnit::ConcurrencyState::finish() {}
2684
Hans Wennborgdcfba332015-10-06 23:40:43 +00002685#endif // NDEBUG