blob: 84e74ad50580ed4198e86a38aea84ca68db8d827 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
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"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000021#include "clang/Basic/MemoryBufferCache.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000024#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000029#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000033#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000034#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Serialization/ASTReader.h"
36#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000037#include "llvm/ADT/ArrayRef.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000040#include "llvm/Support/DJB.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000047#include <atomic>
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
Hans Wennborgdcfba332015-10-06 23:40:43 +000050
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +000082
83 template <class T>
84 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
85 if (!Val)
86 return nullptr;
87 return std::move(*Val);
88 }
89
90 template <class T>
91 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
92 if (!Val)
93 return false;
94 Output = std::move(*Val);
95 return true;
96 }
Ted Kremenek06b4f912011-10-27 17:55:18 +000097
Ilya Biryukov200b3282017-06-21 10:24:58 +000098/// \brief Get a source buffer for \p MainFilePath, handling all file-to-file
99/// and file-to-buffer remappings inside \p Invocation.
100static std::unique_ptr<llvm::MemoryBuffer>
101getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
102 vfs::FileSystem *VFS,
103 StringRef FilePath) {
104 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
Ted Kremenekbd307a52011-10-27 19:44:25 +0000105
Ilya Biryukov200b3282017-06-21 10:24:58 +0000106 // Try to determine if the main file has been remapped, either from the
107 // command line (to another file) or directly through the compiler
108 // invocation (to a memory buffer).
109 llvm::MemoryBuffer *Buffer = nullptr;
110 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
111 auto FileStatus = VFS->status(FilePath);
112 if (FileStatus) {
113 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000114
Ilya Biryukov200b3282017-06-21 10:24:58 +0000115 // Check whether there is a file-file remapping of the main file
116 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
117 std::string MPath(RF.first);
118 auto MPathStatus = VFS->status(MPath);
119 if (MPathStatus) {
120 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
121 if (MainFileID == MID) {
122 // We found a remapping. Try to load the resulting, remapped source.
123 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
124 if (!BufferOwner)
125 return nullptr;
126 }
127 }
128 }
129
130 // Check whether there is a file-buffer remapping. It supercedes the
131 // file-file remapping.
132 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
133 std::string MPath(RB.first);
134 auto MPathStatus = VFS->status(MPath);
135 if (MPathStatus) {
136 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
137 if (MainFileID == MID) {
138 // We found a remapping.
139 BufferOwner.reset();
140 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
141 }
142 }
143 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000144 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000145
Ilya Biryukov200b3282017-06-21 10:24:58 +0000146 // If the main source file was not remapped, load it now.
147 if (!Buffer && !BufferOwner) {
148 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
149 if (!BufferOwner)
150 return nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000151 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152
Ilya Biryukov200b3282017-06-21 10:24:58 +0000153 if (BufferOwner)
154 return BufferOwner;
155 if (!Buffer)
156 return nullptr;
157 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000158}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159}
160
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000161struct ASTUnit::ASTWriterData {
162 SmallString<128> Buffer;
163 llvm::BitstreamWriter Stream;
164 ASTWriter Writer;
165
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000166 ASTWriterData(MemoryBufferCache &PCMCache)
167 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000168};
169
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000170void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000171 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000172}
173
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000174/// \brief After failing to build a precompiled preamble (due to
175/// errors in the source that occurs in the preamble), the number of
176/// reparses during which we'll skip even trying to precompile the
177/// preamble.
178const unsigned DefaultPreambleRebuildInterval = 5;
179
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000180/// \brief Tracks the number of ASTUnit objects that are currently active.
181///
182/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000183static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000184
Douglas Gregord03e8232010-04-05 21:10:19 +0000185ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000186 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000187 OnlyLocalDecls(false), CaptureDiagnostics(false),
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000188 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000189 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000190 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000191 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000192 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000193 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000194 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000195 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000196 CompletionCacheTopLevelHashValue(0),
197 PreambleTopLevelHashValue(0),
198 CurrentTopLevelHashValue(0),
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000199 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000200 if (getenv("LIBCLANG_OBJTRACKING"))
201 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000202}
Douglas Gregord03e8232010-04-05 21:10:19 +0000203
Daniel Dunbar764c0822009-12-01 09:51:01 +0000204ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000205 // If we loaded from an AST file, balance out the BeginSourceFile call.
206 if (MainFileIsAST && getDiagnostics().getClient()) {
207 getDiagnostics().getClient()->EndSourceFile();
208 }
209
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000210 clearFileLevelDecls();
211
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000212 // Free the buffers associated with remapped files. We are required to
213 // perform this operation here because we explicitly request that the
214 // compiler instance *not* free these buffers for each invocation of the
215 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000216 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000217 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000218 for (const auto &RB : PPOpts.RemappedFileBuffers)
219 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000220 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000221
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000222 ClearCachedCompletionResults();
223
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000226}
227
David Blaikie41565462017-01-05 19:48:07 +0000228void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
229 this->PP = std::move(PP);
230}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000231
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000232/// \brief Determine the set of code-completion contexts in which this
Douglas Gregor39982192010-08-15 06:18:01 +0000233/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000234static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000235 const LangOptions &LangOpts,
236 bool &IsNestedNameSpecifier) {
237 IsNestedNameSpecifier = false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000238
Douglas Gregor39982192010-08-15 06:18:01 +0000239 if (isa<UsingShadowDecl>(ND))
240 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
241 if (!ND)
242 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000243
Richard Smith697cc9e2012-08-14 03:13:00 +0000244 uint64_t Contexts = 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000245 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
Erik Verbruggen51ee12a2017-09-08 09:31:13 +0000246 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
247 isa<TypeAliasTemplateDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000248 // Types can appear in these contexts.
249 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000250 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
251 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
252 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
253 | (1LL << CodeCompletionContext::CCC_Statement)
254 | (1LL << CodeCompletionContext::CCC_Type)
255 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000256
257 // In C++, types can appear in expressions contexts (for functional casts).
258 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000259 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000260
Douglas Gregor39982192010-08-15 06:18:01 +0000261 // In Objective-C, message sends can send interfaces. In Objective-C++,
262 // all types are available due to functional casts.
263 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000264 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000265
Douglas Gregor21325842011-07-07 16:03:39 +0000266 // In Objective-C, you can only be a subclass of another Objective-C class
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000267 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
268 // Objective-C interfaces can be used in a class property expression.
269 if (ID->getDefinition())
270 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Richard Smith697cc9e2012-08-14 03:13:00 +0000271 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000272 }
Douglas Gregor39982192010-08-15 06:18:01 +0000273
274 // Deal with tag names.
275 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000276 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000277
Douglas Gregor59cab552010-08-16 23:05:20 +0000278 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000279 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000280 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000281 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000282 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000284 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000285 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000286
Douglas Gregor39982192010-08-15 06:18:01 +0000287 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000288 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000289 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000290 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000291 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
292 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000293 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
294 | (1LL << CodeCompletionContext::CCC_Expression)
295 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
296 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000297 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000298 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000299 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000300 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000301 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000302 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000303
Douglas Gregor39982192010-08-15 06:18:01 +0000304 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000306 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000307
Douglas Gregor39982192010-08-15 06:18:01 +0000308 return Contexts;
309}
310
Douglas Gregorb14904c2010-08-13 22:48:40 +0000311void ASTUnit::CacheCodeCompletionResults() {
312 if (!TheSema)
313 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000314
Douglas Gregor16896c42010-10-28 15:44:59 +0000315 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000316 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000317
318 // Clear out the previous results.
319 ClearCachedCompletionResults();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000320
Douglas Gregorb14904c2010-08-13 22:48:40 +0000321 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000322 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000323 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000324 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000325 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000326 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000327 CCTUInfo, Results);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000328
Douglas Gregorb14904c2010-08-13 22:48:40 +0000329 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000330 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000331 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000332
333 for (Result &R : Results) {
334 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000335 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000336 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000337 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000338 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000339 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000340 IncludeBriefCommentsInCodeCompletion);
341 CachedResult.ShowInContexts = getDeclShowContexts(
342 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
343 CachedResult.Priority = R.Priority;
344 CachedResult.Kind = R.CursorKind;
345 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000346
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000347 // Keep track of the type of this completion in an ASTContext-agnostic
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000348 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000349 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000350 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000351 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000352 CachedResult.Type = 0;
353 } else {
354 CanQualType CanUsageType
355 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
356 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
357
358 // Determine whether we have already seen this type. If so, we save
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000359 // ourselves the work of formatting the type string by using the
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000360 // temporary, CanQualType-based hash table to find the associated value.
361 unsigned &TypeValue = CompletionTypes[CanUsageType];
362 if (TypeValue == 0) {
363 TypeValue = CompletionTypes.size();
364 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
365 = TypeValue;
366 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000367
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000368 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000369 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000370
Douglas Gregor39982192010-08-15 06:18:01 +0000371 CachedCompletionResults.push_back(CachedResult);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000372
Douglas Gregor59cab552010-08-16 23:05:20 +0000373 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000374 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
375 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000376 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000377 uint64_t NNSContexts
378 = (1LL << CodeCompletionContext::CCC_TopLevel)
379 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
380 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
381 | (1LL << CodeCompletionContext::CCC_Statement)
382 | (1LL << CodeCompletionContext::CCC_Expression)
383 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
384 | (1LL << CodeCompletionContext::CCC_EnumTag)
385 | (1LL << CodeCompletionContext::CCC_UnionTag)
386 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
387 | (1LL << CodeCompletionContext::CCC_Type)
388 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
389 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000390
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000391 if (isa<NamespaceDecl>(R.Declaration) ||
392 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000393 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000394
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000395 if (unsigned RemainingContexts
Douglas Gregor59cab552010-08-16 23:05:20 +0000396 = NNSContexts & ~CachedResult.ShowInContexts) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000397 // If there any contexts where this completion can be a
398 // nested-name-specifier but isn't already an option, create a
Douglas Gregor59cab552010-08-16 23:05:20 +0000399 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000400 R.StartsNestedNameSpecifier = true;
401 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000402 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000403 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000404 CachedResult.ShowInContexts = RemainingContexts;
405 CachedResult.Priority = CCP_NestedNameSpecifier;
406 CachedResult.TypeClass = STC_Void;
407 CachedResult.Type = 0;
408 CachedCompletionResults.push_back(CachedResult);
409 }
410 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000411 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000412 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000413
Douglas Gregorb14904c2010-08-13 22:48:40 +0000414 case Result::RK_Keyword:
415 case Result::RK_Pattern:
416 // Ignore keywords and patterns; we don't care, since they are so
417 // easily regenerated.
418 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000419
Douglas Gregorb14904c2010-08-13 22:48:40 +0000420 case Result::RK_Macro: {
421 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000422 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000423 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000424 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000425 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000426 = (1LL << CodeCompletionContext::CCC_TopLevel)
427 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
428 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
429 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
430 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
431 | (1LL << CodeCompletionContext::CCC_Statement)
432 | (1LL << CodeCompletionContext::CCC_Expression)
433 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
434 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
435 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
436 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
437 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000438
439 CachedResult.Priority = R.Priority;
440 CachedResult.Kind = R.CursorKind;
441 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000442 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000443 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000444 CachedCompletionResults.push_back(CachedResult);
445 break;
446 }
447 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000448 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000449
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000450 // Save the current top-level hash value.
451 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000452}
453
454void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000455 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000456 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000457 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000458}
459
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000460namespace {
461
Sebastian Redl2c499f62010-08-18 23:56:43 +0000462/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000463/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000464class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000465 Preprocessor &PP;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000466 ASTContext *Context;
Richard Smith18934752017-06-06 00:32:01 +0000467 HeaderSearchOptions &HSOpts;
468 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000469 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000470 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000471 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000472 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000473
Douglas Gregore8bbc122011-09-02 00:18:52 +0000474 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000475public:
Richard Smithdbafb6c2017-06-29 23:23:46 +0000476 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
Richard Smith18934752017-06-06 00:32:01 +0000477 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
478 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000479 std::shared_ptr<TargetOptions> &TargetOpts,
480 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000481 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
482 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
483 Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000484
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000485 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
486 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000487 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000488 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000489
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000490 LangOpt = LangOpts;
491 InitializedLanguage = true;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000492
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000493 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494 return false;
495 }
Mike Stump11289f42009-09-09 15:08:12 +0000496
Richard Smith18934752017-06-06 00:32:01 +0000497 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
498 StringRef SpecificModuleCachePath,
499 bool Complain) override {
500 this->HSOpts = HSOpts;
501 return false;
502 }
503
504 virtual bool
505 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
506 std::string &SuggestedPredefines) override {
507 this->PPOpts = PPOpts;
508 return false;
509 }
510
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000511 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
512 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000513 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000514 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000515 return false;
Alp Toker80758082014-07-06 05:26:44 +0000516
517 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
518 Target =
519 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000520
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000521 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 return false;
523 }
Mike Stump11289f42009-09-09 15:08:12 +0000524
Craig Topperafa7cb32014-03-13 06:07:04 +0000525 void ReadCounter(const serialization::ModuleFile &M,
526 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000527 Counter = Value;
528 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000529
530private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000531 void updated() {
532 if (!Target || !InitializedLanguage)
533 return;
534
535 // Inform the target of the language options.
536 //
537 // FIXME: We shouldn't need to do this, the target should be immutable once
538 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000539 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000540
541 // Initialize the preprocessor.
542 PP.Initialize(*Target);
543
Richard Smithdbafb6c2017-06-29 23:23:46 +0000544 if (!Context)
545 return;
546
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000547 // Initialize the ASTContext
Richard Smithdbafb6c2017-06-29 23:23:46 +0000548 Context->InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000549
Vedant Kumarfd9fad92017-08-25 18:07:03 +0000550 // Adjust printing policy based on language options.
551 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
552
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000553 // We didn't have access to the comment options when the ASTContext was
554 // constructed, so register them now.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000555 Context->getCommentCommandTraits().registerCommentOptions(
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000556 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000557 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000558};
559
Douglas Gregor6b930962013-05-03 22:58:43 +0000560 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000561class StoredDiagnosticConsumer : public DiagnosticConsumer {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000562 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
563 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
564 const LangOptions *LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000565 SourceManager *SourceMgr;
566
Douglas Gregor33cdd812010-02-18 18:08:43 +0000567public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000568 StoredDiagnosticConsumer(
569 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
570 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
571 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
572 LangOpts(nullptr), SourceMgr(nullptr) {
573 assert((StoredDiags || StandaloneDiags) &&
574 "No output collections were passed to StoredDiagnosticConsumer.");
575 }
Douglas Gregor6b930962013-05-03 22:58:43 +0000576
Craig Topperafa7cb32014-03-13 06:07:04 +0000577 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000578 const Preprocessor *PP = nullptr) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000579 this->LangOpts = &LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000580 if (PP)
581 SourceMgr = &PP->getSourceManager();
582 }
583
Craig Topperafa7cb32014-03-13 06:07:04 +0000584 void HandleDiagnostic(DiagnosticsEngine::Level Level,
585 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000586};
587
588/// \brief RAII object that optionally captures diagnostics, if
589/// there is no diagnostic client to capture them already.
590class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000591 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000592 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000593 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000594 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595
596public:
David Blaikie9c902b52011-09-25 23:23:43 +0000597 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000598 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
599 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
600 : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000601 {
Craig Topper49a27902014-05-22 04:46:25 +0000602 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000603 OwningPreviousClient = Diags.takeClient();
604 PreviousClient = Diags.getClient();
605 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000606 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000607 }
608
609 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000610 if (Diags.getClient() == &Client)
611 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000612 }
613};
614
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000615} // anonymous namespace
616
Ilya Biryukov200b3282017-06-21 10:24:58 +0000617static ASTUnit::StandaloneDiagnostic
618makeStandaloneDiagnostic(const LangOptions &LangOpts,
619 const StoredDiagnostic &InDiag);
620
David Blaikief18d91a2011-09-26 00:01:39 +0000621void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000622 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000623 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000624 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000625
Douglas Gregor6b930962013-05-03 22:58:43 +0000626 // Only record the diagnostic if it's part of the source manager we know
627 // about. This effectively drops diagnostics from modules we're building.
628 // FIXME: In the long run, ee don't want to drop source managers from modules.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000629 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
630 StoredDiagnostic *ResultDiag = nullptr;
631 if (StoredDiags) {
632 StoredDiags->emplace_back(Level, Info);
633 ResultDiag = &StoredDiags->back();
634 }
635
636 if (StandaloneDiags) {
637 llvm::Optional<StoredDiagnostic> StoredDiag = llvm::None;
638 if (!ResultDiag) {
639 StoredDiag.emplace(Level, Info);
640 ResultDiag = StoredDiag.getPointer();
641 }
642 StandaloneDiags->push_back(
643 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
644 }
645 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000646}
647
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000648IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
649 return Reader;
650}
651
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000652ASTMutationListener *ASTUnit::getASTMutationListener() {
653 if (WriterData)
654 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000655 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000656}
657
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000658ASTDeserializationListener *ASTUnit::getDeserializationListener() {
659 if (WriterData)
660 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000661 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000662}
663
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000664std::unique_ptr<llvm::MemoryBuffer>
665ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000666 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000667 auto Buffer = FileMgr->getBufferForFile(Filename);
668 if (Buffer)
669 return std::move(*Buffer);
670 if (ErrorStr)
671 *ErrorStr = Buffer.getError().message();
672 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000673}
674
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000675/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000676void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000677 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000678 assert(Diags.get() && "no DiagnosticsEngine was provided");
679 if (CaptureDiagnostics)
Ilya Biryukov200b3282017-06-21 10:24:58 +0000680 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000681}
682
David Blaikie6f7382d2014-08-10 19:08:04 +0000683std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000684 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Richard Smithdbafb6c2017-06-29 23:23:46 +0000685 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000686 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
687 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
688 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
689 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000690 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000691
692 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000693 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
694 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000695 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
696 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000697 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000698
Justin Bognerdbbcb112014-10-14 23:36:06 +0000699 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000700
Richard Smithab755972017-06-05 18:10:11 +0000701 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000702 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000703 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000704 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000705 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
706 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000707 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000708 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000709 AST->getFileManager(),
710 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000711 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000712 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000713 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000714 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000715 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000716 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000717 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000718 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000719 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000720
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000721 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000722 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000723
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000724 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000725
David Blaikie6f7382d2014-08-10 19:08:04 +0000726 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000727 unsigned Counter;
728
David Blaikie41565462017-01-05 19:48:07 +0000729 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000730 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Richard Smith5d2ed482017-06-09 19:22:32 +0000731 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000732 /*IILookup=*/nullptr,
733 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000734 Preprocessor &PP = *AST->PP;
735
Richard Smithdbafb6c2017-06-29 23:23:46 +0000736 if (ToLoad >= LoadASTOnly)
737 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
738 PP.getIdentifierTable(), PP.getSelectorTable(),
739 PP.getBuiltinInfo());
Douglas Gregor83297df2011-09-01 23:39:15 +0000740
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000741 bool disableValid = false;
742 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
743 disableValid = true;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000744 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000745 /*isysroot=*/"",
746 /*DisableValidation=*/disableValid,
747 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000748
David Blaikie2721c322014-08-10 16:54:39 +0000749 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000750 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
Richard Smith18934752017-06-06 00:32:01 +0000751 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000752
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000753 // Attach the AST reader to the AST context as an external AST
754 // source, so that declarations will be deserialized from the
755 // AST file as needed.
756 // We need the external source to be set up before we read the AST, because
757 // eagerly-deserialized declarations may use it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000758 if (AST->Ctx)
759 AST->Ctx->setExternalSource(AST->Reader);
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000760
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000761 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000762 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000763 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000764 break;
Mike Stump11289f42009-09-09 15:08:12 +0000765
Sebastian Redl2c499f62010-08-18 23:56:43 +0000766 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000767 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000768 case ASTReader::OutOfDate:
769 case ASTReader::VersionMismatch:
770 case ASTReader::ConfigurationMismatch:
771 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000772 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000773 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000776 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000777
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000778 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000779
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000780 // Create an AST consumer, even though it isn't used.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000781 if (ToLoad >= LoadASTOnly)
782 AST->Consumer.reset(new ASTConsumer);
783
Sebastian Redl2c499f62010-08-18 23:56:43 +0000784 // Create a semantic analysis object and tell the AST reader about it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000785 if (ToLoad >= LoadEverything) {
786 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
787 AST->TheSema->Initialize();
788 AST->Reader->InitializeSema(*AST->TheSema);
789 }
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000790
Douglas Gregor6b930962013-05-03 22:58:43 +0000791 // Tell the diagnostic client that we have started a source file.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000792 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
Douglas Gregor6b930962013-05-03 22:58:43 +0000793
David Blaikie6f7382d2014-08-10 19:08:04 +0000794 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000795}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000796
797namespace {
798
Ilya Biryukov200b3282017-06-21 10:24:58 +0000799/// \brief Add the given macro to the hash of all top-level entities.
800void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000801 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000802}
803
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000804/// \brief Preprocessor callback class that updates a hash value with the names
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000805/// of all macros that have been defined by the translation unit.
806class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
807 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000808
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000809public:
810 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000811
812 void MacroDefined(const Token &MacroNameTok,
813 const MacroDirective *MD) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000814 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000815 }
816};
817
818/// \brief Add the given declaration to the hash of all top-level entities.
819void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
820 if (!D)
821 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000822
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000823 DeclContext *DC = D->getDeclContext();
824 if (!DC)
825 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000826
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000827 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
828 return;
829
830 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000831 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
832 // For an unscoped enum include the enumerators in the hash since they
833 // enter the top-level namespace.
834 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000835 for (const auto *EI : EnumD->enumerators()) {
836 if (EI->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000837 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000838 }
839 }
840 }
841
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000842 if (ND->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000843 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000844 else if (DeclarationName Name = ND->getDeclName()) {
845 std::string NameStr = Name.getAsString();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000846 Hash = llvm::djbHash(NameStr, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000847 }
848 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000849 }
850
851 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
852 if (Module *Mod = ImportD->getImportedModule()) {
853 std::string ModName = Mod->getFullModuleName();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000854 Hash = llvm::djbHash(ModName, Hash);
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000855 }
856 return;
857 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000858}
859
Daniel Dunbar644dca02009-12-04 08:17:33 +0000860class TopLevelDeclTrackerConsumer : public ASTConsumer {
861 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000862 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000863
Daniel Dunbar644dca02009-12-04 08:17:33 +0000864public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000865 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
866 : Unit(_Unit), Hash(Hash) {
867 Hash = 0;
868 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000869
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000870 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000871 if (!D)
872 return;
873
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000874 // FIXME: Currently ObjC method declarations are incorrectly being
875 // reported as top-level declarations, even though their DeclContext
876 // is the containing ObjC @interface/@implementation. This is a
877 // fundamental problem in the parser right now.
878 if (isa<ObjCMethodDecl>(D))
879 return;
880
881 AddTopLevelDeclarationToHash(D, Hash);
882 Unit.addTopLevelDecl(D);
883
884 handleFileLevelDecl(D);
885 }
886
887 void handleFileLevelDecl(Decl *D) {
888 Unit.addFileLevelDecl(D);
889 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000890 for (auto *I : NSD->decls())
891 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000892 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000893 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000894
Craig Topperafa7cb32014-03-13 06:07:04 +0000895 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000896 for (Decl *TopLevelDecl : D)
897 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000898 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000899 }
900
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000901 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000902 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000903
Craig Topperafa7cb32014-03-13 06:07:04 +0000904 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000905 for (Decl *TopLevelDecl : D)
906 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000907 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000908
Craig Topperafa7cb32014-03-13 06:07:04 +0000909 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000910 return Unit.getASTMutationListener();
911 }
912
Craig Topperafa7cb32014-03-13 06:07:04 +0000913 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000914 return Unit.getDeserializationListener();
915 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000916};
917
918class TopLevelDeclTrackerAction : public ASTFrontendAction {
919public:
920 ASTUnit &Unit;
921
David Blaikie6beb6aa2014-08-10 19:56:51 +0000922 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
923 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000924 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000925 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
926 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000927 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
928 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000929 }
930
931public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000932 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
933
Craig Topperafa7cb32014-03-13 06:07:04 +0000934 bool hasCodeCompletionSupport() const override { return false; }
935 TranslationUnitKind getTranslationUnitKind() override {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000936 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000937 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000938};
939
Ilya Biryukov200b3282017-06-21 10:24:58 +0000940class ASTUnitPreambleCallbacks : public PreambleCallbacks {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000941public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000942 unsigned getHash() const { return Hash; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000943
Ilya Biryukov200b3282017-06-21 10:24:58 +0000944 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000945
Ilya Biryukov200b3282017-06-21 10:24:58 +0000946 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
947 return std::move(TopLevelDeclIDs);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000948 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000949
Ilya Biryukov200b3282017-06-21 10:24:58 +0000950 void AfterPCHEmitted(ASTWriter &Writer) override {
951 TopLevelDeclIDs.reserve(TopLevelDecls.size());
952 for (Decl *D : TopLevelDecls) {
953 // Invalid top-level decls may not have been serialized.
954 if (D->isInvalidDecl())
955 continue;
956 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
957 }
958 }
959
960 void HandleTopLevelDecl(DeclGroupRef DG) override {
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000961 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000962 // FIXME: Currently ObjC method declarations are incorrectly being
963 // reported as top-level declarations, even though their DeclContext
964 // is the containing ObjC @interface/@implementation. This is a
965 // fundamental problem in the parser right now.
966 if (isa<ObjCMethodDecl>(D))
967 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000968 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000969 TopLevelDecls.push_back(D);
970 }
971 }
972
Ilya Biryukov41e90bc2017-12-15 11:27:51 +0000973 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
974 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000975 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000976
977private:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000978 unsigned Hash = 0;
979 std::vector<Decl *> TopLevelDecls;
980 std::vector<serialization::DeclID> TopLevelDeclIDs;
981 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000982};
983
Hans Wennborgdcfba332015-10-06 23:40:43 +0000984} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000985
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000986static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
987 return StoredDiag.getLocation().isValid();
988}
989
990static void
991checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000992 // Get rid of stored diagnostics except the ones from the driver which do not
993 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000994 StoredDiags.erase(
995 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
996 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000997}
998
999static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1000 StoredDiagnostics,
1001 SourceManager &SM) {
1002 // The stored diagnostic has the old source manager in it; update
1003 // the locations to refer into the new source manager. Since we've
1004 // been careful to make sure that the source manager's state
1005 // before and after are identical, so that we can reuse the source
1006 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001007 for (StoredDiagnostic &SD : StoredDiagnostics) {
1008 if (SD.getLocation().isValid()) {
1009 FullSourceLoc Loc(SD.getLocation(), SM);
1010 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001011 }
1012 }
1013}
1014
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001015/// Parse the source file into a translation unit using the given compiler
1016/// invocation, replacing the current translation unit.
1017///
1018/// \returns True if a failure occurred that causes the ASTUnit not to
1019/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001020bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001021 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1022 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001023 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001024 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001025
Ilya Biryukov417085a2017-11-16 16:25:01 +00001026 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1027 if (OverrideMainBuffer) {
1028 assert(Preamble &&
1029 "No preamble was built, but OverrideMainBuffer is not null");
1030 IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS;
1031 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1032 if (OldVFS != VFS && FileMgr) {
1033 assert(OldVFS == FileMgr->getVirtualFileSystem() &&
1034 "VFS passed to Parse and VFS in FileMgr are different");
1035 FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
1036 }
1037 }
1038
Daniel Dunbar764c0822009-12-01 09:51:01 +00001039 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001040 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001041 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001042 if (FileMgr && VFS) {
1043 assert(VFS == FileMgr->getVirtualFileSystem() &&
1044 "VFS passed to Parse and VFS in FileMgr are different");
1045 } else if (VFS) {
1046 Clang->setVirtualFileSystem(VFS);
1047 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001048
1049 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001050 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1051 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001052
Ilya Biryukov417085a2017-11-16 16:25:01 +00001053 Clang->setInvocation(CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001054 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001055
Douglas Gregor8e984da2010-08-04 16:47:14 +00001056 // Set up diagnostics, capturing any diagnostics that would
1057 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001058 Clang->setDiagnostics(&getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001059
Daniel Dunbar764c0822009-12-01 09:51:01 +00001060 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001061 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001062 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001063 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001064 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001065
Daniel Dunbar764c0822009-12-01 09:51:01 +00001066 // Inform the target of the language options.
1067 //
1068 // FIXME: We shouldn't need to do this, the target should be immutable once
1069 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001070 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001071
Ted Kremenek84de4a12011-03-21 18:40:07 +00001072 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001073 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001074 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1075 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001076 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001077 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1078 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001079 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001080
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001081 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001082 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001083 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001084 if (!FileMgr) {
1085 Clang->createFileManager();
1086 FileMgr = &Clang->getFileManager();
1087 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001088
1089 ResetForParse();
1090
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001091 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1092 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001093 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001094 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001095 TopLevelDeclsInPreamble.clear();
1096 }
1097
Daniel Dunbar764c0822009-12-01 09:51:01 +00001098 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 Clang->setFileManager(&getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001100
Daniel Dunbar764c0822009-12-01 09:51:01 +00001101 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001102 Clang->setSourceManager(&getSourceManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001103
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001104 // If the main file has been overridden due to the use of a preamble,
1105 // make that override happen and introduce the preamble.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001106 if (OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001107 // The stored diagnostic has the old source manager in it; update
1108 // the locations to refer into the new source manager. Since we've
1109 // been careful to make sure that the source manager's state
1110 // before and after are identical, so that we can reuse the source
1111 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001112 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001113
1114 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001115 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001116 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001117
1118 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1119 new TopLevelDeclTrackerAction(*this));
1120
Ted Kremenek022a4902011-03-22 01:15:24 +00001121 // Recover resources if we crash before exiting this method.
1122 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1123 ActCleanup(Act.get());
1124
Douglas Gregor32fbe312012-01-20 16:28:04 +00001125 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001126 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001127
Richard Smith26b8f782016-03-25 21:46:44 +00001128 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001129 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1130 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001131 else
1132 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001133
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001134 if (!Act->Execute())
1135 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001136
1137 transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001138
Daniel Dunbar644dca02009-12-04 08:17:33 +00001139 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001140
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001141 FailedParseDiagnostics.clear();
1142
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001143 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001144
Daniel Dunbar764c0822009-12-01 09:51:01 +00001145error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001146 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001147 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001148
1149 // Keep the ownership of the data in the ASTUnit because the client may
1150 // want to see the diagnostics.
1151 transferASTDataFromCompilerInstance(*Clang);
1152 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001153 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001154 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001155 return true;
1156}
1157
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001158static std::pair<unsigned, unsigned>
1159makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1160 const LangOptions &LangOpts) {
1161 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1162 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1163 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1164 return std::make_pair(Offset, EndOffset);
1165}
1166
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001167static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1168 const LangOptions &LangOpts,
1169 const FixItHint &InFix) {
1170 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001171 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1172 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1173 LangOpts);
1174 OutFix.CodeToInsert = InFix.CodeToInsert;
1175 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001176 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001177}
1178
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001179static ASTUnit::StandaloneDiagnostic
1180makeStandaloneDiagnostic(const LangOptions &LangOpts,
1181 const StoredDiagnostic &InDiag) {
1182 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001183 OutDiag.ID = InDiag.getID();
1184 OutDiag.Level = InDiag.getLevel();
1185 OutDiag.Message = InDiag.getMessage();
1186 OutDiag.LocOffset = 0;
1187 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001188 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001189 const SourceManager &SM = InDiag.getLocation().getManager();
1190 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1191 OutDiag.Filename = SM.getFilename(FileLoc);
1192 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001193 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001194 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001195 for (const CharSourceRange &Range : InDiag.getRanges())
1196 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1197 for (const FixItHint &FixIt : InDiag.getFixIts())
1198 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001199
1200 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001201}
1202
Douglas Gregor4dde7492010-07-23 23:58:40 +00001203/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1204/// the source file.
1205///
1206/// This routine will compute the preamble of the main source file. If a
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001207/// non-trivial preamble is found, it will precompile that preamble into a
Douglas Gregor4dde7492010-07-23 23:58:40 +00001208/// precompiled header so that the precompiled preamble can be used to reduce
1209/// reparsing time. If a precompiled preamble has already been constructed,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001210/// this routine will determine if it is still valid and, if so, avoid
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211/// rebuilding the precompiled preamble.
1212///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001213/// \param AllowRebuild When true (the default), this routine is
1214/// allowed to rebuild the precompiled preamble if it is found to be
1215/// out-of-date.
1216///
1217/// \param MaxLines When non-zero, the maximum number of lines that
1218/// can occur within the preamble.
1219///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001220/// \returns If the precompiled preamble can be used, returns a newly-allocated
1221/// buffer that should be used in place of the main file when doing so.
1222/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001223std::unique_ptr<llvm::MemoryBuffer>
1224ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001225 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001226 const CompilerInvocation &PreambleInvocationIn,
1227 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
Rafael Espindola2346a372014-08-18 18:47:08 +00001228 unsigned MaxLines) {
1229
Ilya Biryukov200b3282017-06-21 10:24:58 +00001230 auto MainFilePath =
1231 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1232 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1233 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1234 MainFilePath);
1235 if (!MainFileBuffer)
Craig Topper49a27902014-05-22 04:46:25 +00001236 return nullptr;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001237
Ilya Biryukov200b3282017-06-21 10:24:58 +00001238 PreambleBounds Bounds =
1239 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1240 MainFileBuffer.get(), MaxLines);
1241 if (!Bounds.Size)
1242 return nullptr;
Alp Toker1b070d22014-07-07 07:47:20 +00001243
Ilya Biryukov200b3282017-06-21 10:24:58 +00001244 if (Preamble) {
1245 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1246 VFS.get())) {
1247 // Okay! We can re-use the precompiled preamble.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001248
Ilya Biryukov200b3282017-06-21 10:24:58 +00001249 // Set the state of the diagnostic object to mimic its state
1250 // after parsing the preamble.
1251 getDiagnostics().Reset();
1252 ProcessWarningOptions(getDiagnostics(),
1253 PreambleInvocationIn.getDiagnosticOpts());
1254 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Alp Toker1b070d22014-07-07 07:47:20 +00001255
Ilya Biryukov200b3282017-06-21 10:24:58 +00001256 PreambleRebuildCounter = 1;
1257 return MainFileBuffer;
1258 } else {
1259 Preamble.reset();
1260 PreambleDiagnostics.clear();
1261 TopLevelDeclsInPreamble.clear();
1262 PreambleRebuildCounter = 1;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001264 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001265
1266 // If the preamble rebuild counter > 1, it's because we previously
1267 // failed to build a preamble and we're not yet ready to try
1268 // again. Decrement the counter and return a failure.
1269 if (PreambleRebuildCounter > 1) {
1270 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001271 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001272 }
1273
Ilya Biryukov200b3282017-06-21 10:24:58 +00001274 assert(!Preamble && "No Preamble should be stored at that point");
1275 // If we aren't allowed to rebuild the precompiled preamble, just
1276 // return now.
1277 if (!AllowRebuild)
Ben Langmuir8832c062014-04-15 18:16:25 +00001278 return nullptr;
1279
Ilya Biryukov200b3282017-06-21 10:24:58 +00001280 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1281 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001282 ASTUnitPreambleCallbacks Callbacks;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001283 {
1284 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1285 if (CaptureDiagnostics)
1286 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1287 &NewPreambleDiagsStandalone);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001288
Ilya Biryukov200b3282017-06-21 10:24:58 +00001289 // We did not previously compute a preamble, or it can't be reused anyway.
1290 SimpleTimer PreambleTimer(WantTiming);
1291 PreambleTimer.setOutput("Precompiling preamble");
Ahmed Charlesb8984322014-03-07 20:03:18 +00001292
Ilya Biryukov200b3282017-06-21 10:24:58 +00001293 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1294 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +00001295 PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
Ilya Biryukov200b3282017-06-21 10:24:58 +00001296 if (NewPreamble) {
1297 Preamble = std::move(*NewPreamble);
1298 PreambleRebuildCounter = 1;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001299 } else {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001300 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1301 case BuildPreambleError::CouldntCreateTempFile:
1302 case BuildPreambleError::PreambleIsEmpty:
1303 // Try again next time.
1304 PreambleRebuildCounter = 1;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001305 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001306 case BuildPreambleError::CouldntCreateTargetInfo:
1307 case BuildPreambleError::BeginSourceFileFailed:
1308 case BuildPreambleError::CouldntEmitPCH:
1309 case BuildPreambleError::CouldntCreateVFSOverlay:
1310 // These erros are more likely to repeat, retry after some period.
1311 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001312 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001313 }
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001314 llvm_unreachable("unexpected BuildPreambleError");
Dmitri Gribenko47652522013-12-20 00:16:25 +00001315 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001316 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001317
Ilya Biryukov200b3282017-06-21 10:24:58 +00001318 assert(Preamble && "Preamble wasn't built");
1319
1320 TopLevelDecls.clear();
1321 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1322 PreambleTopLevelHashValue = Callbacks.getHash();
1323
1324 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1325
1326 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1327 StoredDiagnostics = std::move(NewPreambleDiags);
1328 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
Alp Toker1b070d22014-07-07 07:47:20 +00001329
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001330 // If the hash of top-level entities differs from the hash of the top-level
1331 // entities the last time we rebuilt the preamble, clear out the completion
1332 // cache.
1333 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1334 CompletionCacheTopLevelHashValue = 0;
1335 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1336 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001337
Ilya Biryukov200b3282017-06-21 10:24:58 +00001338 return MainFileBuffer;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001339}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001340
Douglas Gregore9db88f2010-08-03 19:06:41 +00001341void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001342 assert(Preamble && "Should only be called when preamble was built");
1343
Douglas Gregore9db88f2010-08-03 19:06:41 +00001344 std::vector<Decl *> Resolved;
1345 Resolved.reserve(TopLevelDeclsInPreamble.size());
1346 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001347 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001348 // Resolve the declaration ID to an actual declaration, possibly
1349 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001350 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001351 Resolved.push_back(D);
1352 }
1353 TopLevelDeclsInPreamble.clear();
1354 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1355}
1356
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001357void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001358 // Steal the created target, context, and preprocessor if they have been
1359 // created.
1360 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001361 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001362 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001363 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001364 if (CI.hasASTContext())
1365 Ctx = &CI.getASTContext();
1366 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001367 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001368 CI.setSourceManager(nullptr);
1369 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001370 if (CI.hasTarget())
1371 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001372 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001373 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001374}
1375
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001376StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001377 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1378 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1379 if (Input.isFile())
1380 return Input.getFile();
1381 else
1382 return Input.getBuffer()->getBufferIdentifier();
1383 }
1384
1385 if (SourceMgr) {
1386 if (const FileEntry *
1387 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1388 return FE->getName();
1389 }
1390
1391 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001392}
1393
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001394StringRef ASTUnit::getASTFileName() const {
1395 if (!isMainFileAST())
1396 return StringRef();
1397
1398 serialization::ModuleFile &
1399 Mod = Reader->getModuleManager().getPrimaryModule();
1400 return Mod.FileName;
1401}
1402
David Blaikieea4395e2017-01-06 19:49:01 +00001403std::unique_ptr<ASTUnit>
1404ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1405 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1406 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1407 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001408 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001409 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1410 createVFSFromCompilerInvocation(*CI, *Diags);
1411 if (!VFS)
1412 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001413 AST->Diagnostics = Diags;
1414 AST->FileSystemOpts = CI->getFileSystemOpts();
1415 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001416 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001417 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1418 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1419 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001420 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001421
David Blaikieea4395e2017-01-06 19:49:01 +00001422 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001423}
1424
Ahmed Charlesb8984322014-03-07 20:03:18 +00001425ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001426 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001427 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001428 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001429 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001430 bool OnlyLocalDecls, bool CaptureDiagnostics,
1431 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1432 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1433 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001434 assert(CI && "A CompilerInvocation is required");
1435
Ahmed Charlesb8984322014-03-07 20:03:18 +00001436 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001437 ASTUnit *AST = Unit;
1438 if (!AST) {
1439 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001440 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001441 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001442 if (!AST)
1443 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001444 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001445
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001446 if (!ResourceFilesPath.empty()) {
1447 // Override the resources path.
1448 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1449 }
1450 AST->OnlyLocalDecls = OnlyLocalDecls;
1451 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001452 if (PrecompilePreambleAfterNParses > 0)
1453 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001454 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001455 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001456 AST->IncludeBriefCommentsInCodeCompletion
1457 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001458
1459 // Recover resources if we crash before exiting this method.
1460 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001461 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001462 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1463 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001464 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001465
1466 // We'll manage file buffers ourselves.
1467 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1468 CI->getFrontendOpts().DisableFree = false;
1469 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1470
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001471 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001472 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001473 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001474
1475 // Recover resources if we crash before exiting this method.
1476 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1477 CICleanup(Clang.get());
1478
David Blaikieea4395e2017-01-06 19:49:01 +00001479 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001480 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001481
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001482 // Set up diagnostics, capturing any diagnostics that would
1483 // otherwise be dropped.
1484 Clang->setDiagnostics(&AST->getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001485
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001486 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001487 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001488 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001489 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001490 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001491
1492 // Inform the target of the language options.
1493 //
1494 // FIXME: We shouldn't need to do this, the target should be immutable once
1495 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001496 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001497
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001498 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1499 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001500 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1501 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001502 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001503 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1504 InputKind::LLVM_IR &&
1505 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001506
1507 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001508 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001509 AST->Ctx = nullptr;
1510 AST->PP = nullptr;
1511 AST->Reader = nullptr;
1512
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001513 // Create a file manager object to provide access to and cache the filesystem.
1514 Clang->setFileManager(&AST->getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001515
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001516 // Create the source manager.
1517 Clang->setSourceManager(&AST->getSourceManager());
1518
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001519 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001520
Ahmed Charlesb8984322014-03-07 20:03:18 +00001521 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001522 if (!Act) {
1523 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1524 Act = TrackerAct.get();
1525 }
1526
1527 // Recover resources if we crash before exiting this method.
1528 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1529 ActCleanup(TrackerAct.get());
1530
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001531 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1532 AST->transferASTDataFromCompilerInstance(*Clang);
1533 if (OwnAST && ErrAST)
1534 ErrAST->swap(OwnAST);
1535
Craig Topper49a27902014-05-22 04:46:25 +00001536 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001537 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001538
1539 if (Persistent && !TrackerAct) {
1540 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001541 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1542 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001543 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001544 if (Clang->hasASTConsumer())
1545 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001546 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1547 *AST, AST->getCurrentTopLevelHashValue()));
1548 Clang->setASTConsumer(
1549 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001550 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001551 if (!Act->Execute()) {
1552 AST->transferASTDataFromCompilerInstance(*Clang);
1553 if (OwnAST && ErrAST)
1554 ErrAST->swap(OwnAST);
1555
Craig Topper49a27902014-05-22 04:46:25 +00001556 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001557 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001558
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001559 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001560 AST->transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001561
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001562 Act->EndSourceFile();
1563
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001564 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001565 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001566 else
1567 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001568}
1569
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001570bool ASTUnit::LoadFromCompilerInvocation(
1571 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001572 unsigned PrecompilePreambleAfterNParses,
1573 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001574 if (!Invocation)
1575 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001576
1577 assert(VFS && "VFS is null");
1578
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001579 // We'll manage file buffers ourselves.
1580 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1581 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001582 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001583 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001584
Rafael Espindola32482082014-08-18 16:23:45 +00001585 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001586 if (PrecompilePreambleAfterNParses > 0) {
1587 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001588 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001589 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001590 getDiagnostics().Reset();
1591 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001592 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001593
Douglas Gregor16896c42010-10-28 15:44:59 +00001594 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001595 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001596
Ted Kremenek022a4902011-03-22 01:15:24 +00001597 // Recover resources if we crash before exiting this method.
1598 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001599 MemBufferCleanup(OverrideMainBuffer.get());
1600
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001601 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001602}
1603
David Blaikie103a2de2014-04-25 17:01:33 +00001604std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001605 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001606 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001607 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001608 bool OnlyLocalDecls, bool CaptureDiagnostics,
1609 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1610 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1611 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001612 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001613 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001614 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001615 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001616 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001617 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001618 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001619 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001620 AST->IncludeBriefCommentsInCodeCompletion
1621 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001622 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001623 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1624 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001625 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001626
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001627 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001628 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1629 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001630 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1631 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001632 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001633
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001634 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001635 PrecompilePreambleAfterNParses,
1636 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001637 return nullptr;
1638 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001639}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001640
Ahmed Charlesb8984322014-03-07 20:03:18 +00001641ASTUnit *ASTUnit::LoadFromCommandLine(
1642 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001643 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001644 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1645 bool OnlyLocalDecls, bool CaptureDiagnostics,
1646 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001647 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001648 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1649 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001650 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001651 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1652 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001653 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001654
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001655 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001656
1657 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001658
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001659 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001660
Ilya Biryukov200b3282017-06-21 10:24:58 +00001661 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1662 &StoredDiagnostics, nullptr);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001663
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001664 CI = clang::createInvocationFromCommandLine(
Ilya Biryukovafdadf52017-06-28 15:06:34 +00001665 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001666 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001667 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001668 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001669
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001670 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001671 for (const auto &RemappedFile : RemappedFiles) {
1672 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1673 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001674 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001675 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1676 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1677 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001678 PPOpts.SingleFileParseMode = SingleFileParse;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001679
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001680 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001681 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001682
Erik Verbruggen6e922512012-04-12 10:11:59 +00001683 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1684
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001685 if (ModuleFormat)
1686 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1687
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001688 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001689 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001690 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001691 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001692 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001693 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001694 if (!VFS)
1695 VFS = vfs::getRealFileSystem();
1696 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001697 if (!VFS)
1698 return nullptr;
1699 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001700 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001701 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001702 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001703 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001704 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001705 AST->IncludeBriefCommentsInCodeCompletion
1706 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001707 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001708 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001709 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001710 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001711 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001712 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001713 // Zero out now to ease cleanup during crash recovery.
1714 CI = nullptr;
1715 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001716
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001717 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001718 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1719 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001720
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001721 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001722 PrecompilePreambleAfterNParses,
1723 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001724 // Some error occurred, if caller wants to examine diagnostics, pass it the
1725 // ASTUnit.
1726 if (ErrAST) {
1727 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1728 ErrAST->swap(AST);
1729 }
Craig Topper49a27902014-05-22 04:46:25 +00001730 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001731 }
1732
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001733 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001734}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001735
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001736bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001737 ArrayRef<RemappedFile> RemappedFiles,
1738 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001739 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001740 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001741
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001742 if (!VFS) {
1743 assert(FileMgr && "FileMgr is null on Reparse call");
1744 VFS = FileMgr->getVirtualFileSystem();
1745 }
1746
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001747 clearFileLevelDecls();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001748
Douglas Gregor16896c42010-10-28 15:44:59 +00001749 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001750 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001751
Douglas Gregor0e119552010-07-31 00:40:00 +00001752 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001753 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00001754 for (const auto &RB : PPOpts.RemappedFileBuffers)
1755 delete RB.second;
1756
Douglas Gregor0e119552010-07-31 00:40:00 +00001757 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001758 for (const auto &RemappedFile : RemappedFiles) {
1759 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1760 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001761 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001762
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001763 // If we have a preamble file lying around, or if we might try to
1764 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00001765 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001766 if (Preamble || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001767 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001768 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1769
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001770
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001771 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00001772 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001773 getDiagnostics().Reset();
1774 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001775 if (OverrideMainBuffer)
1776 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001777
Douglas Gregor4dde7492010-07-23 23:58:40 +00001778 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001779 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001780 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00001781
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001782 // If we're caching global code-completion results, and the top-level
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001783 // declarations have changed, clear out the code-completion cache.
1784 if (!Result && ShouldCacheCodeCompletionResults &&
1785 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1786 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001787
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001788 // We now need to clear out the completion info related to this translation
1789 // unit; it'll be recreated if necessary.
1790 CCTUInfo.reset();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001791
Douglas Gregor4dde7492010-07-23 23:58:40 +00001792 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001793}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001794
Erik Verbruggen346066b2017-05-30 14:25:54 +00001795void ASTUnit::ResetForParse() {
1796 SavedMainFileBuffer.reset();
1797
1798 SourceMgr.reset();
1799 TheSema.reset();
1800 Ctx.reset();
1801 PP.reset();
1802 Reader.reset();
1803
1804 TopLevelDecls.clear();
1805 clearFileLevelDecls();
1806}
1807
Douglas Gregorb14904c2010-08-13 22:48:40 +00001808//----------------------------------------------------------------------------//
1809// Code completion
1810//----------------------------------------------------------------------------//
1811
1812namespace {
1813 /// \brief Code completion consumer that combines the cached code-completion
1814 /// results from an ASTUnit with the code-completion results provided to it,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001815 /// then passes the result on to
Douglas Gregorb14904c2010-08-13 22:48:40 +00001816 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00001817 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001818 ASTUnit &AST;
1819 CodeCompleteConsumer &Next;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001820
Douglas Gregorb14904c2010-08-13 22:48:40 +00001821 public:
1822 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001823 const CodeCompleteOptions &CodeCompleteOpts)
1824 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1825 AST(AST), Next(Next)
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001826 {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001827 // Compute the set of contexts in which we will look when we don't have
1828 // any information about the specific context.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001829 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00001830 = (1LL << CodeCompletionContext::CCC_TopLevel)
1831 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1832 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1833 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1834 | (1LL << CodeCompletionContext::CCC_Statement)
1835 | (1LL << CodeCompletionContext::CCC_Expression)
1836 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1837 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1838 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1839 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1840 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1841 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1842 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00001843
David Blaikiebbafb8a2012-03-11 07:00:24 +00001844 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00001845 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1846 | (1LL << CodeCompletionContext::CCC_UnionTag)
1847 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001848 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001849
1850 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1851 CodeCompletionResult *Results,
1852 unsigned NumResults) override;
1853
1854 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1855 OverloadCandidate *Candidates,
1856 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001857 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1858 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001859
1860 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001861 return Next.getAllocator();
1862 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001863
Craig Topperafa7cb32014-03-13 06:07:04 +00001864 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001865 return Next.getCodeCompletionTUInfo();
1866 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001867 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001868} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00001869
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001870/// \brief Helper function that computes which global names are hidden by the
1871/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001872static void CalculateHiddenNames(const CodeCompletionContext &Context,
1873 CodeCompletionResult *Results,
1874 unsigned NumResults,
1875 ASTContext &Ctx,
1876 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001877 bool OnlyTagNames = false;
1878 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001879 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001880 case CodeCompletionContext::CCC_TopLevel:
1881 case CodeCompletionContext::CCC_ObjCInterface:
1882 case CodeCompletionContext::CCC_ObjCImplementation:
1883 case CodeCompletionContext::CCC_ObjCIvarList:
1884 case CodeCompletionContext::CCC_ClassStructUnion:
1885 case CodeCompletionContext::CCC_Statement:
1886 case CodeCompletionContext::CCC_Expression:
1887 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001888 case CodeCompletionContext::CCC_DotMemberAccess:
1889 case CodeCompletionContext::CCC_ArrowMemberAccess:
1890 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001891 case CodeCompletionContext::CCC_Namespace:
1892 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001893 case CodeCompletionContext::CCC_Name:
1894 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001895 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001896 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001897 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001898
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001899 case CodeCompletionContext::CCC_EnumTag:
1900 case CodeCompletionContext::CCC_UnionTag:
1901 case CodeCompletionContext::CCC_ClassOrStructTag:
1902 OnlyTagNames = true;
1903 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001904
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001905 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001906 case CodeCompletionContext::CCC_MacroName:
1907 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001908 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001909 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001910 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001911 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001912 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001913 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001914 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00001915 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1916 case CodeCompletionContext::CCC_ObjCClassMessage:
1917 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001918 // We're looking for nothing, or we're looking for names that cannot
1919 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001920 return;
1921 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001922
John McCall276321a2010-08-25 06:19:51 +00001923 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001924 for (unsigned I = 0; I != NumResults; ++I) {
1925 if (Results[I].Kind != Result::RK_Declaration)
1926 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001927
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001928 unsigned IDNS
1929 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1930
1931 bool Hiding = false;
1932 if (OnlyTagNames)
1933 Hiding = (IDNS & Decl::IDNS_Tag);
1934 else {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001935 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001936 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1937 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001938 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001939 HiddenIDNS |= Decl::IDNS_Tag;
1940 Hiding = (IDNS & HiddenIDNS);
1941 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001942
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001943 if (!Hiding)
1944 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001945
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001946 DeclarationName Name = Results[I].Declaration->getDeclName();
1947 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1948 HiddenNames.insert(Identifier->getName());
1949 else
1950 HiddenNames.insert(Name.getAsString());
1951 }
1952}
1953
Douglas Gregord46cf182010-08-16 20:01:48 +00001954void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1955 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001956 CodeCompletionResult *Results,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001957 unsigned NumResults) {
Douglas Gregord46cf182010-08-16 20:01:48 +00001958 // Merge the results we were given with the results we cached.
1959 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00001960 uint64_t InContexts =
1961 Context.getKind() == CodeCompletionContext::CCC_Recovery
1962 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001963 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001964 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001965 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001966 SmallVector<Result, 8> AllResults;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001967 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001968 C = AST.cached_completion_begin(),
1969 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001970 C != CEnd; ++C) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001971 // If the context we are in matches any of the contexts we are
Douglas Gregord46cf182010-08-16 20:01:48 +00001972 // interested in, we'll add this result.
1973 if ((C->ShowInContexts & InContexts) == 0)
1974 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001975
Douglas Gregord46cf182010-08-16 20:01:48 +00001976 // If we haven't added any results previously, do so now.
1977 if (!AddedResult) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001978 CalculateHiddenNames(Context, Results, NumResults, S.Context,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001979 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001980 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1981 AddedResult = true;
1982 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001983
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001984 // Determine whether this global completion result is hidden by a local
1985 // completion result. If so, skip it.
1986 if (C->Kind != CXCursor_MacroDefinition &&
1987 HiddenNames.count(C->Completion->getTypedText()))
1988 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001989
Douglas Gregord46cf182010-08-16 20:01:48 +00001990 // Adjust priority based on similar type classes.
1991 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00001992 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001993 if (!Context.getPreferredType().isNull()) {
1994 if (C->Kind == CXCursor_MacroDefinition) {
1995 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001996 S.getLangOpts(),
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001997 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001998 } else if (C->Type) {
1999 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002000 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002001 Context.getPreferredType().getUnqualifiedType());
2002 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2003 if (ExpectedSTC == C->TypeClass) {
2004 // We know this type is similar; check for an exact match.
2005 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002006 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002007 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002008 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002009 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2010 Priority /= CCF_ExactTypeMatch;
2011 else
2012 Priority /= CCF_SimilarTypeMatch;
2013 }
2014 }
2015 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002016
Douglas Gregor12785102010-08-24 20:21:13 +00002017 // Adjust the completion string, if required.
2018 if (C->Kind == CXCursor_MacroDefinition &&
2019 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2020 // Create a new code-completion string that just contains the
2021 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002022 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2023 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002024 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002025 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002026 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002027 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002028
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002029 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002030 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002031 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002032
Douglas Gregord46cf182010-08-16 20:01:48 +00002033 // If we did not add any cached completion results, just forward the
2034 // results we were given to the next consumer.
2035 if (!AddedResult) {
2036 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2037 return;
2038 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002039
Douglas Gregord46cf182010-08-16 20:01:48 +00002040 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2041 AllResults.size());
2042}
2043
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002044void ASTUnit::CodeComplete(
2045 StringRef File, unsigned Line, unsigned Column,
2046 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2047 bool IncludeCodePatterns, bool IncludeBriefComments,
2048 CodeCompleteConsumer &Consumer,
2049 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2050 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2051 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2052 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002053 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002054 return;
2055
Douglas Gregor16896c42010-10-28 15:44:59 +00002056 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002057 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002058 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002059
David Blaikieea4395e2017-01-06 19:49:01 +00002060 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002061
2062 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002063 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002064 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002065
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002066 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2067 CachedCompletionResults.empty();
2068 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2069 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2070 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
Sam McCallbb2cf632018-01-12 14:51:47 +00002071 CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002072
2073 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2074
Douglas Gregor8e984da2010-08-04 16:47:14 +00002075 FrontendOpts.CodeCompletionAt.FileName = File;
2076 FrontendOpts.CodeCompletionAt.Line = Line;
2077 FrontendOpts.CodeCompletionAt.Column = Column;
2078
2079 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002080 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002081
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002082 // Spell-checking and warnings are wasteful during code-completion.
2083 LangOpts.SpellChecking = false;
2084 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2085
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002086 std::unique_ptr<CompilerInstance> Clang(
2087 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002088
2089 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002090 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2091 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002092
David Blaikieea4395e2017-01-06 19:49:01 +00002093 auto &Inv = *CCInvocation;
2094 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002095 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002096
Douglas Gregor8e984da2010-08-04 16:47:14 +00002097 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002098 Clang->setDiagnostics(&Diag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002099 CaptureDroppedDiagnostics Capture(true,
2100 Clang->getDiagnostics(),
Ilya Biryukov200b3282017-06-21 10:24:58 +00002101 &StoredDiagnostics, nullptr);
David Blaikieea4395e2017-01-06 19:49:01 +00002102 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2103
Douglas Gregor8e984da2010-08-04 16:47:14 +00002104 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002105 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002106 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002107 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002108 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002109 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002110 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002111
Douglas Gregor8e984da2010-08-04 16:47:14 +00002112 // Inform the target of the language options.
2113 //
2114 // FIXME: We shouldn't need to do this, the target should be immutable once
2115 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002116 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002117
Ted Kremenek84de4a12011-03-21 18:40:07 +00002118 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002119 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002120 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2121 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002122 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002123 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2124 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002125 "IR inputs not support here!");
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002126
Douglas Gregor8e984da2010-08-04 16:47:14 +00002127 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002128 Clang->setFileManager(&FileMgr);
2129 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002130
2131 // Remap files.
2132 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002133 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002134 for (const auto &RemappedFile : RemappedFiles) {
2135 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2136 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002137 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002138
Douglas Gregorb14904c2010-08-13 22:48:40 +00002139 // Use the code completion consumer we were given, but adding any cached
2140 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002141 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002142 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002143 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002144
Douglas Gregor028d3e42010-08-09 20:45:32 +00002145 // If we have a precompiled preamble, try to use it. We only allow
2146 // the use of the precompiled preamble if we're if the completion
2147 // point is within the main file, after the end of the precompiled
2148 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002149 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002150 if (Preamble) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002151 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002152
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002153 auto VFS = FileMgr.getVirtualFileSystem();
2154 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2155 if (CompleteFileStatus) {
2156 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2157
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002158 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002159 auto MainStatus = VFS->status(MainPath);
2160 if (MainStatus) {
2161 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002162 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002163 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002164 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002165 }
2166 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002167 }
2168
2169 // If the main file has been overridden due to the use of a preamble,
2170 // make that override happen and introduce the preamble.
2171 if (OverrideMainBuffer) {
Ilya Biryukov417085a2017-11-16 16:25:01 +00002172 assert(Preamble &&
2173 "No preamble was built, but OverrideMainBuffer is not null");
2174
2175 auto VFS = FileMgr.getVirtualFileSystem();
2176 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2177 OverrideMainBuffer.get());
2178 // FIXME: there is no way to update VFS if it was changed by
2179 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2180 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2181 // PCH files are always readable.
Rafael Espindola2346a372014-08-18 18:47:08 +00002182 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002183 } else {
2184 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2185 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002186 }
2187
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002188 // Disable the preprocessing record if modules are not enabled.
2189 if (!Clang->getLangOpts().Modules)
2190 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002191
2192 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002193 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002194 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002195 Act->Execute();
2196 Act->EndSourceFile();
2197 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002198}
Douglas Gregore9386682010-08-13 05:36:37 +00002199
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002200bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002201 if (HadModuleLoaderFatalFailure)
2202 return true;
2203
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002204 // Write to a temporary file and later rename it to the actual file, to avoid
2205 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002206 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002207 TempPath = File;
2208 TempPath += "-%%%%%%%%";
2209 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002210 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002211 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002212
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002213 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
Douglas Gregore9386682010-08-13 05:36:37 +00002214 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002215 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002216
2217 serialize(Out);
2218 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002219 if (Out.has_error()) {
2220 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002221 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002222 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002223
Yaron Keren92e1b622015-03-18 10:17:07 +00002224 if (llvm::sys::fs::rename(TempPath, File)) {
2225 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002226 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002227 }
2228
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002229 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002230}
2231
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002232static bool serializeUnit(ASTWriter &Writer,
2233 SmallVectorImpl<char> &Buffer,
2234 Sema &S,
2235 bool hasErrors,
2236 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002237 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002238
2239 // Write the generated bitstream to "Out".
2240 if (!Buffer.empty())
2241 OS.write(Buffer.data(), Buffer.size());
2242
2243 return false;
2244}
2245
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002247 // For serialization we are lenient if the errors were only warn-as-error kind.
2248 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002249
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002250 if (WriterData)
2251 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2252 getSema(), hasErrors, OS);
2253
Daniel Dunbar9a963862012-02-29 20:31:23 +00002254 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002255 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002256 MemoryBufferCache PCMCache;
2257 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002258 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002259}
Douglas Gregor925296b2011-07-19 16:10:42 +00002260
2261typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2262
Douglas Gregor925296b2011-07-19 16:10:42 +00002263void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002264 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002265 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002266 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002267 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002268 // Map the standalone diagnostic into the new source manager. We also need to
2269 // remap all the locations to the new view. This includes the diag location,
2270 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002271 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002272 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002273 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002274
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002275 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002276 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002277 if (SD.Filename.empty())
2278 continue;
2279 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2280 if (!FE)
2281 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002282 SourceLocation FileLoc;
2283 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2284 if (ItFileID == PreambleSrcLocCache.end()) {
2285 FileID FID = SrcMgr.translateFile(FE);
2286 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2287 PreambleSrcLocCache[SD.Filename] = FileLoc;
2288 } else {
2289 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002290 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002291
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002292 if (FileLoc.isInvalid())
2293 continue;
2294 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002295 FullSourceLoc Loc(L, SrcMgr);
2296
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002297 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002298 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002299 for (const auto &Range : SD.Ranges) {
2300 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2301 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002302 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002303 }
2304
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002305 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002306 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002307 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002308 FixIts.push_back(FixItHint());
2309 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002310 FH.CodeToInsert = FixIt.CodeToInsert;
2311 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2312 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002313 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002314 }
2315
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002316 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002317 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002318 }
2319 Result.swap(Out);
2320}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002321
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002322void ASTUnit::addFileLevelDecl(Decl *D) {
2323 assert(D);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002324
Douglas Gregor61d63d02011-11-07 18:53:57 +00002325 // We only care about local declarations.
2326 if (D->isFromASTFile())
2327 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002328
2329 SourceManager &SM = *SourceMgr;
2330 SourceLocation Loc = D->getLocation();
2331 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2332 return;
2333
2334 // We only keep track of the file-level declarations of each file.
2335 if (!D->getLexicalDeclContext()->isFileContext())
2336 return;
2337
2338 SourceLocation FileLoc = SM.getFileLoc(Loc);
2339 assert(SM.isLocalSourceLocation(FileLoc));
2340 FileID FID;
2341 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002342 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002343 if (FID.isInvalid())
2344 return;
2345
2346 LocDeclsTy *&Decls = FileDecls[FID];
2347 if (!Decls)
2348 Decls = new LocDeclsTy();
2349
2350 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2351
2352 if (Decls->empty() || Decls->back().first <= Offset) {
2353 Decls->push_back(LocDecl);
2354 return;
2355 }
2356
Benjamin Kramer45025c02013-08-24 13:22:59 +00002357 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2358 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002359
2360 Decls->insert(I, LocDecl);
2361}
2362
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002363void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2364 SmallVectorImpl<Decl *> &Decls) {
2365 if (File.isInvalid())
2366 return;
2367
2368 if (SourceMgr->isLoadedFileID(File)) {
2369 assert(Ctx->getExternalSource() && "No external source!");
2370 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2371 Decls);
2372 }
2373
2374 FileDeclsTy::iterator I = FileDecls.find(File);
2375 if (I == FileDecls.end())
2376 return;
2377
2378 LocDeclsTy &LocDecls = *I->second;
2379 if (LocDecls.empty())
2380 return;
2381
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002382 LocDeclsTy::iterator BeginIt =
2383 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002384 std::make_pair(Offset, (Decl *)nullptr),
2385 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002386 if (BeginIt != LocDecls.begin())
2387 --BeginIt;
2388
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002389 // If we are pointing at a top-level decl inside an objc container, we need
2390 // to backtrack until we find it otherwise we will fail to report that the
2391 // region overlaps with an objc container.
2392 while (BeginIt != LocDecls.begin() &&
2393 BeginIt->second->isTopLevelDeclInObjCContainer())
2394 --BeginIt;
2395
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002396 LocDeclsTy::iterator EndIt = std::upper_bound(
2397 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002398 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002399 if (EndIt != LocDecls.end())
2400 ++EndIt;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002401
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002402 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2403 Decls.push_back(DIt->second);
2404}
2405
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002406SourceLocation ASTUnit::getLocation(const FileEntry *File,
2407 unsigned Line, unsigned Col) const {
2408 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002409 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002410 return SM.getMacroArgExpandedLocation(Loc);
2411}
2412
2413SourceLocation ASTUnit::getLocation(const FileEntry *File,
2414 unsigned Offset) const {
2415 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002416 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002417 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2418}
2419
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002420/// \brief If \arg Loc is a loaded location from the preamble, returns
2421/// the corresponding local location of the main file, otherwise it returns
2422/// \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002423SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002424 FileID PreambleID;
2425 if (SourceMgr)
2426 PreambleID = SourceMgr->getPreambleFileID();
2427
Ilya Biryukov200b3282017-06-21 10:24:58 +00002428 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002429 return Loc;
2430
2431 unsigned Offs;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002432 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002433 SourceLocation FileLoc
2434 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2435 return FileLoc.getLocWithOffset(Offs);
2436 }
2437
2438 return Loc;
2439}
2440
2441/// \brief If \arg Loc is a local location of the main file but inside the
2442/// preamble chunk, returns the corresponding loaded location from the
2443/// preamble, otherwise it returns \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002444SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002445 FileID PreambleID;
2446 if (SourceMgr)
2447 PreambleID = SourceMgr->getPreambleFileID();
2448
Ilya Biryukov200b3282017-06-21 10:24:58 +00002449 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002450 return Loc;
2451
2452 unsigned Offs;
2453 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Ilya Biryukov200b3282017-06-21 10:24:58 +00002454 Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002455 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2456 return FileLoc.getLocWithOffset(Offs);
2457 }
2458
2459 return Loc;
2460}
2461
Vedant Kumar525a7f62017-07-25 19:53:27 +00002462bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002463 FileID FID;
2464 if (SourceMgr)
2465 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002466
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002467 if (Loc.isInvalid() || FID.isInvalid())
2468 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002469
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002470 return SourceMgr->isInFileID(Loc, FID);
2471}
2472
Vedant Kumar525a7f62017-07-25 19:53:27 +00002473bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002474 FileID FID;
2475 if (SourceMgr)
2476 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002477
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002478 if (Loc.isInvalid() || FID.isInvalid())
2479 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002480
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002481 return SourceMgr->isInFileID(Loc, FID);
2482}
2483
Vedant Kumar525a7f62017-07-25 19:53:27 +00002484SourceLocation ASTUnit::getEndOfPreambleFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002485 FileID FID;
2486 if (SourceMgr)
2487 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002488
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002489 if (FID.isInvalid())
2490 return SourceLocation();
2491
2492 return SourceMgr->getLocForEndOfFile(FID);
2493}
2494
Vedant Kumar525a7f62017-07-25 19:53:27 +00002495SourceLocation ASTUnit::getStartOfMainFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002496 FileID FID;
2497 if (SourceMgr)
2498 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002499
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002500 if (FID.isInvalid())
2501 return SourceLocation();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002502
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002503 return SourceMgr->getLocForStartOfFile(FID);
2504}
2505
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002506llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002507ASTUnit::getLocalPreprocessingEntities() const {
2508 if (isMainFileAST()) {
2509 serialization::ModuleFile &
2510 Mod = Reader->getModuleManager().getPrimaryModule();
2511 return Reader->getModulePreprocessedEntities(Mod);
2512 }
2513
2514 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002515 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002516
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002517 return llvm::make_range(PreprocessingRecord::iterator(),
2518 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002519}
2520
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002521bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002522 if (isMainFileAST()) {
2523 serialization::ModuleFile &
2524 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002525 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2526 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002527 return false;
2528 }
2529
2530 return true;
2531 }
2532
2533 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2534 TLEnd = top_level_end();
2535 TL != TLEnd; ++TL) {
2536 if (!Fn(context, *TL))
2537 return false;
2538 }
2539
2540 return true;
2541}
2542
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002543const FileEntry *ASTUnit::getPCHFile() {
2544 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002545 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002546
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002547 serialization::ModuleFile *Mod = nullptr;
2548 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2549 switch (M.Kind) {
2550 case serialization::MK_ImplicitModule:
2551 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002552 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002553 return true; // skip dependencies.
2554 case serialization::MK_PCH:
2555 Mod = &M;
2556 return true; // found it.
2557 case serialization::MK_Preamble:
2558 return false; // look in dependencies.
2559 case serialization::MK_MainFile:
2560 return false; // look in dependencies.
2561 }
2562
2563 return true;
2564 });
2565 if (Mod)
2566 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002567
Craig Topper49a27902014-05-22 04:46:25 +00002568 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002569}
2570
Vedant Kumar525a7f62017-07-25 19:53:27 +00002571bool ASTUnit::isModuleFile() const {
Richard Smithab755972017-06-05 18:10:11 +00002572 return isMainFileAST() && getLangOpts().isCompilingModule();
2573}
2574
2575InputKind ASTUnit::getInputKind() const {
2576 auto &LangOpts = getLangOpts();
2577
2578 InputKind::Language Lang;
2579 if (LangOpts.OpenCL)
2580 Lang = InputKind::OpenCL;
2581 else if (LangOpts.CUDA)
2582 Lang = InputKind::CUDA;
2583 else if (LangOpts.RenderScript)
2584 Lang = InputKind::RenderScript;
2585 else if (LangOpts.CPlusPlus)
2586 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2587 else
2588 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2589
2590 InputKind::Format Fmt = InputKind::Source;
2591 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2592 Fmt = InputKind::ModuleMap;
2593
2594 // We don't know if input was preprocessed. Assume not.
2595 bool PP = false;
2596
2597 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002598}
2599
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002600#ifndef NDEBUG
2601ASTUnit::ConcurrencyState::ConcurrencyState() {
2602 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2603}
2604
2605ASTUnit::ConcurrencyState::~ConcurrencyState() {
2606 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2607}
2608
2609void ASTUnit::ConcurrencyState::start() {
2610 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2611 assert(acquired && "Concurrent access to ASTUnit!");
2612}
2613
2614void ASTUnit::ConcurrencyState::finish() {
2615 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2616}
2617
2618#else // NDEBUG
2619
Hans Wennborgdcfba332015-10-06 23:40:43 +00002620ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002621ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002622void ASTUnit::ConcurrencyState::start() {}
2623void ASTUnit::ConcurrencyState::finish() {}
2624
Hans Wennborgdcfba332015-10-06 23:40:43 +00002625#endif // NDEBUG