blob: 1e5fd8b40a6084f0ea71a2cf6f30ced8ca775f9f [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 Gregordf7a79a2011-02-16 18:16:54 +000038#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000039#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.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 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000082
83 struct OnDiskData {
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
86
Ted Kremenek06b4f912011-10-27 17:55:18 +000087 /// \brief Erase the preamble file.
88 void CleanPreambleFile();
89
90 /// \brief Erase temporary files and the preamble file.
91 void Cleanup();
92 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +000093
94 template <class T>
95 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
96 if (!Val)
97 return nullptr;
98 return std::move(*Val);
99 }
100
101 template <class T>
102 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
103 if (!Val)
104 return false;
105 Output = std::move(*Val);
106 return true;
107 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000108}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000109
Ted Kremenekbd307a52011-10-27 19:44:25 +0000110static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
111 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
112 return M;
113}
114
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000115static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000116
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000117typedef llvm::DenseMap<const ASTUnit *,
118 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000119static OnDiskDataMap &getOnDiskDataMap() {
120 static OnDiskDataMap M;
121 static bool hasRegisteredAtExit = false;
122 if (!hasRegisteredAtExit) {
123 hasRegisteredAtExit = true;
124 atexit(cleanupOnDiskMapAtExit);
125 }
126 return M;
127}
128
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000129static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000130 // Use the mutex because there can be an alive thread destroying an ASTUnit.
131 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000132 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000133 // We don't worry about freeing the memory associated with OnDiskDataMap.
134 // All we care about is erasing stale files.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000135 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000136 }
137}
138
139static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000140 // We require the mutex since we are modifying the structure of the
141 // DenseMap.
142 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000143 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000144 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000145 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000146 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000147 return *D;
148}
149
150static void erasePreambleFile(const ASTUnit *AU) {
151 getOnDiskData(AU).CleanPreambleFile();
152}
153
154static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000155 // We require the mutex since we are modifying the structure of the
156 // DenseMap.
157 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000158 OnDiskDataMap &M = getOnDiskDataMap();
159 OnDiskDataMap::iterator I = M.find(AU);
160 if (I != M.end()) {
161 I->second->Cleanup();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000162 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000163 }
164}
165
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000166static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000167 getOnDiskData(AU).PreambleFile = preambleFile;
168}
169
170static const std::string &getPreambleFile(const ASTUnit *AU) {
171 return getOnDiskData(AU).PreambleFile;
172}
173
Ted Kremenek06b4f912011-10-27 17:55:18 +0000174void OnDiskData::CleanPreambleFile() {
175 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000176 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000177 PreambleFile.clear();
178 }
179}
180
181void OnDiskData::Cleanup() {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000185struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
188 ASTWriter Writer;
189
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000190 ASTWriterData(MemoryBufferCache &PCMCache)
191 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000192};
193
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000194void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000195 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000196}
197
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000198/// \brief After failing to build a precompiled preamble (due to
199/// errors in the source that occurs in the preamble), the number of
200/// reparses during which we'll skip even trying to precompile the
201/// preamble.
202const unsigned DefaultPreambleRebuildInterval = 5;
203
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000204/// \brief Tracks the number of ASTUnit objects that are currently active.
205///
206/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000207static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000208
Douglas Gregord03e8232010-04-05 21:10:19 +0000209ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000210 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000211 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000212 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000213 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000214 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000215 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000216 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000217 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000218 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000219 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000220 CompletionCacheTopLevelHashValue(0),
221 PreambleTopLevelHashValue(0),
222 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000223 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000226}
Douglas Gregord03e8232010-04-05 21:10:19 +0000227
Daniel Dunbar764c0822009-12-01 09:51:01 +0000228ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000229 // If we loaded from an AST file, balance out the BeginSourceFile call.
230 if (MainFileIsAST && getDiagnostics().getClient()) {
231 getDiagnostics().getClient()->EndSourceFile();
232 }
233
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000234 clearFileLevelDecls();
235
Ted Kremenek06b4f912011-10-27 17:55:18 +0000236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
238
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
242 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000243 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000245 for (const auto &RB : PPOpts.RemappedFileBuffers)
246 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000247 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000248
Douglas Gregor16896c42010-10-28 15:44:59 +0000249 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000250
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000251 if (getenv("LIBCLANG_OBJTRACKING"))
252 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000253}
254
David Blaikie41565462017-01-05 19:48:07 +0000255void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
256 this->PP = std::move(PP);
257}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000258
Douglas Gregor39982192010-08-15 06:18:01 +0000259/// \brief Determine the set of code-completion contexts in which this
260/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000261static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000262 const LangOptions &LangOpts,
263 bool &IsNestedNameSpecifier) {
264 IsNestedNameSpecifier = false;
265
Douglas Gregor39982192010-08-15 06:18:01 +0000266 if (isa<UsingShadowDecl>(ND))
267 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
268 if (!ND)
269 return 0;
270
Richard Smith697cc9e2012-08-14 03:13:00 +0000271 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000272 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
273 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
274 // Types can appear in these contexts.
275 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000276 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
277 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
278 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
279 | (1LL << CodeCompletionContext::CCC_Statement)
280 | (1LL << CodeCompletionContext::CCC_Type)
281 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000282
283 // In C++, types can appear in expressions contexts (for functional casts).
284 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000285 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000286
287 // In Objective-C, message sends can send interfaces. In Objective-C++,
288 // all types are available due to functional casts.
289 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000290 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000291
292 // In Objective-C, you can only be a subclass of another Objective-C class
293 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000295
296 // Deal with tag names.
297 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000298 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000299
Douglas Gregor59cab552010-08-16 23:05:20 +0000300 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000301 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000302 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000303 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000304 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000306 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000307 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000308
Douglas Gregor39982192010-08-15 06:18:01 +0000309 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000310 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000311 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000312 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000313 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
314 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000315 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
316 | (1LL << CodeCompletionContext::CCC_Expression)
317 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
318 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000319 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000320 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000321 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000322 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000323 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000324 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000325
326 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000327 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000328 }
329
330 return Contexts;
331}
332
Douglas Gregorb14904c2010-08-13 22:48:40 +0000333void ASTUnit::CacheCodeCompletionResults() {
334 if (!TheSema)
335 return;
336
Douglas Gregor16896c42010-10-28 15:44:59 +0000337 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000338 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000339
340 // Clear out the previous results.
341 ClearCachedCompletionResults();
342
343 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000344 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000345 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000346 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000347 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000348 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000349 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000350
351 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000352 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000353 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000354
355 for (Result &R : Results) {
356 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000357 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000358 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000359 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000360 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000361 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000362 IncludeBriefCommentsInCodeCompletion);
363 CachedResult.ShowInContexts = getDeclShowContexts(
364 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
365 CachedResult.Priority = R.Priority;
366 CachedResult.Kind = R.CursorKind;
367 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000368
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000369 // Keep track of the type of this completion in an ASTContext-agnostic
370 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000371 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000372 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000373 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000374 CachedResult.Type = 0;
375 } else {
376 CanQualType CanUsageType
377 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
378 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
379
380 // Determine whether we have already seen this type. If so, we save
381 // ourselves the work of formatting the type string by using the
382 // temporary, CanQualType-based hash table to find the associated value.
383 unsigned &TypeValue = CompletionTypes[CanUsageType];
384 if (TypeValue == 0) {
385 TypeValue = CompletionTypes.size();
386 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
387 = TypeValue;
388 }
389
390 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000391 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000392
Douglas Gregor39982192010-08-15 06:18:01 +0000393 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000394
395 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000396 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
397 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000398 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000399 uint64_t NNSContexts
400 = (1LL << CodeCompletionContext::CCC_TopLevel)
401 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
402 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
403 | (1LL << CodeCompletionContext::CCC_Statement)
404 | (1LL << CodeCompletionContext::CCC_Expression)
405 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
406 | (1LL << CodeCompletionContext::CCC_EnumTag)
407 | (1LL << CodeCompletionContext::CCC_UnionTag)
408 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
409 | (1LL << CodeCompletionContext::CCC_Type)
410 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
411 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000412
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000413 if (isa<NamespaceDecl>(R.Declaration) ||
414 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000415 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000416
417 if (unsigned RemainingContexts
418 = NNSContexts & ~CachedResult.ShowInContexts) {
419 // If there any contexts where this completion can be a
420 // nested-name-specifier but isn't already an option, create a
421 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000422 R.StartsNestedNameSpecifier = true;
423 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000424 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000425 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000426 CachedResult.ShowInContexts = RemainingContexts;
427 CachedResult.Priority = CCP_NestedNameSpecifier;
428 CachedResult.TypeClass = STC_Void;
429 CachedResult.Type = 0;
430 CachedCompletionResults.push_back(CachedResult);
431 }
432 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000433 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000434 }
435
Douglas Gregorb14904c2010-08-13 22:48:40 +0000436 case Result::RK_Keyword:
437 case Result::RK_Pattern:
438 // Ignore keywords and patterns; we don't care, since they are so
439 // easily regenerated.
440 break;
441
442 case Result::RK_Macro: {
443 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000444 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000445 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000446 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000447 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000448 = (1LL << CodeCompletionContext::CCC_TopLevel)
449 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
450 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
451 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
452 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
453 | (1LL << CodeCompletionContext::CCC_Statement)
454 | (1LL << CodeCompletionContext::CCC_Expression)
455 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
456 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
457 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
458 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
459 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000460
461 CachedResult.Priority = R.Priority;
462 CachedResult.Kind = R.CursorKind;
463 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000464 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000465 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000466 CachedCompletionResults.push_back(CachedResult);
467 break;
468 }
469 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000470 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000471
472 // Save the current top-level hash value.
473 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000474}
475
476void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000477 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000478 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000479 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000480}
481
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000482namespace {
483
Sebastian Redl2c499f62010-08-18 23:56:43 +0000484/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000485/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000486class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000487 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000488 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000489 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000490 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000491 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000492 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Douglas Gregore8bbc122011-09-02 00:18:52 +0000494 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000495public:
Alp Toker80758082014-07-06 05:26:44 +0000496 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
497 std::shared_ptr<TargetOptions> &TargetOpts,
498 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
499 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
500 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000501
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000502 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
503 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000504 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000505 return false;
506
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000507 LangOpt = LangOpts;
508 InitializedLanguage = true;
509
510 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000511 return false;
512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000514 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
515 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000516 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000517 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000518 return false;
Alp Toker80758082014-07-06 05:26:44 +0000519
520 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
521 Target =
522 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000523
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000524 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000525 return false;
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Craig Topperafa7cb32014-03-13 06:07:04 +0000528 void ReadCounter(const serialization::ModuleFile &M,
529 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000530 Counter = Value;
531 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000532
533private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000534 void updated() {
535 if (!Target || !InitializedLanguage)
536 return;
537
538 // Inform the target of the language options.
539 //
540 // FIXME: We shouldn't need to do this, the target should be immutable once
541 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000542 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000543
544 // Initialize the preprocessor.
545 PP.Initialize(*Target);
546
547 // Initialize the ASTContext
548 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000549
550 // We didn't have access to the comment options when the ASTContext was
551 // constructed, so register them now.
552 Context.getCommentCommandTraits().registerCommentOptions(
553 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000554 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000555};
556
Douglas Gregor6b930962013-05-03 22:58:43 +0000557 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000558class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000559 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000560 SourceManager *SourceMgr;
561
Douglas Gregor33cdd812010-02-18 18:08:43 +0000562public:
David Blaikief18d91a2011-09-26 00:01:39 +0000563 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000564 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000565 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000566
Craig Topperafa7cb32014-03-13 06:07:04 +0000567 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000568 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000569 if (PP)
570 SourceMgr = &PP->getSourceManager();
571 }
572
Craig Topperafa7cb32014-03-13 06:07:04 +0000573 void HandleDiagnostic(DiagnosticsEngine::Level Level,
574 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000575};
576
577/// \brief RAII object that optionally captures diagnostics, if
578/// there is no diagnostic client to capture them already.
579class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000580 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000581 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000582 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000583 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000584
585public:
David Blaikie9c902b52011-09-25 23:23:43 +0000586 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000587 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000588 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000589 {
Craig Topper49a27902014-05-22 04:46:25 +0000590 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000591 OwningPreviousClient = Diags.takeClient();
592 PreviousClient = Diags.getClient();
593 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000594 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595 }
596
597 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000598 if (Diags.getClient() == &Client)
599 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000600 }
601};
602
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000603} // anonymous namespace
604
David Blaikief18d91a2011-09-26 00:01:39 +0000605void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000606 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000607 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000608 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000609
Douglas Gregor6b930962013-05-03 22:58:43 +0000610 // Only record the diagnostic if it's part of the source manager we know
611 // about. This effectively drops diagnostics from modules we're building.
612 // FIXME: In the long run, ee don't want to drop source managers from modules.
613 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000614 StoredDiags.emplace_back(Level, Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000615}
616
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000617IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
618 return Reader;
619}
620
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000621ASTMutationListener *ASTUnit::getASTMutationListener() {
622 if (WriterData)
623 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000624 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000625}
626
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000627ASTDeserializationListener *ASTUnit::getDeserializationListener() {
628 if (WriterData)
629 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000630 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000631}
632
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000633std::unique_ptr<llvm::MemoryBuffer>
634ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000635 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000636 auto Buffer = FileMgr->getBufferForFile(Filename);
637 if (Buffer)
638 return std::move(*Buffer);
639 if (ErrorStr)
640 *ErrorStr = Buffer.getError().message();
641 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000642}
643
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000644/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000645void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000646 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000647 assert(Diags.get() && "no DiagnosticsEngine was provided");
648 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000650}
651
David Blaikie6f7382d2014-08-10 19:08:04 +0000652std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000653 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000655 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
656 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
657 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
658 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000659 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000660
661 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000662 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
663 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000664 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
665 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000666 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000667
Justin Bognerdbbcb112014-10-14 23:36:06 +0000668 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000669
Richard Smithab755972017-06-05 18:10:11 +0000670 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000671 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000672 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000673 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000674 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
675 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000676 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000677 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000678 AST->getFileManager(),
679 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000680 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000681 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000682 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000683 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000684 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000685 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000686 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000687 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000688
David Blaikiee3041682017-01-05 19:11:36 +0000689 auto PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000690
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000691 for (const auto &RemappedFile : RemappedFiles)
692 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000693
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000694 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000695
David Blaikie6f7382d2014-08-10 19:08:04 +0000696 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000697 unsigned Counter;
698
David Blaikie41565462017-01-05 19:48:07 +0000699 AST->PP = std::make_shared<Preprocessor>(
Richard Smithab755972017-06-05 18:10:11 +0000700 std::move(PPOpts), AST->getDiagnostics(), *AST->LangOpts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000701 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
David Blaikie41565462017-01-05 19:48:07 +0000702 /*IILookup=*/nullptr,
703 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000704 Preprocessor &PP = *AST->PP;
705
Richard Smithab755972017-06-05 18:10:11 +0000706 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
Alp Toker08043432014-05-03 03:46:04 +0000707 PP.getIdentifierTable(), PP.getSelectorTable(),
708 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000710
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000711 bool disableValid = false;
712 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
713 disableValid = true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000714 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000715 /*isysroot=*/"",
716 /*DisableValidation=*/disableValid,
717 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000718
David Blaikie2721c322014-08-10 16:54:39 +0000719 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithab755972017-06-05 18:10:11 +0000720 *AST->PP, Context, *AST->LangOpts, AST->TargetOpts, AST->Target,
David Blaikie2721c322014-08-10 16:54:39 +0000721 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000722
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000723 // Attach the AST reader to the AST context as an external AST
724 // source, so that declarations will be deserialized from the
725 // AST file as needed.
726 // We need the external source to be set up before we read the AST, because
727 // eagerly-deserialized declarations may use it.
728 Context.setExternalSource(AST->Reader);
729
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000730 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000731 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000732 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000733 break;
Mike Stump11289f42009-09-09 15:08:12 +0000734
Sebastian Redl2c499f62010-08-18 23:56:43 +0000735 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000736 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000737 case ASTReader::OutOfDate:
738 case ASTReader::VersionMismatch:
739 case ASTReader::ConfigurationMismatch:
740 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000741 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000742 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000745 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000746
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000747 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000748
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000749 // Create an AST consumer, even though it isn't used.
750 AST->Consumer.reset(new ASTConsumer);
751
Sebastian Redl2c499f62010-08-18 23:56:43 +0000752 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000753 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
754 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000755 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000756
Douglas Gregor6b930962013-05-03 22:58:43 +0000757 // Tell the diagnostic client that we have started a source file.
758 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
759
David Blaikie6f7382d2014-08-10 19:08:04 +0000760 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000761}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000762
763namespace {
764
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000765/// \brief Preprocessor callback class that updates a hash value with the names
766/// of all macros that have been defined by the translation unit.
767class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
768 unsigned &Hash;
769
770public:
771 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000772
773 void MacroDefined(const Token &MacroNameTok,
774 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000775 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
776 }
777};
778
779/// \brief Add the given declaration to the hash of all top-level entities.
780void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
781 if (!D)
782 return;
783
784 DeclContext *DC = D->getDeclContext();
785 if (!DC)
786 return;
787
788 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
789 return;
790
791 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000792 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
793 // For an unscoped enum include the enumerators in the hash since they
794 // enter the top-level namespace.
795 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000796 for (const auto *EI : EnumD->enumerators()) {
797 if (EI->getIdentifier())
798 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000799 }
800 }
801 }
802
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000803 if (ND->getIdentifier())
804 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
805 else if (DeclarationName Name = ND->getDeclName()) {
806 std::string NameStr = Name.getAsString();
807 Hash = llvm::HashString(NameStr, Hash);
808 }
809 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000810 }
811
812 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
813 if (Module *Mod = ImportD->getImportedModule()) {
814 std::string ModName = Mod->getFullModuleName();
815 Hash = llvm::HashString(ModName, Hash);
816 }
817 return;
818 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000819}
820
Daniel Dunbar644dca02009-12-04 08:17:33 +0000821class TopLevelDeclTrackerConsumer : public ASTConsumer {
822 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000823 unsigned &Hash;
824
Daniel Dunbar644dca02009-12-04 08:17:33 +0000825public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000826 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
827 : Unit(_Unit), Hash(Hash) {
828 Hash = 0;
829 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000830
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000831 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000832 if (!D)
833 return;
834
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000835 // FIXME: Currently ObjC method declarations are incorrectly being
836 // reported as top-level declarations, even though their DeclContext
837 // is the containing ObjC @interface/@implementation. This is a
838 // fundamental problem in the parser right now.
839 if (isa<ObjCMethodDecl>(D))
840 return;
841
842 AddTopLevelDeclarationToHash(D, Hash);
843 Unit.addTopLevelDecl(D);
844
845 handleFileLevelDecl(D);
846 }
847
848 void handleFileLevelDecl(Decl *D) {
849 Unit.addFileLevelDecl(D);
850 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000851 for (auto *I : NSD->decls())
852 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000853 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000854 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000855
Craig Topperafa7cb32014-03-13 06:07:04 +0000856 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000857 for (Decl *TopLevelDecl : D)
858 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000859 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000860 }
861
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000862 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000863 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000864
Craig Topperafa7cb32014-03-13 06:07:04 +0000865 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000866 for (Decl *TopLevelDecl : D)
867 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000868 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000869
Craig Topperafa7cb32014-03-13 06:07:04 +0000870 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000871 return Unit.getASTMutationListener();
872 }
873
Craig Topperafa7cb32014-03-13 06:07:04 +0000874 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000875 return Unit.getDeserializationListener();
876 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000877};
878
879class TopLevelDeclTrackerAction : public ASTFrontendAction {
880public:
881 ASTUnit &Unit;
882
David Blaikie6beb6aa2014-08-10 19:56:51 +0000883 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
884 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000885 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000886 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
887 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000888 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
889 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000890 }
891
892public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000893 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
894
Craig Topperafa7cb32014-03-13 06:07:04 +0000895 bool hasCodeCompletionSupport() const override { return false; }
896 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000897 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000898 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000899};
900
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000901class PrecompilePreambleAction : public ASTFrontendAction {
902 ASTUnit &Unit;
903 bool HasEmittedPreamblePCH;
904
905public:
906 explicit PrecompilePreambleAction(ASTUnit &Unit)
907 : Unit(Unit), HasEmittedPreamblePCH(false) {}
908
David Blaikie6beb6aa2014-08-10 19:56:51 +0000909 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
910 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000911 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
912 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000913 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000914
Craig Topperafa7cb32014-03-13 06:07:04 +0000915 bool hasCodeCompletionSupport() const override { return false; }
916 bool hasASTFileSupport() const override { return false; }
917 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000918};
919
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000920class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000921 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000922 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000923 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000924 PrecompilePreambleAction *Action;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000925 std::unique_ptr<raw_ostream> Out;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000926
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000927public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000928 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
929 const Preprocessor &PP, StringRef isysroot,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000930 std::unique_ptr<raw_ostream> Out)
Richard Smithbd97f352016-08-25 18:26:30 +0000931 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
David Blaikie61137e12017-01-05 18:23:18 +0000932 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000933 /*AllowASTWithErrors=*/true),
934 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000935 Out(std::move(Out)) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000936 Hash = 0;
937 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000938
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000939 bool HandleTopLevelDecl(DeclGroupRef DG) override {
940 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000941 // FIXME: Currently ObjC method declarations are incorrectly being
942 // reported as top-level declarations, even though their DeclContext
943 // is the containing ObjC @interface/@implementation. This is a
944 // fundamental problem in the parser right now.
945 if (isa<ObjCMethodDecl>(D))
946 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000947 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000948 TopLevelDecls.push_back(D);
949 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000950 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000951 }
952
Craig Topperafa7cb32014-03-13 06:07:04 +0000953 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000954 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000955 if (hasEmittedPCH()) {
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000956 // Write the generated bitstream to "Out".
957 *Out << getPCH();
958 // Make sure it hits disk now.
959 Out->flush();
960 // Free the buffer.
961 llvm::SmallVector<char, 0> Empty;
962 getPCH() = std::move(Empty);
963
Douglas Gregore9db88f2010-08-03 19:06:41 +0000964 // Translate the top-level declarations we captured during
965 // parsing into declaration IDs in the precompiled
966 // preamble. This will allow us to deserialize those top-level
967 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000968 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000969 // Invalid top-level decls may not have been serialized.
970 if (D->isInvalidDecl())
971 continue;
972 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
973 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000974
975 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000976 }
977 }
978};
979
Hans Wennborgdcfba332015-10-06 23:40:43 +0000980} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000981
David Blaikie6beb6aa2014-08-10 19:56:51 +0000982std::unique_ptr<ASTConsumer>
983PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
984 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000985 std::string Sysroot;
986 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000987 std::unique_ptr<raw_ostream> OS =
988 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
989 OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +0000990 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000991 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000992
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000993 if (!CI.getFrontendOpts().RelocatablePCH)
994 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000995
Craig Topperb8a70532014-09-10 04:53:53 +0000996 CI.getPreprocessor().addPPCallbacks(
997 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
998 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000999 return llvm::make_unique<PrecompilePreambleConsumer>(
Peter Collingbourne03f89072016-07-15 00:55:40 +00001000 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
Daniel Dunbar764c0822009-12-01 09:51:01 +00001001}
1002
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001003static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1004 return StoredDiag.getLocation().isValid();
1005}
1006
1007static void
1008checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001009 // Get rid of stored diagnostics except the ones from the driver which do not
1010 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001011 StoredDiags.erase(
1012 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1013 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001014}
1015
1016static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1017 StoredDiagnostics,
1018 SourceManager &SM) {
1019 // The stored diagnostic has the old source manager in it; update
1020 // the locations to refer into the new source manager. Since we've
1021 // been careful to make sure that the source manager's state
1022 // before and after are identical, so that we can reuse the source
1023 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001024 for (StoredDiagnostic &SD : StoredDiagnostics) {
1025 if (SD.getLocation().isValid()) {
1026 FullSourceLoc Loc(SD.getLocation(), SM);
1027 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001028 }
1029 }
1030}
1031
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001032/// Parse the source file into a translation unit using the given compiler
1033/// invocation, replacing the current translation unit.
1034///
1035/// \returns True if a failure occurred that causes the ASTUnit not to
1036/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001037bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001038 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1039 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001040 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001041 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001042
Daniel Dunbar764c0822009-12-01 09:51:01 +00001043 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001044 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001045 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001046 if (FileMgr && VFS) {
1047 assert(VFS == FileMgr->getVirtualFileSystem() &&
1048 "VFS passed to Parse and VFS in FileMgr are different");
1049 } else if (VFS) {
1050 Clang->setVirtualFileSystem(VFS);
1051 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001052
1053 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001054 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1055 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001056
David Blaikieea4395e2017-01-06 19:49:01 +00001057 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001058 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001059
Douglas Gregor8e984da2010-08-04 16:47:14 +00001060 // Set up diagnostics, capturing any diagnostics that would
1061 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001062 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001063
Daniel Dunbar764c0822009-12-01 09:51:01 +00001064 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001065 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001066 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001067 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001068 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001069
Daniel Dunbar764c0822009-12-01 09:51:01 +00001070 // Inform the target of the language options.
1071 //
1072 // FIXME: We shouldn't need to do this, the target should be immutable once
1073 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001074 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001075
Ted Kremenek84de4a12011-03-21 18:40:07 +00001076 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001077 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001078 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1079 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001080 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001081 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1082 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001083 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001084
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001085 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001086 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001087 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001088 if (!FileMgr) {
1089 Clang->createFileManager();
1090 FileMgr = &Clang->getFileManager();
1091 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001092
1093 ResetForParse();
1094
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001095 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1096 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001097 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001098 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001099 TopLevelDeclsInPreamble.clear();
1100 }
1101
Daniel Dunbar764c0822009-12-01 09:51:01 +00001102 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001104
Daniel Dunbar764c0822009-12-01 09:51:01 +00001105 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001106 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001107
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001108 // If the main file has been overridden due to the use of a preamble,
1109 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001110 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001111 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001112 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1113 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001114 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1115 PreprocessorOpts.PrecompiledPreambleBytes.second
1116 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001117 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001118 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001119
Douglas Gregord9a30af2010-08-02 20:51:39 +00001120 // The stored diagnostic has the old source manager in it; update
1121 // the locations to refer into the new source manager. Since we've
1122 // been careful to make sure that the source manager's state
1123 // before and after are identical, so that we can reuse the source
1124 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001125 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001126
1127 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001128 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001129 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001130
1131 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1132 new TopLevelDeclTrackerAction(*this));
1133
Ted Kremenek022a4902011-03-22 01:15:24 +00001134 // Recover resources if we crash before exiting this method.
1135 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1136 ActCleanup(Act.get());
1137
Douglas Gregor32fbe312012-01-20 16:28:04 +00001138 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001139 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001140
Richard Smith26b8f782016-03-25 21:46:44 +00001141 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001142 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1143 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001144
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001145 if (!Act->Execute())
1146 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001147
1148 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001149
Daniel Dunbar644dca02009-12-04 08:17:33 +00001150 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001151
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001152 FailedParseDiagnostics.clear();
1153
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001154 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001155
Daniel Dunbar764c0822009-12-01 09:51:01 +00001156error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001157 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001158 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001159
1160 // Keep the ownership of the data in the ASTUnit because the client may
1161 // want to see the diagnostics.
1162 transferASTDataFromCompilerInstance(*Clang);
1163 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001164 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001165 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001166 return true;
1167}
1168
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001169/// \brief Simple function to retrieve a path for a preamble precompiled header.
1170static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001171 // FIXME: This is a hack so that we can override the preamble file during
1172 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001173 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001174 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1175 if (TmpFile)
1176 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001177
1178 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001179 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001180
1181 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001182}
1183
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001184/// \brief Compute the preamble for the main file, providing the source buffer
1185/// that corresponds to the main file along with a pair (bytes, start-of-line)
1186/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001187ASTUnit::ComputedPreamble
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001188ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines,
1189 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001190 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001191 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001192
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001193 // Try to determine if the main file has been remapped, either from the
1194 // command line (to another file) or directly through the compiler invocation
1195 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001196 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001197 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001198 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001199 auto MainFileStatus = VFS->status(MainFilePath);
1200 if (MainFileStatus) {
1201 llvm::sys::fs::UniqueID MainFileID = MainFileStatus->getUniqueID();
1202
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001203 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001204 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1205 std::string MPath(RF.first);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001206 auto MPathStatus = VFS->status(MPath);
1207 if (MPathStatus) {
1208 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001209 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001210 // We found a remapping. Try to load the resulting, remapped source.
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001211 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
David Blaikied6902a12014-08-29 06:34:53 +00001212 if (!BufferOwner)
1213 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001214 }
1215 }
1216 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001217
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001218 // Check whether there is a file-buffer remapping. It supercedes the
1219 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001220 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1221 std::string MPath(RB.first);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001222 auto MPathStatus = VFS->status(MPath);
1223 if (MPathStatus) {
1224 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001225 if (MainFileID == MID) {
1226 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001227 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001228 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001229 }
1230 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001231 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001232 }
1233
1234 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001235 if (!Buffer && !BufferOwner) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001236 BufferOwner = valueOrNull(VFS->getBufferForFile(FrontendOpts.Inputs[0].getFile()));
David Blaikied6902a12014-08-29 06:34:53 +00001237 if (!BufferOwner)
1238 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001239 }
David Blaikie3d95d852014-08-11 22:08:06 +00001240
David Blaikied6902a12014-08-29 06:34:53 +00001241 if (!Buffer)
1242 Buffer = BufferOwner.get();
1243 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1244 *Invocation.getLangOpts(), MaxLines);
1245 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1246 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001247}
1248
Dmitri Gribenko47652522013-12-20 00:16:25 +00001249ASTUnit::PreambleFileHash
1250ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1251 PreambleFileHash Result;
1252 Result.Size = Size;
1253 Result.ModTime = ModTime;
Zachary Turner82a0c972017-03-20 23:33:18 +00001254 Result.MD5 = {};
Dmitri Gribenko47652522013-12-20 00:16:25 +00001255 return Result;
1256}
1257
1258ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1259 const llvm::MemoryBuffer *Buffer) {
1260 PreambleFileHash Result;
1261 Result.Size = Buffer->getBufferSize();
1262 Result.ModTime = 0;
1263
1264 llvm::MD5 MD5Ctx;
1265 MD5Ctx.update(Buffer->getBuffer().data());
1266 MD5Ctx.final(Result.MD5);
1267
1268 return Result;
1269}
1270
1271namespace clang {
1272bool operator==(const ASTUnit::PreambleFileHash &LHS,
1273 const ASTUnit::PreambleFileHash &RHS) {
1274 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Zachary Turner82a0c972017-03-20 23:33:18 +00001275 LHS.MD5 == RHS.MD5;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001276}
1277} // namespace clang
1278
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001279static std::pair<unsigned, unsigned>
1280makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1281 const LangOptions &LangOpts) {
1282 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1283 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1284 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1285 return std::make_pair(Offset, EndOffset);
1286}
1287
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001288static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1289 const LangOptions &LangOpts,
1290 const FixItHint &InFix) {
1291 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001292 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1293 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1294 LangOpts);
1295 OutFix.CodeToInsert = InFix.CodeToInsert;
1296 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001297 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001298}
1299
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001300static ASTUnit::StandaloneDiagnostic
1301makeStandaloneDiagnostic(const LangOptions &LangOpts,
1302 const StoredDiagnostic &InDiag) {
1303 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001304 OutDiag.ID = InDiag.getID();
1305 OutDiag.Level = InDiag.getLevel();
1306 OutDiag.Message = InDiag.getMessage();
1307 OutDiag.LocOffset = 0;
1308 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001309 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001310 const SourceManager &SM = InDiag.getLocation().getManager();
1311 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1312 OutDiag.Filename = SM.getFilename(FileLoc);
1313 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001314 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001315 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001316 for (const CharSourceRange &Range : InDiag.getRanges())
1317 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1318 for (const FixItHint &FixIt : InDiag.getFixIts())
1319 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001320
1321 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001322}
1323
Douglas Gregor4dde7492010-07-23 23:58:40 +00001324/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1325/// the source file.
1326///
1327/// This routine will compute the preamble of the main source file. If a
1328/// non-trivial preamble is found, it will precompile that preamble into a
1329/// precompiled header so that the precompiled preamble can be used to reduce
1330/// reparsing time. If a precompiled preamble has already been constructed,
1331/// this routine will determine if it is still valid and, if so, avoid
1332/// rebuilding the precompiled preamble.
1333///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001334/// \param AllowRebuild When true (the default), this routine is
1335/// allowed to rebuild the precompiled preamble if it is found to be
1336/// out-of-date.
1337///
1338/// \param MaxLines When non-zero, the maximum number of lines that
1339/// can occur within the preamble.
1340///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001341/// \returns If the precompiled preamble can be used, returns a newly-allocated
1342/// buffer that should be used in place of the main file when doing so.
1343/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001344std::unique_ptr<llvm::MemoryBuffer>
1345ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001346 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001347 const CompilerInvocation &PreambleInvocationIn,
1348 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
Rafael Espindola2346a372014-08-18 18:47:08 +00001349 unsigned MaxLines) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001350 assert(VFS && "VFS is null");
Rafael Espindola2346a372014-08-18 18:47:08 +00001351
David Blaikieea4395e2017-01-06 19:49:01 +00001352 auto PreambleInvocation =
1353 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
Douglas Gregor3cc15812011-07-01 18:22:13 +00001354 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001355 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001356 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001357
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001358 ComputedPreamble NewPreamble =
1359 ComputePreamble(*PreambleInvocation, MaxLines, VFS);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001360
David Blaikied6902a12014-08-29 06:34:53 +00001361 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001362 // We couldn't find a preamble in the main source. Clear out the current
1363 // preamble, if we have one. It's obviously no good any more.
1364 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001365 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001366
1367 // The next time we actually see a preamble, precompile it.
1368 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001369 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001370 }
1371
1372 if (!Preamble.empty()) {
1373 // We've previously computed a preamble. Check whether we have the same
1374 // preamble now that we did before, and that there's enough space in
1375 // the main-file buffer within the precompiled preamble to fit the
1376 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001377 if (Preamble.size() == NewPreamble.Size &&
1378 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1379 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1380 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001381 // The preamble has not changed. We may be able to re-use the precompiled
1382 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001383
Douglas Gregor0e119552010-07-31 00:40:00 +00001384 // Check that none of the files used by the preamble have changed.
1385 bool AnyFileChanged = false;
1386
1387 // First, make a record of those files that have been overridden via
1388 // remapping or unsaved_files.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001389 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001390 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1391 if (AnyFileChanged)
1392 break;
1393
Ben Langmuirc8130a72014-02-20 21:59:23 +00001394 vfs::Status Status;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001395 if (!moveOnNoError(VFS->status(R.second), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001396 // If we can't stat the file we're remapping to, assume that something
1397 // horrible happened.
1398 AnyFileChanged = true;
1399 break;
1400 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001401
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001402 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001403 Status.getSize(),
1404 llvm::sys::toTimeT(Status.getLastModificationTime()));
Douglas Gregor0e119552010-07-31 00:40:00 +00001405 }
Alp Toker1b070d22014-07-07 07:47:20 +00001406
1407 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1408 if (AnyFileChanged)
1409 break;
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001410
1411 vfs::Status Status;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001412 if (!moveOnNoError(VFS->status(RB.first), Status)) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001413 AnyFileChanged = true;
1414 break;
1415 }
1416
1417 OverriddenFiles[Status.getUniqueID()] =
Alp Toker1b070d22014-07-07 07:47:20 +00001418 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001419 }
1420
1421 // Check whether anything has changed.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001422 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001423 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1424 !AnyFileChanged && F != FEnd;
1425 ++F) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001426 vfs::Status Status;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001427 if (!moveOnNoError(VFS->status(F->first()), Status)) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001428 // If we can't stat the file, assume that something horrible happened.
1429 AnyFileChanged = true;
1430 break;
1431 }
1432
1433 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1434 = OverriddenFiles.find(Status.getUniqueID());
Douglas Gregor0e119552010-07-31 00:40:00 +00001435 if (Overridden != OverriddenFiles.end()) {
1436 // This file was remapped; check whether the newly-mapped file
1437 // matches up with the previous mapping.
1438 if (Overridden->second != F->second)
1439 AnyFileChanged = true;
1440 continue;
1441 }
1442
1443 // The file was not remapped; check whether it has changed on disk.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001444 if (Status.getSize() != uint64_t(F->second.Size) ||
Pavel Labathac71c8e2016-11-09 10:52:22 +00001445 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1446 F->second.ModTime)
Douglas Gregor0e119552010-07-31 00:40:00 +00001447 AnyFileChanged = true;
1448 }
1449
1450 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001451 // Okay! We can re-use the precompiled preamble.
1452
1453 // Set the state of the diagnostic object to mimic its state
1454 // after parsing the preamble.
1455 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001456 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001457 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001458 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001459
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001460 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001461 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001462 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001463 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001464
1465 // If we aren't allowed to rebuild the precompiled preamble, just
1466 // return now.
1467 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001468 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001469
Douglas Gregor4dde7492010-07-23 23:58:40 +00001470 // We can't reuse the previously-computed preamble. Build a new one.
1471 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001472 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001473 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001474 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001475 } else if (!AllowRebuild) {
1476 // We aren't allowed to rebuild the precompiled preamble; just
1477 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001478 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001479 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001480
1481 // If the preamble rebuild counter > 1, it's because we previously
1482 // failed to build a preamble and we're not yet ready to try
1483 // again. Decrement the counter and return a failure.
1484 if (PreambleRebuildCounter > 1) {
1485 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001486 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001487 }
1488
Douglas Gregore10f0e52010-09-11 17:56:52 +00001489 // Create a temporary file for the precompiled preamble. In rare
1490 // circumstances, this can fail.
1491 std::string PreamblePCHPath = GetPreamblePCHPath();
1492 if (PreamblePCHPath.empty()) {
1493 // Try again next time.
1494 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001495 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001496 }
1497
Douglas Gregor4dde7492010-07-23 23:58:40 +00001498 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001499 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001500 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001501
Douglas Gregord9a30af2010-08-02 20:51:39 +00001502 // Save the preamble text for later; we'll need to compare against it for
1503 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001504 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001505 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001506 NewPreamble.Buffer->getBufferStart(),
1507 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1508 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001509
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001510 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001511 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001512
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001513 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001514 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001515 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001516
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001517 // Tell the compiler invocation to generate a temporary precompiled header.
1518 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001519 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001520 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001521 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1522 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001523
1524 // Create the compiler instance to use for building the precompiled preamble.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001525 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001526 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001527
1528 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001529 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1530 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001531
David Blaikieea4395e2017-01-06 19:49:01 +00001532 Clang->setInvocation(std::move(PreambleInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001533 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001534
Douglas Gregor8e984da2010-08-04 16:47:14 +00001535 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001536 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001537
1538 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001539 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001540 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001541 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001542 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001543 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001544 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001545 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001546 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001547 }
1548
1549 // Inform the target of the language options.
1550 //
1551 // FIXME: We shouldn't need to do this, the target should be immutable once
1552 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001553 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554
Ted Kremenek84de4a12011-03-21 18:40:07 +00001555 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001556 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001557 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1558 InputKind::Source &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001559 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001560 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1561 InputKind::LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001562 "IR inputs not support here!");
1563
1564 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001565 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001566 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001567 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001568 TopLevelDecls.clear();
1569 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001570 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001571
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001572 VFS = createVFSFromCompilerInvocation(Clang->getInvocation(),
1573 getDiagnostics(), VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001574 if (!VFS)
1575 return nullptr;
1576
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001577 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001578 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001579
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001580 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001581 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001582 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001583
Ben Langmuir33c80902014-06-30 20:04:14 +00001584 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1585 Clang->addDependencyCollector(PreambleDepCollector);
1586
Ahmed Charlesb8984322014-03-07 20:03:18 +00001587 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001588 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001589 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001590 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001591 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001592 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001593 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001594 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001595 }
1596
1597 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001598
1599 // Transfer any diagnostics generated when parsing the preamble into the set
1600 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001601 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1602 E = stored_diag_end();
1603 I != E; ++I)
1604 PreambleDiagnostics.push_back(
1605 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001606
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001607 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001608
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001609 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1610
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001611 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001612 // The preamble PCH failed (e.g. there was a module loading fatal error),
1613 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001614 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001615 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001616 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001617 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001618 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001619 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001620 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001621 }
1622
1623 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001624 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001625 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001626
1627 // Keep track of all of the files that the source manager knows about,
1628 // so we can verify whether they have changed or not.
1629 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001630 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001631 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1632 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1633 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001634 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001635 if (time_t ModTime = File->getModificationTime()) {
1636 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001637 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001638 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001639 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001640 FilesInPreamble[File->getName()] =
1641 PreambleFileHash::createForMemoryBuffer(Buffer);
1642 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001643 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001644
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001645 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001646 PreprocessorOpts.RemappedFileBuffers.pop_back();
1647
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001648 // If the hash of top-level entities differs from the hash of the top-level
1649 // entities the last time we rebuilt the preamble, clear out the completion
1650 // cache.
1651 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1652 CompletionCacheTopLevelHashValue = 0;
1653 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1654 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001655
David Blaikied6902a12014-08-29 06:34:53 +00001656 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001657 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001658}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001659
Douglas Gregore9db88f2010-08-03 19:06:41 +00001660void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1661 std::vector<Decl *> Resolved;
1662 Resolved.reserve(TopLevelDeclsInPreamble.size());
1663 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001664 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001665 // Resolve the declaration ID to an actual declaration, possibly
1666 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001667 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001668 Resolved.push_back(D);
1669 }
1670 TopLevelDeclsInPreamble.clear();
1671 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1672}
1673
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001674void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001675 // Steal the created target, context, and preprocessor if they have been
1676 // created.
1677 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001678 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001679 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001680 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001681 if (CI.hasASTContext())
1682 Ctx = &CI.getASTContext();
1683 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001684 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001685 CI.setSourceManager(nullptr);
1686 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001687 if (CI.hasTarget())
1688 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001689 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001690 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001691}
1692
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001693StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001694 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1695 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1696 if (Input.isFile())
1697 return Input.getFile();
1698 else
1699 return Input.getBuffer()->getBufferIdentifier();
1700 }
1701
1702 if (SourceMgr) {
1703 if (const FileEntry *
1704 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1705 return FE->getName();
1706 }
1707
1708 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001709}
1710
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001711StringRef ASTUnit::getASTFileName() const {
1712 if (!isMainFileAST())
1713 return StringRef();
1714
1715 serialization::ModuleFile &
1716 Mod = Reader->getModuleManager().getPrimaryModule();
1717 return Mod.FileName;
1718}
1719
David Blaikieea4395e2017-01-06 19:49:01 +00001720std::unique_ptr<ASTUnit>
1721ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1722 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1723 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1724 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001725 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001726 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1727 createVFSFromCompilerInvocation(*CI, *Diags);
1728 if (!VFS)
1729 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001730 AST->Diagnostics = Diags;
1731 AST->FileSystemOpts = CI->getFileSystemOpts();
1732 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001733 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001734 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1735 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1736 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001737 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001738
David Blaikieea4395e2017-01-06 19:49:01 +00001739 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001740}
1741
Ahmed Charlesb8984322014-03-07 20:03:18 +00001742ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001743 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001744 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001745 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001746 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001747 bool OnlyLocalDecls, bool CaptureDiagnostics,
1748 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1749 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1750 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001751 assert(CI && "A CompilerInvocation is required");
1752
Ahmed Charlesb8984322014-03-07 20:03:18 +00001753 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001754 ASTUnit *AST = Unit;
1755 if (!AST) {
1756 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001757 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001758 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001759 if (!AST)
1760 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001761 }
1762
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001763 if (!ResourceFilesPath.empty()) {
1764 // Override the resources path.
1765 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1766 }
1767 AST->OnlyLocalDecls = OnlyLocalDecls;
1768 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001769 if (PrecompilePreambleAfterNParses > 0)
1770 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001771 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001772 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001773 AST->IncludeBriefCommentsInCodeCompletion
1774 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001775
1776 // Recover resources if we crash before exiting this method.
1777 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001778 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001779 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1780 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001781 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001782
1783 // We'll manage file buffers ourselves.
1784 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1785 CI->getFrontendOpts().DisableFree = false;
1786 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1787
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001788 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001789 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001790 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001791
1792 // Recover resources if we crash before exiting this method.
1793 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1794 CICleanup(Clang.get());
1795
David Blaikieea4395e2017-01-06 19:49:01 +00001796 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001797 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001798
1799 // Set up diagnostics, capturing any diagnostics that would
1800 // otherwise be dropped.
1801 Clang->setDiagnostics(&AST->getDiagnostics());
1802
1803 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001804 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001805 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001806 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001807 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001808
1809 // Inform the target of the language options.
1810 //
1811 // FIXME: We shouldn't need to do this, the target should be immutable once
1812 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001813 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001814
1815 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1816 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001817 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1818 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001819 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001820 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1821 InputKind::LLVM_IR &&
1822 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001823
1824 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001825 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001826 AST->Ctx = nullptr;
1827 AST->PP = nullptr;
1828 AST->Reader = nullptr;
1829
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001830 // Create a file manager object to provide access to and cache the filesystem.
1831 Clang->setFileManager(&AST->getFileManager());
1832
1833 // Create the source manager.
1834 Clang->setSourceManager(&AST->getSourceManager());
1835
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001836 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001837
Ahmed Charlesb8984322014-03-07 20:03:18 +00001838 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001839 if (!Act) {
1840 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1841 Act = TrackerAct.get();
1842 }
1843
1844 // Recover resources if we crash before exiting this method.
1845 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1846 ActCleanup(TrackerAct.get());
1847
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001848 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1849 AST->transferASTDataFromCompilerInstance(*Clang);
1850 if (OwnAST && ErrAST)
1851 ErrAST->swap(OwnAST);
1852
Craig Topper49a27902014-05-22 04:46:25 +00001853 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001854 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001855
1856 if (Persistent && !TrackerAct) {
1857 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001858 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1859 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001860 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001861 if (Clang->hasASTConsumer())
1862 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001863 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1864 *AST, AST->getCurrentTopLevelHashValue()));
1865 Clang->setASTConsumer(
1866 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001867 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001868 if (!Act->Execute()) {
1869 AST->transferASTDataFromCompilerInstance(*Clang);
1870 if (OwnAST && ErrAST)
1871 ErrAST->swap(OwnAST);
1872
Craig Topper49a27902014-05-22 04:46:25 +00001873 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001874 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001875
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001876 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001877 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001878
1879 Act->EndSourceFile();
1880
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001881 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001882 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001883 else
1884 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001885}
1886
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001887bool ASTUnit::LoadFromCompilerInvocation(
1888 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001889 unsigned PrecompilePreambleAfterNParses,
1890 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001891 if (!Invocation)
1892 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001893
1894 assert(VFS && "VFS is null");
1895
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001896 // We'll manage file buffers ourselves.
1897 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1898 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001899 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001900 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001901
Rafael Espindola32482082014-08-18 16:23:45 +00001902 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001903 if (PrecompilePreambleAfterNParses > 0) {
1904 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001905 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001906 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001907 getDiagnostics().Reset();
1908 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001909 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001910
Douglas Gregor16896c42010-10-28 15:44:59 +00001911 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001912 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001913
Ted Kremenek022a4902011-03-22 01:15:24 +00001914 // Recover resources if we crash before exiting this method.
1915 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001916 MemBufferCleanup(OverrideMainBuffer.get());
1917
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001918 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001919}
1920
David Blaikie103a2de2014-04-25 17:01:33 +00001921std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001922 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001923 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001924 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001925 bool OnlyLocalDecls, bool CaptureDiagnostics,
1926 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1927 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1928 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001929 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001930 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001931 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001932 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001933 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001934 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001935 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001936 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001937 AST->IncludeBriefCommentsInCodeCompletion
1938 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001939 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001940 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1941 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001942 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001943
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001944 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001945 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1946 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001947 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1948 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001949 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001950
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001951 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001952 PrecompilePreambleAfterNParses,
1953 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001954 return nullptr;
1955 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001956}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001957
Ahmed Charlesb8984322014-03-07 20:03:18 +00001958ASTUnit *ASTUnit::LoadFromCommandLine(
1959 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001960 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001961 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1962 bool OnlyLocalDecls, bool CaptureDiagnostics,
1963 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001964 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001965 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1966 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1967 bool UserFilesAreVolatile, bool ForSerialization,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001968 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1969 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001970 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001971
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001972 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001973
1974 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001975
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001976 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001977
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001978 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001979 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001980
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001981 CI = clang::createInvocationFromCommandLine(
David Blaikieea4395e2017-01-06 19:49:01 +00001982 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001983 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001984 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001985 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001986
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001987 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001988 for (const auto &RemappedFile : RemappedFiles) {
1989 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1990 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001991 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001992 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1993 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1994 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00001995 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001996
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001997 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001998 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001999
Erik Verbruggen6e922512012-04-12 10:11:59 +00002000 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2001
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00002002 if (ModuleFormat)
2003 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
2004
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002005 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00002006 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002007 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00002008 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002009 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002010 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002011 if (!VFS)
2012 VFS = vfs::getRealFileSystem();
2013 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00002014 if (!VFS)
2015 return nullptr;
2016 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002017 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002018 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002019 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002020 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002021 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002022 AST->IncludeBriefCommentsInCodeCompletion
2023 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002024 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002025 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002026 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002027 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002028 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002029 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00002030 // Zero out now to ease cleanup during crash recovery.
2031 CI = nullptr;
2032 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00002033
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002034 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002035 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2036 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002037
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002038 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002039 PrecompilePreambleAfterNParses,
2040 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002041 // Some error occurred, if caller wants to examine diagnostics, pass it the
2042 // ASTUnit.
2043 if (ErrAST) {
2044 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2045 ErrAST->swap(AST);
2046 }
Craig Topper49a27902014-05-22 04:46:25 +00002047 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002048 }
2049
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002050 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002051}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002052
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002053bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002054 ArrayRef<RemappedFile> RemappedFiles,
2055 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002056 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002057 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002058
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002059 if (!VFS) {
2060 assert(FileMgr && "FileMgr is null on Reparse call");
2061 VFS = FileMgr->getVirtualFileSystem();
2062 }
2063
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002064 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002065
Douglas Gregor16896c42010-10-28 15:44:59 +00002066 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002067 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002068
Douglas Gregor0e119552010-07-31 00:40:00 +00002069 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002070 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002071 for (const auto &RB : PPOpts.RemappedFileBuffers)
2072 delete RB.second;
2073
Douglas Gregor0e119552010-07-31 00:40:00 +00002074 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002075 for (const auto &RemappedFile : RemappedFiles) {
2076 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2077 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002078 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002079
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002080 // If we have a preamble file lying around, or if we might try to
2081 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002082 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002083 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002084 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002085 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
2086
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002087
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002088 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00002089 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002090 getDiagnostics().Reset();
2091 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002092 if (OverrideMainBuffer)
2093 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002094
Douglas Gregor4dde7492010-07-23 23:58:40 +00002095 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002096 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002097 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00002098
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002099 // If we're caching global code-completion results, and the top-level
2100 // declarations have changed, clear out the code-completion cache.
2101 if (!Result && ShouldCacheCodeCompletionResults &&
2102 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2103 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002104
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002105 // We now need to clear out the completion info related to this translation
2106 // unit; it'll be recreated if necessary.
2107 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002108
Douglas Gregor4dde7492010-07-23 23:58:40 +00002109 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002110}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002111
Erik Verbruggen346066b2017-05-30 14:25:54 +00002112void ASTUnit::ResetForParse() {
2113 SavedMainFileBuffer.reset();
2114
2115 SourceMgr.reset();
2116 TheSema.reset();
2117 Ctx.reset();
2118 PP.reset();
2119 Reader.reset();
2120
2121 TopLevelDecls.clear();
2122 clearFileLevelDecls();
2123}
2124
Douglas Gregorb14904c2010-08-13 22:48:40 +00002125//----------------------------------------------------------------------------//
2126// Code completion
2127//----------------------------------------------------------------------------//
2128
2129namespace {
2130 /// \brief Code completion consumer that combines the cached code-completion
2131 /// results from an ASTUnit with the code-completion results provided to it,
2132 /// then passes the result on to
2133 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002134 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002135 ASTUnit &AST;
2136 CodeCompleteConsumer &Next;
2137
2138 public:
2139 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002140 const CodeCompleteOptions &CodeCompleteOpts)
2141 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2142 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002143 {
2144 // Compute the set of contexts in which we will look when we don't have
2145 // any information about the specific context.
2146 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002147 = (1LL << CodeCompletionContext::CCC_TopLevel)
2148 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2149 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2150 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2151 | (1LL << CodeCompletionContext::CCC_Statement)
2152 | (1LL << CodeCompletionContext::CCC_Expression)
2153 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2154 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2155 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2156 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2157 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2158 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2159 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002160
David Blaikiebbafb8a2012-03-11 07:00:24 +00002161 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002162 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2163 | (1LL << CodeCompletionContext::CCC_UnionTag)
2164 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002165 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002166
2167 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2168 CodeCompletionResult *Results,
2169 unsigned NumResults) override;
2170
2171 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2172 OverloadCandidate *Candidates,
2173 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002174 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2175 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002176
2177 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002178 return Next.getAllocator();
2179 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002180
Craig Topperafa7cb32014-03-13 06:07:04 +00002181 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002182 return Next.getCodeCompletionTUInfo();
2183 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002184 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002185} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00002186
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002187/// \brief Helper function that computes which global names are hidden by the
2188/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002189static void CalculateHiddenNames(const CodeCompletionContext &Context,
2190 CodeCompletionResult *Results,
2191 unsigned NumResults,
2192 ASTContext &Ctx,
2193 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002194 bool OnlyTagNames = false;
2195 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002196 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002197 case CodeCompletionContext::CCC_TopLevel:
2198 case CodeCompletionContext::CCC_ObjCInterface:
2199 case CodeCompletionContext::CCC_ObjCImplementation:
2200 case CodeCompletionContext::CCC_ObjCIvarList:
2201 case CodeCompletionContext::CCC_ClassStructUnion:
2202 case CodeCompletionContext::CCC_Statement:
2203 case CodeCompletionContext::CCC_Expression:
2204 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002205 case CodeCompletionContext::CCC_DotMemberAccess:
2206 case CodeCompletionContext::CCC_ArrowMemberAccess:
2207 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002208 case CodeCompletionContext::CCC_Namespace:
2209 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002210 case CodeCompletionContext::CCC_Name:
2211 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002212 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002213 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002214 break;
2215
2216 case CodeCompletionContext::CCC_EnumTag:
2217 case CodeCompletionContext::CCC_UnionTag:
2218 case CodeCompletionContext::CCC_ClassOrStructTag:
2219 OnlyTagNames = true;
2220 break;
2221
2222 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002223 case CodeCompletionContext::CCC_MacroName:
2224 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002225 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002226 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002227 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002228 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002229 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002230 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002231 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002232 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2233 case CodeCompletionContext::CCC_ObjCClassMessage:
2234 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002235 // We're looking for nothing, or we're looking for names that cannot
2236 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002237 return;
2238 }
2239
John McCall276321a2010-08-25 06:19:51 +00002240 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002241 for (unsigned I = 0; I != NumResults; ++I) {
2242 if (Results[I].Kind != Result::RK_Declaration)
2243 continue;
2244
2245 unsigned IDNS
2246 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2247
2248 bool Hiding = false;
2249 if (OnlyTagNames)
2250 Hiding = (IDNS & Decl::IDNS_Tag);
2251 else {
2252 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002253 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2254 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002255 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002256 HiddenIDNS |= Decl::IDNS_Tag;
2257 Hiding = (IDNS & HiddenIDNS);
2258 }
2259
2260 if (!Hiding)
2261 continue;
2262
2263 DeclarationName Name = Results[I].Declaration->getDeclName();
2264 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2265 HiddenNames.insert(Identifier->getName());
2266 else
2267 HiddenNames.insert(Name.getAsString());
2268 }
2269}
2270
Douglas Gregord46cf182010-08-16 20:01:48 +00002271void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2272 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002273 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002274 unsigned NumResults) {
2275 // Merge the results we were given with the results we cached.
2276 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002277 uint64_t InContexts =
2278 Context.getKind() == CodeCompletionContext::CCC_Recovery
2279 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002280 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002281 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002282 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002283 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002284 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002285 C = AST.cached_completion_begin(),
2286 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002287 C != CEnd; ++C) {
2288 // If the context we are in matches any of the contexts we are
2289 // interested in, we'll add this result.
2290 if ((C->ShowInContexts & InContexts) == 0)
2291 continue;
2292
2293 // If we haven't added any results previously, do so now.
2294 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002295 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2296 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002297 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2298 AddedResult = true;
2299 }
2300
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002301 // Determine whether this global completion result is hidden by a local
2302 // completion result. If so, skip it.
2303 if (C->Kind != CXCursor_MacroDefinition &&
2304 HiddenNames.count(C->Completion->getTypedText()))
2305 continue;
2306
Douglas Gregord46cf182010-08-16 20:01:48 +00002307 // Adjust priority based on similar type classes.
2308 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002309 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002310 if (!Context.getPreferredType().isNull()) {
2311 if (C->Kind == CXCursor_MacroDefinition) {
2312 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002313 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002314 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002315 } else if (C->Type) {
2316 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002317 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002318 Context.getPreferredType().getUnqualifiedType());
2319 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2320 if (ExpectedSTC == C->TypeClass) {
2321 // We know this type is similar; check for an exact match.
2322 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002323 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002324 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002325 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002326 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2327 Priority /= CCF_ExactTypeMatch;
2328 else
2329 Priority /= CCF_SimilarTypeMatch;
2330 }
2331 }
2332 }
2333
Douglas Gregor12785102010-08-24 20:21:13 +00002334 // Adjust the completion string, if required.
2335 if (C->Kind == CXCursor_MacroDefinition &&
2336 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2337 // Create a new code-completion string that just contains the
2338 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002339 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2340 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002341 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002342 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002343 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002344 }
2345
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002346 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002347 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002348 }
2349
2350 // If we did not add any cached completion results, just forward the
2351 // results we were given to the next consumer.
2352 if (!AddedResult) {
2353 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2354 return;
2355 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002356
Douglas Gregord46cf182010-08-16 20:01:48 +00002357 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2358 AllResults.size());
2359}
2360
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002361void ASTUnit::CodeComplete(
2362 StringRef File, unsigned Line, unsigned Column,
2363 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2364 bool IncludeCodePatterns, bool IncludeBriefComments,
2365 CodeCompleteConsumer &Consumer,
2366 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2367 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2368 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2369 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002370 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002371 return;
2372
Douglas Gregor16896c42010-10-28 15:44:59 +00002373 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002374 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002375 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002376
David Blaikieea4395e2017-01-06 19:49:01 +00002377 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002378
2379 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002380 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002381 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002382
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002383 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2384 CachedCompletionResults.empty();
2385 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2386 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2387 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2388
2389 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2390
Douglas Gregor8e984da2010-08-04 16:47:14 +00002391 FrontendOpts.CodeCompletionAt.FileName = File;
2392 FrontendOpts.CodeCompletionAt.Line = Line;
2393 FrontendOpts.CodeCompletionAt.Column = Column;
2394
2395 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002396 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002397
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002398 // Spell-checking and warnings are wasteful during code-completion.
2399 LangOpts.SpellChecking = false;
2400 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2401
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002402 std::unique_ptr<CompilerInstance> Clang(
2403 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002404
2405 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002406 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2407 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002408
David Blaikieea4395e2017-01-06 19:49:01 +00002409 auto &Inv = *CCInvocation;
2410 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002411 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002412
2413 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002414 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002415 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002416 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002417 StoredDiagnostics);
David Blaikieea4395e2017-01-06 19:49:01 +00002418 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2419
Douglas Gregor8e984da2010-08-04 16:47:14 +00002420 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002421 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002422 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002423 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002424 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002425 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002426 }
2427
2428 // Inform the target of the language options.
2429 //
2430 // FIXME: We shouldn't need to do this, the target should be immutable once
2431 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002432 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002433
Ted Kremenek84de4a12011-03-21 18:40:07 +00002434 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002435 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002436 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2437 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002438 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002439 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2440 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002441 "IR inputs not support here!");
Douglas Gregor8e984da2010-08-04 16:47:14 +00002442
2443 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002444 Clang->setFileManager(&FileMgr);
2445 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002446
2447 // Remap files.
2448 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002449 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002450 for (const auto &RemappedFile : RemappedFiles) {
2451 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2452 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002453 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002454
Douglas Gregorb14904c2010-08-13 22:48:40 +00002455 // Use the code completion consumer we were given, but adding any cached
2456 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002457 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002458 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002459 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002460
Douglas Gregor028d3e42010-08-09 20:45:32 +00002461 // If we have a precompiled preamble, try to use it. We only allow
2462 // the use of the precompiled preamble if we're if the completion
2463 // point is within the main file, after the end of the precompiled
2464 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002465 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002466 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002467 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002468
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002469 auto VFS = FileMgr.getVirtualFileSystem();
2470 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2471 if (CompleteFileStatus) {
2472 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2473
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002474 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002475 auto MainStatus = VFS->status(MainPath);
2476 if (MainStatus) {
2477 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002478 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002479 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002480 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002481 }
2482 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002483 }
2484
2485 // If the main file has been overridden due to the use of a preamble,
2486 // make that override happen and introduce the preamble.
2487 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002488 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2489 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002490 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2491 PreprocessorOpts.PrecompiledPreambleBytes.second
2492 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002493 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002494 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002495
2496 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002497 } else {
2498 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2499 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002500 }
2501
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002502 // Disable the preprocessing record if modules are not enabled.
2503 if (!Clang->getLangOpts().Modules)
2504 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002505
2506 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002507 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002508 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002509 Act->Execute();
2510 Act->EndSourceFile();
2511 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002512}
Douglas Gregore9386682010-08-13 05:36:37 +00002513
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002514bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002515 if (HadModuleLoaderFatalFailure)
2516 return true;
2517
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002518 // Write to a temporary file and later rename it to the actual file, to avoid
2519 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002520 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002521 TempPath = File;
2522 TempPath += "-%%%%%%%%";
2523 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002524 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002525 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002526
Douglas Gregore9386682010-08-13 05:36:37 +00002527 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2528 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002529 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002530
2531 serialize(Out);
2532 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002533 if (Out.has_error()) {
2534 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002535 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002536 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002537
Yaron Keren92e1b622015-03-18 10:17:07 +00002538 if (llvm::sys::fs::rename(TempPath, File)) {
2539 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002540 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002541 }
2542
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002543 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002544}
2545
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002546static bool serializeUnit(ASTWriter &Writer,
2547 SmallVectorImpl<char> &Buffer,
2548 Sema &S,
2549 bool hasErrors,
2550 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002551 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002552
2553 // Write the generated bitstream to "Out".
2554 if (!Buffer.empty())
2555 OS.write(Buffer.data(), Buffer.size());
2556
2557 return false;
2558}
2559
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002560bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002561 // For serialization we are lenient if the errors were only warn-as-error kind.
2562 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002563
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002564 if (WriterData)
2565 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2566 getSema(), hasErrors, OS);
2567
Daniel Dunbar9a963862012-02-29 20:31:23 +00002568 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002569 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002570 MemoryBufferCache PCMCache;
2571 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002572 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002573}
Douglas Gregor925296b2011-07-19 16:10:42 +00002574
2575typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2576
Douglas Gregor925296b2011-07-19 16:10:42 +00002577void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002578 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002579 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002580 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002581 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002582 // Map the standalone diagnostic into the new source manager. We also need to
2583 // remap all the locations to the new view. This includes the diag location,
2584 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002585 // FIXME: There should be a cleaner way to do this.
2586
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002587 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002588 Result.reserve(Diags.size());
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002589 const FileEntry *PreviousFE = nullptr;
2590 FileID FID;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002591 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002592 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002593 if (SD.Filename.empty())
2594 continue;
2595 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2596 if (!FE)
2597 continue;
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002598 if (FE != PreviousFE) {
2599 FID = SrcMgr.translateFile(FE);
2600 PreviousFE = FE;
2601 }
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002602 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2603 if (FileLoc.isInvalid())
2604 continue;
2605 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002606 FullSourceLoc Loc(L, SrcMgr);
2607
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002608 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002609 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002610 for (const auto &Range : SD.Ranges) {
2611 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2612 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002613 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002614 }
2615
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002616 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002617 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002618 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002619 FixIts.push_back(FixItHint());
2620 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002621 FH.CodeToInsert = FixIt.CodeToInsert;
2622 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2623 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002624 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002625 }
2626
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002627 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2628 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002629 }
2630 Result.swap(Out);
2631}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002632
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002633void ASTUnit::addFileLevelDecl(Decl *D) {
2634 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002635
2636 // We only care about local declarations.
2637 if (D->isFromASTFile())
2638 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002639
2640 SourceManager &SM = *SourceMgr;
2641 SourceLocation Loc = D->getLocation();
2642 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2643 return;
2644
2645 // We only keep track of the file-level declarations of each file.
2646 if (!D->getLexicalDeclContext()->isFileContext())
2647 return;
2648
2649 SourceLocation FileLoc = SM.getFileLoc(Loc);
2650 assert(SM.isLocalSourceLocation(FileLoc));
2651 FileID FID;
2652 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002653 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002654 if (FID.isInvalid())
2655 return;
2656
2657 LocDeclsTy *&Decls = FileDecls[FID];
2658 if (!Decls)
2659 Decls = new LocDeclsTy();
2660
2661 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2662
2663 if (Decls->empty() || Decls->back().first <= Offset) {
2664 Decls->push_back(LocDecl);
2665 return;
2666 }
2667
Benjamin Kramer45025c02013-08-24 13:22:59 +00002668 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2669 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002670
2671 Decls->insert(I, LocDecl);
2672}
2673
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002674void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2675 SmallVectorImpl<Decl *> &Decls) {
2676 if (File.isInvalid())
2677 return;
2678
2679 if (SourceMgr->isLoadedFileID(File)) {
2680 assert(Ctx->getExternalSource() && "No external source!");
2681 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2682 Decls);
2683 }
2684
2685 FileDeclsTy::iterator I = FileDecls.find(File);
2686 if (I == FileDecls.end())
2687 return;
2688
2689 LocDeclsTy &LocDecls = *I->second;
2690 if (LocDecls.empty())
2691 return;
2692
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002693 LocDeclsTy::iterator BeginIt =
2694 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002695 std::make_pair(Offset, (Decl *)nullptr),
2696 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002697 if (BeginIt != LocDecls.begin())
2698 --BeginIt;
2699
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002700 // If we are pointing at a top-level decl inside an objc container, we need
2701 // to backtrack until we find it otherwise we will fail to report that the
2702 // region overlaps with an objc container.
2703 while (BeginIt != LocDecls.begin() &&
2704 BeginIt->second->isTopLevelDeclInObjCContainer())
2705 --BeginIt;
2706
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002707 LocDeclsTy::iterator EndIt = std::upper_bound(
2708 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002709 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002710 if (EndIt != LocDecls.end())
2711 ++EndIt;
2712
2713 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2714 Decls.push_back(DIt->second);
2715}
2716
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002717SourceLocation ASTUnit::getLocation(const FileEntry *File,
2718 unsigned Line, unsigned Col) const {
2719 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002720 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002721 return SM.getMacroArgExpandedLocation(Loc);
2722}
2723
2724SourceLocation ASTUnit::getLocation(const FileEntry *File,
2725 unsigned Offset) const {
2726 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002727 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002728 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2729}
2730
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002731/// \brief If \arg Loc is a loaded location from the preamble, returns
2732/// the corresponding local location of the main file, otherwise it returns
2733/// \arg Loc.
2734SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2735 FileID PreambleID;
2736 if (SourceMgr)
2737 PreambleID = SourceMgr->getPreambleFileID();
2738
2739 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2740 return Loc;
2741
2742 unsigned Offs;
2743 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2744 SourceLocation FileLoc
2745 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2746 return FileLoc.getLocWithOffset(Offs);
2747 }
2748
2749 return Loc;
2750}
2751
2752/// \brief If \arg Loc is a local location of the main file but inside the
2753/// preamble chunk, returns the corresponding loaded location from the
2754/// preamble, otherwise it returns \arg Loc.
2755SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2756 FileID PreambleID;
2757 if (SourceMgr)
2758 PreambleID = SourceMgr->getPreambleFileID();
2759
2760 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2761 return Loc;
2762
2763 unsigned Offs;
2764 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2765 Offs < Preamble.size()) {
2766 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2767 return FileLoc.getLocWithOffset(Offs);
2768 }
2769
2770 return Loc;
2771}
2772
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002773bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2774 FileID FID;
2775 if (SourceMgr)
2776 FID = SourceMgr->getPreambleFileID();
2777
2778 if (Loc.isInvalid() || FID.isInvalid())
2779 return false;
2780
2781 return SourceMgr->isInFileID(Loc, FID);
2782}
2783
2784bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2785 FileID FID;
2786 if (SourceMgr)
2787 FID = SourceMgr->getMainFileID();
2788
2789 if (Loc.isInvalid() || FID.isInvalid())
2790 return false;
2791
2792 return SourceMgr->isInFileID(Loc, FID);
2793}
2794
2795SourceLocation ASTUnit::getEndOfPreambleFileID() {
2796 FileID FID;
2797 if (SourceMgr)
2798 FID = SourceMgr->getPreambleFileID();
2799
2800 if (FID.isInvalid())
2801 return SourceLocation();
2802
2803 return SourceMgr->getLocForEndOfFile(FID);
2804}
2805
2806SourceLocation ASTUnit::getStartOfMainFileID() {
2807 FileID FID;
2808 if (SourceMgr)
2809 FID = SourceMgr->getMainFileID();
2810
2811 if (FID.isInvalid())
2812 return SourceLocation();
2813
2814 return SourceMgr->getLocForStartOfFile(FID);
2815}
2816
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002817llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002818ASTUnit::getLocalPreprocessingEntities() const {
2819 if (isMainFileAST()) {
2820 serialization::ModuleFile &
2821 Mod = Reader->getModuleManager().getPrimaryModule();
2822 return Reader->getModulePreprocessedEntities(Mod);
2823 }
2824
2825 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002826 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002827
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002828 return llvm::make_range(PreprocessingRecord::iterator(),
2829 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002830}
2831
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002832bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002833 if (isMainFileAST()) {
2834 serialization::ModuleFile &
2835 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002836 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2837 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002838 return false;
2839 }
2840
2841 return true;
2842 }
2843
2844 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2845 TLEnd = top_level_end();
2846 TL != TLEnd; ++TL) {
2847 if (!Fn(context, *TL))
2848 return false;
2849 }
2850
2851 return true;
2852}
2853
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002854const FileEntry *ASTUnit::getPCHFile() {
2855 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002856 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002857
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002858 serialization::ModuleFile *Mod = nullptr;
2859 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2860 switch (M.Kind) {
2861 case serialization::MK_ImplicitModule:
2862 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002863 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002864 return true; // skip dependencies.
2865 case serialization::MK_PCH:
2866 Mod = &M;
2867 return true; // found it.
2868 case serialization::MK_Preamble:
2869 return false; // look in dependencies.
2870 case serialization::MK_MainFile:
2871 return false; // look in dependencies.
2872 }
2873
2874 return true;
2875 });
2876 if (Mod)
2877 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002878
Craig Topper49a27902014-05-22 04:46:25 +00002879 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002880}
2881
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002882bool ASTUnit::isModuleFile() {
Richard Smithab755972017-06-05 18:10:11 +00002883 return isMainFileAST() && getLangOpts().isCompilingModule();
2884}
2885
2886InputKind ASTUnit::getInputKind() const {
2887 auto &LangOpts = getLangOpts();
2888
2889 InputKind::Language Lang;
2890 if (LangOpts.OpenCL)
2891 Lang = InputKind::OpenCL;
2892 else if (LangOpts.CUDA)
2893 Lang = InputKind::CUDA;
2894 else if (LangOpts.RenderScript)
2895 Lang = InputKind::RenderScript;
2896 else if (LangOpts.CPlusPlus)
2897 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2898 else
2899 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2900
2901 InputKind::Format Fmt = InputKind::Source;
2902 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2903 Fmt = InputKind::ModuleMap;
2904
2905 // We don't know if input was preprocessed. Assume not.
2906 bool PP = false;
2907
2908 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002909}
2910
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002911void ASTUnit::PreambleData::countLines() const {
2912 NumLines = 0;
2913 if (empty())
2914 return;
2915
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002916 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2917
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002918 if (Buffer.back() != '\n')
2919 ++NumLines;
2920}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002921
2922#ifndef NDEBUG
2923ASTUnit::ConcurrencyState::ConcurrencyState() {
2924 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2925}
2926
2927ASTUnit::ConcurrencyState::~ConcurrencyState() {
2928 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2929}
2930
2931void ASTUnit::ConcurrencyState::start() {
2932 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2933 assert(acquired && "Concurrent access to ASTUnit!");
2934}
2935
2936void ASTUnit::ConcurrencyState::finish() {
2937 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2938}
2939
2940#else // NDEBUG
2941
Hans Wennborgdcfba332015-10-06 23:40:43 +00002942ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002943ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002944void ASTUnit::ConcurrencyState::start() {}
2945void ASTUnit::ConcurrencyState::finish() {}
2946
Hans Wennborgdcfba332015-10-06 23:40:43 +00002947#endif // NDEBUG