blob: 6ee211c2de671a90b094ebc6bcd0540d6b14a8dc [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 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000093}
Ted Kremenek06b4f912011-10-27 17:55:18 +000094
Ted Kremenekbd307a52011-10-27 19:44:25 +000095static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
96 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
97 return M;
98}
99
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000100static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000101
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000102typedef llvm::DenseMap<const ASTUnit *,
103 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000104static OnDiskDataMap &getOnDiskDataMap() {
105 static OnDiskDataMap M;
106 static bool hasRegisteredAtExit = false;
107 if (!hasRegisteredAtExit) {
108 hasRegisteredAtExit = true;
109 atexit(cleanupOnDiskMapAtExit);
110 }
111 return M;
112}
113
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000114static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000115 // Use the mutex because there can be an alive thread destroying an ASTUnit.
116 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000117 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000118 // We don't worry about freeing the memory associated with OnDiskDataMap.
119 // All we care about is erasing stale files.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000120 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000121 }
122}
123
124static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000125 // We require the mutex since we are modifying the structure of the
126 // DenseMap.
127 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000128 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000129 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000130 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000131 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000132 return *D;
133}
134
135static void erasePreambleFile(const ASTUnit *AU) {
136 getOnDiskData(AU).CleanPreambleFile();
137}
138
139static void removeOnDiskEntry(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();
144 OnDiskDataMap::iterator I = M.find(AU);
145 if (I != M.end()) {
146 I->second->Cleanup();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000147 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000148 }
149}
150
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000151static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152 getOnDiskData(AU).PreambleFile = preambleFile;
153}
154
155static const std::string &getPreambleFile(const ASTUnit *AU) {
156 return getOnDiskData(AU).PreambleFile;
157}
158
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159void OnDiskData::CleanPreambleFile() {
160 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000161 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000162 PreambleFile.clear();
163 }
164}
165
166void OnDiskData::Cleanup() {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000167 CleanPreambleFile();
168}
169
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000170struct ASTUnit::ASTWriterData {
171 SmallString<128> Buffer;
172 llvm::BitstreamWriter Stream;
173 ASTWriter Writer;
174
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000175 ASTWriterData(MemoryBufferCache &PCMCache)
176 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000177};
178
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000179void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000180 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000181}
182
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000183/// \brief After failing to build a precompiled preamble (due to
184/// errors in the source that occurs in the preamble), the number of
185/// reparses during which we'll skip even trying to precompile the
186/// preamble.
187const unsigned DefaultPreambleRebuildInterval = 5;
188
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000189/// \brief Tracks the number of ASTUnit objects that are currently active.
190///
191/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000192static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000193
Douglas Gregord03e8232010-04-05 21:10:19 +0000194ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000195 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000196 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000197 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000198 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000199 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000200 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000201 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000202 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000203 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000204 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000205 CompletionCacheTopLevelHashValue(0),
206 PreambleTopLevelHashValue(0),
207 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000208 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000209 if (getenv("LIBCLANG_OBJTRACKING"))
210 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000211}
Douglas Gregord03e8232010-04-05 21:10:19 +0000212
Daniel Dunbar764c0822009-12-01 09:51:01 +0000213ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000214 // If we loaded from an AST file, balance out the BeginSourceFile call.
215 if (MainFileIsAST && getDiagnostics().getClient()) {
216 getDiagnostics().getClient()->EndSourceFile();
217 }
218
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000219 clearFileLevelDecls();
220
Ted Kremenek06b4f912011-10-27 17:55:18 +0000221 // Clean up the temporary files and the preamble file.
222 removeOnDiskEntry(this);
223
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000224 // Free the buffers associated with remapped files. We are required to
225 // perform this operation here because we explicitly request that the
226 // compiler instance *not* free these buffers for each invocation of the
227 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000228 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000229 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000230 for (const auto &RB : PPOpts.RemappedFileBuffers)
231 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000232 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000233
Douglas Gregor16896c42010-10-28 15:44:59 +0000234 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000235
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000236 if (getenv("LIBCLANG_OBJTRACKING"))
237 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000238}
239
David Blaikie41565462017-01-05 19:48:07 +0000240void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
241 this->PP = std::move(PP);
242}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000243
Douglas Gregor39982192010-08-15 06:18:01 +0000244/// \brief Determine the set of code-completion contexts in which this
245/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000246static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000247 const LangOptions &LangOpts,
248 bool &IsNestedNameSpecifier) {
249 IsNestedNameSpecifier = false;
250
Douglas Gregor39982192010-08-15 06:18:01 +0000251 if (isa<UsingShadowDecl>(ND))
252 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
253 if (!ND)
254 return 0;
255
Richard Smith697cc9e2012-08-14 03:13:00 +0000256 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000257 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
258 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
259 // Types can appear in these contexts.
260 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000261 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
262 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
263 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
264 | (1LL << CodeCompletionContext::CCC_Statement)
265 | (1LL << CodeCompletionContext::CCC_Type)
266 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000267
268 // In C++, types can appear in expressions contexts (for functional casts).
269 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000270 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000271
272 // In Objective-C, message sends can send interfaces. In Objective-C++,
273 // all types are available due to functional casts.
274 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000275 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000276
277 // In Objective-C, you can only be a subclass of another Objective-C class
278 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000279 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000280
281 // Deal with tag names.
282 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000284
Douglas Gregor59cab552010-08-16 23:05:20 +0000285 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000286 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000287 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000288 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000289 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000290 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000291 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000293
Douglas Gregor39982192010-08-15 06:18:01 +0000294 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000295 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000296 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000297 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000298 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
299 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000300 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
301 | (1LL << CodeCompletionContext::CCC_Expression)
302 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
303 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000304 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000305 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000306 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000307 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000308 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000309 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000310
311 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000312 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000313 }
314
315 return Contexts;
316}
317
Douglas Gregorb14904c2010-08-13 22:48:40 +0000318void ASTUnit::CacheCodeCompletionResults() {
319 if (!TheSema)
320 return;
321
Douglas Gregor16896c42010-10-28 15:44:59 +0000322 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000323 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000324
325 // Clear out the previous results.
326 ClearCachedCompletionResults();
327
328 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000329 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000330 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000331 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000332 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000333 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000334 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000335
336 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000337 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000338 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000339
340 for (Result &R : Results) {
341 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000342 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000343 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000344 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000345 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000346 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000347 IncludeBriefCommentsInCodeCompletion);
348 CachedResult.ShowInContexts = getDeclShowContexts(
349 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
350 CachedResult.Priority = R.Priority;
351 CachedResult.Kind = R.CursorKind;
352 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000353
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000354 // Keep track of the type of this completion in an ASTContext-agnostic
355 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000356 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000357 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000358 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000359 CachedResult.Type = 0;
360 } else {
361 CanQualType CanUsageType
362 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
363 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
364
365 // Determine whether we have already seen this type. If so, we save
366 // ourselves the work of formatting the type string by using the
367 // temporary, CanQualType-based hash table to find the associated value.
368 unsigned &TypeValue = CompletionTypes[CanUsageType];
369 if (TypeValue == 0) {
370 TypeValue = CompletionTypes.size();
371 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
372 = TypeValue;
373 }
374
375 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000376 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000377
Douglas Gregor39982192010-08-15 06:18:01 +0000378 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000379
380 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000381 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
382 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000383 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000384 uint64_t NNSContexts
385 = (1LL << CodeCompletionContext::CCC_TopLevel)
386 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
387 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
388 | (1LL << CodeCompletionContext::CCC_Statement)
389 | (1LL << CodeCompletionContext::CCC_Expression)
390 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
391 | (1LL << CodeCompletionContext::CCC_EnumTag)
392 | (1LL << CodeCompletionContext::CCC_UnionTag)
393 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
394 | (1LL << CodeCompletionContext::CCC_Type)
395 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
396 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000397
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000398 if (isa<NamespaceDecl>(R.Declaration) ||
399 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000400 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000401
402 if (unsigned RemainingContexts
403 = NNSContexts & ~CachedResult.ShowInContexts) {
404 // If there any contexts where this completion can be a
405 // nested-name-specifier but isn't already an option, create a
406 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000407 R.StartsNestedNameSpecifier = true;
408 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000409 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000410 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000411 CachedResult.ShowInContexts = RemainingContexts;
412 CachedResult.Priority = CCP_NestedNameSpecifier;
413 CachedResult.TypeClass = STC_Void;
414 CachedResult.Type = 0;
415 CachedCompletionResults.push_back(CachedResult);
416 }
417 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000418 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000419 }
420
Douglas Gregorb14904c2010-08-13 22:48:40 +0000421 case Result::RK_Keyword:
422 case Result::RK_Pattern:
423 // Ignore keywords and patterns; we don't care, since they are so
424 // easily regenerated.
425 break;
426
427 case Result::RK_Macro: {
428 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000429 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000430 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000431 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000432 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000433 = (1LL << CodeCompletionContext::CCC_TopLevel)
434 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
435 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
436 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
437 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
438 | (1LL << CodeCompletionContext::CCC_Statement)
439 | (1LL << CodeCompletionContext::CCC_Expression)
440 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
441 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
442 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
443 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
444 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000445
446 CachedResult.Priority = R.Priority;
447 CachedResult.Kind = R.CursorKind;
448 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000449 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000450 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000451 CachedCompletionResults.push_back(CachedResult);
452 break;
453 }
454 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000455 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000456
457 // Save the current top-level hash value.
458 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000459}
460
461void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000462 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000463 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000464 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000465}
466
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000467namespace {
468
Sebastian Redl2c499f62010-08-18 23:56:43 +0000469/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000470/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000471class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000472 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000473 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000474 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000475 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000476 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000477 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000478
Douglas Gregore8bbc122011-09-02 00:18:52 +0000479 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000480public:
Alp Toker80758082014-07-06 05:26:44 +0000481 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
482 std::shared_ptr<TargetOptions> &TargetOpts,
483 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
484 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
485 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000486
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000487 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
488 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000489 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000490 return false;
491
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000492 LangOpt = LangOpts;
493 InitializedLanguage = true;
494
495 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000496 return false;
497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000499 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
500 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000501 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000502 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000503 return false;
Alp Toker80758082014-07-06 05:26:44 +0000504
505 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
506 Target =
507 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000508
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000509 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000510 return false;
511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Craig Topperafa7cb32014-03-13 06:07:04 +0000513 void ReadCounter(const serialization::ModuleFile &M,
514 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000515 Counter = Value;
516 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000517
518private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000519 void updated() {
520 if (!Target || !InitializedLanguage)
521 return;
522
523 // Inform the target of the language options.
524 //
525 // FIXME: We shouldn't need to do this, the target should be immutable once
526 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000527 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000528
529 // Initialize the preprocessor.
530 PP.Initialize(*Target);
531
532 // Initialize the ASTContext
533 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000534
535 // We didn't have access to the comment options when the ASTContext was
536 // constructed, so register them now.
537 Context.getCommentCommandTraits().registerCommentOptions(
538 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000539 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000540};
541
Douglas Gregor6b930962013-05-03 22:58:43 +0000542 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000543class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000544 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000545 SourceManager *SourceMgr;
546
Douglas Gregor33cdd812010-02-18 18:08:43 +0000547public:
David Blaikief18d91a2011-09-26 00:01:39 +0000548 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000549 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000550 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000551
Craig Topperafa7cb32014-03-13 06:07:04 +0000552 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000553 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000554 if (PP)
555 SourceMgr = &PP->getSourceManager();
556 }
557
Craig Topperafa7cb32014-03-13 06:07:04 +0000558 void HandleDiagnostic(DiagnosticsEngine::Level Level,
559 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000560};
561
562/// \brief RAII object that optionally captures diagnostics, if
563/// there is no diagnostic client to capture them already.
564class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000565 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000566 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000567 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000568 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000569
570public:
David Blaikie9c902b52011-09-25 23:23:43 +0000571 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000572 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000573 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000574 {
Craig Topper49a27902014-05-22 04:46:25 +0000575 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000576 OwningPreviousClient = Diags.takeClient();
577 PreviousClient = Diags.getClient();
578 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000579 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000580 }
581
582 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000583 if (Diags.getClient() == &Client)
584 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000585 }
586};
587
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000588} // anonymous namespace
589
David Blaikief18d91a2011-09-26 00:01:39 +0000590void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000591 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000592 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000593 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000594
Douglas Gregor6b930962013-05-03 22:58:43 +0000595 // Only record the diagnostic if it's part of the source manager we know
596 // about. This effectively drops diagnostics from modules we're building.
597 // FIXME: In the long run, ee don't want to drop source managers from modules.
598 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000599 StoredDiags.emplace_back(Level, Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000600}
601
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000602IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
603 return Reader;
604}
605
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000606ASTMutationListener *ASTUnit::getASTMutationListener() {
607 if (WriterData)
608 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000609 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000610}
611
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000612ASTDeserializationListener *ASTUnit::getDeserializationListener() {
613 if (WriterData)
614 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000615 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000616}
617
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000618std::unique_ptr<llvm::MemoryBuffer>
619ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000620 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000621 auto Buffer = FileMgr->getBufferForFile(Filename);
622 if (Buffer)
623 return std::move(*Buffer);
624 if (ErrorStr)
625 *ErrorStr = Buffer.getError().message();
626 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000627}
628
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000629/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000630void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000631 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000632 assert(Diags.get() && "no DiagnosticsEngine was provided");
633 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000634 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000635}
636
David Blaikie6f7382d2014-08-10 19:08:04 +0000637std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000638 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000639 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000640 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
641 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
642 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
643 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000644 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000645
646 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000647 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
648 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000649 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
650 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000651 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000652
Justin Bognerdbbcb112014-10-14 23:36:06 +0000653 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000654
Douglas Gregor16bef852009-10-16 20:01:17 +0000655 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000656 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000657 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000658 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
659 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000660 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000661 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000662 AST->getFileManager(),
663 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000664 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000665 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000666 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000667 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000668 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000669 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000670 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000671 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000672
David Blaikiee3041682017-01-05 19:11:36 +0000673 auto PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000674
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000675 for (const auto &RemappedFile : RemappedFiles)
676 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000677
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000678 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000679
David Blaikie6f7382d2014-08-10 19:08:04 +0000680 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000681 unsigned Counter;
682
David Blaikie41565462017-01-05 19:48:07 +0000683 AST->PP = std::make_shared<Preprocessor>(
684 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000685 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
David Blaikie41565462017-01-05 19:48:07 +0000686 /*IILookup=*/nullptr,
687 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000688 Preprocessor &PP = *AST->PP;
689
Alp Toker08043432014-05-03 03:46:04 +0000690 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
691 PP.getIdentifierTable(), PP.getSelectorTable(),
692 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000694
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000695 bool disableValid = false;
696 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
697 disableValid = true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000698 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000699 /*isysroot=*/"",
700 /*DisableValidation=*/disableValid,
701 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000702
David Blaikie2721c322014-08-10 16:54:39 +0000703 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
704 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
705 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000706
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000707 // Attach the AST reader to the AST context as an external AST
708 // source, so that declarations will be deserialized from the
709 // AST file as needed.
710 // We need the external source to be set up before we read the AST, because
711 // eagerly-deserialized declarations may use it.
712 Context.setExternalSource(AST->Reader);
713
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000714 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000715 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000716 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000717 break;
Mike Stump11289f42009-09-09 15:08:12 +0000718
Sebastian Redl2c499f62010-08-18 23:56:43 +0000719 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000720 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000721 case ASTReader::OutOfDate:
722 case ASTReader::VersionMismatch:
723 case ASTReader::ConfigurationMismatch:
724 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000725 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000726 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000727 }
Mike Stump11289f42009-09-09 15:08:12 +0000728
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000729 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000730
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000731 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000732
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000733 // Create an AST consumer, even though it isn't used.
734 AST->Consumer.reset(new ASTConsumer);
735
Sebastian Redl2c499f62010-08-18 23:56:43 +0000736 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000737 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
738 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000739 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000740
Douglas Gregor6b930962013-05-03 22:58:43 +0000741 // Tell the diagnostic client that we have started a source file.
742 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
743
David Blaikie6f7382d2014-08-10 19:08:04 +0000744 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000745}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000746
747namespace {
748
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000749/// \brief Preprocessor callback class that updates a hash value with the names
750/// of all macros that have been defined by the translation unit.
751class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
752 unsigned &Hash;
753
754public:
755 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000756
757 void MacroDefined(const Token &MacroNameTok,
758 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000759 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
760 }
761};
762
763/// \brief Add the given declaration to the hash of all top-level entities.
764void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
765 if (!D)
766 return;
767
768 DeclContext *DC = D->getDeclContext();
769 if (!DC)
770 return;
771
772 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
773 return;
774
775 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000776 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
777 // For an unscoped enum include the enumerators in the hash since they
778 // enter the top-level namespace.
779 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000780 for (const auto *EI : EnumD->enumerators()) {
781 if (EI->getIdentifier())
782 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000783 }
784 }
785 }
786
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000787 if (ND->getIdentifier())
788 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
789 else if (DeclarationName Name = ND->getDeclName()) {
790 std::string NameStr = Name.getAsString();
791 Hash = llvm::HashString(NameStr, Hash);
792 }
793 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000794 }
795
796 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
797 if (Module *Mod = ImportD->getImportedModule()) {
798 std::string ModName = Mod->getFullModuleName();
799 Hash = llvm::HashString(ModName, Hash);
800 }
801 return;
802 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000803}
804
Daniel Dunbar644dca02009-12-04 08:17:33 +0000805class TopLevelDeclTrackerConsumer : public ASTConsumer {
806 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000807 unsigned &Hash;
808
Daniel Dunbar644dca02009-12-04 08:17:33 +0000809public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000810 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
811 : Unit(_Unit), Hash(Hash) {
812 Hash = 0;
813 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000814
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000815 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000816 if (!D)
817 return;
818
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000819 // FIXME: Currently ObjC method declarations are incorrectly being
820 // reported as top-level declarations, even though their DeclContext
821 // is the containing ObjC @interface/@implementation. This is a
822 // fundamental problem in the parser right now.
823 if (isa<ObjCMethodDecl>(D))
824 return;
825
826 AddTopLevelDeclarationToHash(D, Hash);
827 Unit.addTopLevelDecl(D);
828
829 handleFileLevelDecl(D);
830 }
831
832 void handleFileLevelDecl(Decl *D) {
833 Unit.addFileLevelDecl(D);
834 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000835 for (auto *I : NSD->decls())
836 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000837 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000838 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000839
Craig Topperafa7cb32014-03-13 06:07:04 +0000840 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000841 for (Decl *TopLevelDecl : D)
842 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000843 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000844 }
845
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000846 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000847 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000848
Craig Topperafa7cb32014-03-13 06:07:04 +0000849 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000850 for (Decl *TopLevelDecl : D)
851 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000852 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000853
Craig Topperafa7cb32014-03-13 06:07:04 +0000854 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000855 return Unit.getASTMutationListener();
856 }
857
Craig Topperafa7cb32014-03-13 06:07:04 +0000858 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000859 return Unit.getDeserializationListener();
860 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000861};
862
863class TopLevelDeclTrackerAction : public ASTFrontendAction {
864public:
865 ASTUnit &Unit;
866
David Blaikie6beb6aa2014-08-10 19:56:51 +0000867 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
868 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000869 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000870 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
871 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000872 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
873 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000874 }
875
876public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000877 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
878
Craig Topperafa7cb32014-03-13 06:07:04 +0000879 bool hasCodeCompletionSupport() const override { return false; }
880 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000881 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000882 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000883};
884
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000885class PrecompilePreambleAction : public ASTFrontendAction {
886 ASTUnit &Unit;
887 bool HasEmittedPreamblePCH;
888
889public:
890 explicit PrecompilePreambleAction(ASTUnit &Unit)
891 : Unit(Unit), HasEmittedPreamblePCH(false) {}
892
David Blaikie6beb6aa2014-08-10 19:56:51 +0000893 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
894 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000895 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
896 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000897 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000898
Craig Topperafa7cb32014-03-13 06:07:04 +0000899 bool hasCodeCompletionSupport() const override { return false; }
900 bool hasASTFileSupport() const override { return false; }
901 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000902};
903
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000904class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000905 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000906 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000907 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000908 PrecompilePreambleAction *Action;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000909 std::unique_ptr<raw_ostream> Out;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000910
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000911public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000912 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
913 const Preprocessor &PP, StringRef isysroot,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000914 std::unique_ptr<raw_ostream> Out)
Richard Smithbd97f352016-08-25 18:26:30 +0000915 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
David Blaikie61137e12017-01-05 18:23:18 +0000916 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000917 /*AllowASTWithErrors=*/true),
918 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000919 Out(std::move(Out)) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000920 Hash = 0;
921 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000922
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000923 bool HandleTopLevelDecl(DeclGroupRef DG) override {
924 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000925 // FIXME: Currently ObjC method declarations are incorrectly being
926 // reported as top-level declarations, even though their DeclContext
927 // is the containing ObjC @interface/@implementation. This is a
928 // fundamental problem in the parser right now.
929 if (isa<ObjCMethodDecl>(D))
930 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000931 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000932 TopLevelDecls.push_back(D);
933 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000934 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000935 }
936
Craig Topperafa7cb32014-03-13 06:07:04 +0000937 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000938 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000939 if (hasEmittedPCH()) {
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000940 // Write the generated bitstream to "Out".
941 *Out << getPCH();
942 // Make sure it hits disk now.
943 Out->flush();
944 // Free the buffer.
945 llvm::SmallVector<char, 0> Empty;
946 getPCH() = std::move(Empty);
947
Douglas Gregore9db88f2010-08-03 19:06:41 +0000948 // Translate the top-level declarations we captured during
949 // parsing into declaration IDs in the precompiled
950 // preamble. This will allow us to deserialize those top-level
951 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000952 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000953 // Invalid top-level decls may not have been serialized.
954 if (D->isInvalidDecl())
955 continue;
956 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
957 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000958
959 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000960 }
961 }
962};
963
Hans Wennborgdcfba332015-10-06 23:40:43 +0000964} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000965
David Blaikie6beb6aa2014-08-10 19:56:51 +0000966std::unique_ptr<ASTConsumer>
967PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
968 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000969 std::string Sysroot;
970 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000971 std::unique_ptr<raw_ostream> OS =
972 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
973 OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +0000974 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000975 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000976
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000977 if (!CI.getFrontendOpts().RelocatablePCH)
978 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000979
Craig Topperb8a70532014-09-10 04:53:53 +0000980 CI.getPreprocessor().addPPCallbacks(
981 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
982 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000983 return llvm::make_unique<PrecompilePreambleConsumer>(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000984 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
Daniel Dunbar764c0822009-12-01 09:51:01 +0000985}
986
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000987static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
988 return StoredDiag.getLocation().isValid();
989}
990
991static void
992checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000993 // Get rid of stored diagnostics except the ones from the driver which do not
994 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000995 StoredDiags.erase(
996 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
997 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000998}
999
1000static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1001 StoredDiagnostics,
1002 SourceManager &SM) {
1003 // The stored diagnostic has the old source manager in it; update
1004 // the locations to refer into the new source manager. Since we've
1005 // been careful to make sure that the source manager's state
1006 // before and after are identical, so that we can reuse the source
1007 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001008 for (StoredDiagnostic &SD : StoredDiagnostics) {
1009 if (SD.getLocation().isValid()) {
1010 FullSourceLoc Loc(SD.getLocation(), SM);
1011 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001012 }
1013 }
1014}
1015
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001016/// Parse the source file into a translation unit using the given compiler
1017/// invocation, replacing the current translation unit.
1018///
1019/// \returns True if a failure occurred that causes the ASTUnit not to
1020/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001021bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1022 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
Rafael Espindola4674a872014-08-13 17:08:22 +00001023 SavedMainFileBuffer.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001024
Rafael Espindola32482082014-08-18 16:23:45 +00001025 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001026 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001027
Daniel Dunbar764c0822009-12-01 09:51:01 +00001028 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001029 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001030 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001031
1032 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001033 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1034 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001035
David Blaikieea4395e2017-01-06 19:49:01 +00001036 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001037 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001038
Douglas Gregor8e984da2010-08-04 16:47:14 +00001039 // Set up diagnostics, capturing any diagnostics that would
1040 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001041 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001042
Daniel Dunbar764c0822009-12-01 09:51:01 +00001043 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001044 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001045 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001046 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001047 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001048
Daniel Dunbar764c0822009-12-01 09:51:01 +00001049 // Inform the target of the language options.
1050 //
1051 // FIXME: We shouldn't need to do this, the target should be immutable once
1052 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001053 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001054
Ted Kremenek84de4a12011-03-21 18:40:07 +00001055 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001056 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001057 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1058 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001059 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001060 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1061 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001062 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001063
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001064 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001065 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001066 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001067 if (!FileMgr) {
1068 Clang->createFileManager();
1069 FileMgr = &Clang->getFileManager();
1070 }
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001071 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1072 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001073 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001074 Ctx = nullptr;
1075 PP = nullptr;
1076 Reader = nullptr;
1077
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001078 // Clear out old caches and data.
1079 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001080 clearFileLevelDecls();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001081
Douglas Gregor7b02b582010-08-20 00:02:33 +00001082 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001083 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001084 TopLevelDeclsInPreamble.clear();
1085 }
1086
Daniel Dunbar764c0822009-12-01 09:51:01 +00001087 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001088 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001089
Daniel Dunbar764c0822009-12-01 09:51:01 +00001090 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001091 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001092
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001093 // If the main file has been overridden due to the use of a preamble,
1094 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001095 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001096 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001097 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1098 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001099 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1100 PreprocessorOpts.PrecompiledPreambleBytes.second
1101 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001102 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001103 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001104
Douglas Gregord9a30af2010-08-02 20:51:39 +00001105 // The stored diagnostic has the old source manager in it; update
1106 // the locations to refer into the new source manager. Since we've
1107 // been careful to make sure that the source manager's state
1108 // before and after are identical, so that we can reuse the source
1109 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001110 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001111
1112 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001113 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001114 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001115
1116 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1117 new TopLevelDeclTrackerAction(*this));
1118
Ted Kremenek022a4902011-03-22 01:15:24 +00001119 // Recover resources if we crash before exiting this method.
1120 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1121 ActCleanup(Act.get());
1122
Douglas Gregor32fbe312012-01-20 16:28:04 +00001123 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001124 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001125
Richard Smith26b8f782016-03-25 21:46:44 +00001126 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001127 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1128 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001129
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001130 if (!Act->Execute())
1131 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001132
1133 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001134
Daniel Dunbar644dca02009-12-04 08:17:33 +00001135 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001136
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001137 FailedParseDiagnostics.clear();
1138
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001139 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001140
Daniel Dunbar764c0822009-12-01 09:51:01 +00001141error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001142 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001143 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001144
1145 // Keep the ownership of the data in the ASTUnit because the client may
1146 // want to see the diagnostics.
1147 transferASTDataFromCompilerInstance(*Clang);
1148 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001149 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001150 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001151 return true;
1152}
1153
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001154/// \brief Simple function to retrieve a path for a preamble precompiled header.
1155static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001156 // FIXME: This is a hack so that we can override the preamble file during
1157 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001158 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001159 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1160 if (TmpFile)
1161 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001162
1163 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001164 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001165
1166 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001167}
1168
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001169/// \brief Compute the preamble for the main file, providing the source buffer
1170/// that corresponds to the main file along with a pair (bytes, start-of-line)
1171/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001172ASTUnit::ComputedPreamble
1173ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001174 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001175 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001176
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001177 // Try to determine if the main file has been remapped, either from the
1178 // command line (to another file) or directly through the compiler invocation
1179 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001180 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001181 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001182 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001183 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001184 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001185 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001186 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1187 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001188 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001189 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001190 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191 // We found a remapping. Try to load the resulting, remapped source.
David Blaikied6902a12014-08-29 06:34:53 +00001192 BufferOwner = getBufferForFile(RF.second);
1193 if (!BufferOwner)
1194 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001195 }
1196 }
1197 }
1198
1199 // Check whether there is a file-buffer remapping. It supercedes the
1200 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001201 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1202 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001203 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001204 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001205 if (MainFileID == MID) {
1206 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001207 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001208 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001209 }
1210 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 }
1213
1214 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001215 if (!Buffer && !BufferOwner) {
1216 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1217 if (!BufferOwner)
1218 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219 }
David Blaikie3d95d852014-08-11 22:08:06 +00001220
David Blaikied6902a12014-08-29 06:34:53 +00001221 if (!Buffer)
1222 Buffer = BufferOwner.get();
1223 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1224 *Invocation.getLangOpts(), MaxLines);
1225 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1226 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001227}
1228
Dmitri Gribenko47652522013-12-20 00:16:25 +00001229ASTUnit::PreambleFileHash
1230ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1231 PreambleFileHash Result;
1232 Result.Size = Size;
1233 Result.ModTime = ModTime;
Zachary Turner82a0c972017-03-20 23:33:18 +00001234 Result.MD5 = {};
Dmitri Gribenko47652522013-12-20 00:16:25 +00001235 return Result;
1236}
1237
1238ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1239 const llvm::MemoryBuffer *Buffer) {
1240 PreambleFileHash Result;
1241 Result.Size = Buffer->getBufferSize();
1242 Result.ModTime = 0;
1243
1244 llvm::MD5 MD5Ctx;
1245 MD5Ctx.update(Buffer->getBuffer().data());
1246 MD5Ctx.final(Result.MD5);
1247
1248 return Result;
1249}
1250
1251namespace clang {
1252bool operator==(const ASTUnit::PreambleFileHash &LHS,
1253 const ASTUnit::PreambleFileHash &RHS) {
1254 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Zachary Turner82a0c972017-03-20 23:33:18 +00001255 LHS.MD5 == RHS.MD5;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001256}
1257} // namespace clang
1258
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001259static std::pair<unsigned, unsigned>
1260makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1261 const LangOptions &LangOpts) {
1262 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1263 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1264 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1265 return std::make_pair(Offset, EndOffset);
1266}
1267
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001268static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1269 const LangOptions &LangOpts,
1270 const FixItHint &InFix) {
1271 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001272 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1273 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1274 LangOpts);
1275 OutFix.CodeToInsert = InFix.CodeToInsert;
1276 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001277 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001278}
1279
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001280static ASTUnit::StandaloneDiagnostic
1281makeStandaloneDiagnostic(const LangOptions &LangOpts,
1282 const StoredDiagnostic &InDiag) {
1283 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001284 OutDiag.ID = InDiag.getID();
1285 OutDiag.Level = InDiag.getLevel();
1286 OutDiag.Message = InDiag.getMessage();
1287 OutDiag.LocOffset = 0;
1288 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001289 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001290 const SourceManager &SM = InDiag.getLocation().getManager();
1291 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1292 OutDiag.Filename = SM.getFilename(FileLoc);
1293 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001294 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001295 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001296 for (const CharSourceRange &Range : InDiag.getRanges())
1297 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1298 for (const FixItHint &FixIt : InDiag.getFixIts())
1299 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001300
1301 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001302}
1303
Douglas Gregor4dde7492010-07-23 23:58:40 +00001304/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1305/// the source file.
1306///
1307/// This routine will compute the preamble of the main source file. If a
1308/// non-trivial preamble is found, it will precompile that preamble into a
1309/// precompiled header so that the precompiled preamble can be used to reduce
1310/// reparsing time. If a precompiled preamble has already been constructed,
1311/// this routine will determine if it is still valid and, if so, avoid
1312/// rebuilding the precompiled preamble.
1313///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001314/// \param AllowRebuild When true (the default), this routine is
1315/// allowed to rebuild the precompiled preamble if it is found to be
1316/// out-of-date.
1317///
1318/// \param MaxLines When non-zero, the maximum number of lines that
1319/// can occur within the preamble.
1320///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001321/// \returns If the precompiled preamble can be used, returns a newly-allocated
1322/// buffer that should be used in place of the main file when doing so.
1323/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001324std::unique_ptr<llvm::MemoryBuffer>
1325ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001326 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Rafael Espindola2346a372014-08-18 18:47:08 +00001327 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1328 unsigned MaxLines) {
1329
David Blaikieea4395e2017-01-06 19:49:01 +00001330 auto PreambleInvocation =
1331 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
Douglas Gregor3cc15812011-07-01 18:22:13 +00001332 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001333 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001334 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001335
David Blaikied6902a12014-08-29 06:34:53 +00001336 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001337
David Blaikied6902a12014-08-29 06:34:53 +00001338 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001339 // We couldn't find a preamble in the main source. Clear out the current
1340 // preamble, if we have one. It's obviously no good any more.
1341 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001342 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001343
1344 // The next time we actually see a preamble, precompile it.
1345 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001346 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001347 }
1348
1349 if (!Preamble.empty()) {
1350 // We've previously computed a preamble. Check whether we have the same
1351 // preamble now that we did before, and that there's enough space in
1352 // the main-file buffer within the precompiled preamble to fit the
1353 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001354 if (Preamble.size() == NewPreamble.Size &&
1355 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1356 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1357 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001358 // The preamble has not changed. We may be able to re-use the precompiled
1359 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001360
Douglas Gregor0e119552010-07-31 00:40:00 +00001361 // Check that none of the files used by the preamble have changed.
1362 bool AnyFileChanged = false;
1363
1364 // First, make a record of those files that have been overridden via
1365 // remapping or unsaved_files.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001366 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001367 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1368 if (AnyFileChanged)
1369 break;
1370
Ben Langmuirc8130a72014-02-20 21:59:23 +00001371 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001372 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001373 // If we can't stat the file we're remapping to, assume that something
1374 // horrible happened.
1375 AnyFileChanged = true;
1376 break;
1377 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001378
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001379 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001380 Status.getSize(),
1381 llvm::sys::toTimeT(Status.getLastModificationTime()));
Douglas Gregor0e119552010-07-31 00:40:00 +00001382 }
Alp Toker1b070d22014-07-07 07:47:20 +00001383
1384 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1385 if (AnyFileChanged)
1386 break;
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001387
1388 vfs::Status Status;
1389 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1390 AnyFileChanged = true;
1391 break;
1392 }
1393
1394 OverriddenFiles[Status.getUniqueID()] =
Alp Toker1b070d22014-07-07 07:47:20 +00001395 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001396 }
1397
1398 // Check whether anything has changed.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001399 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001400 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1401 !AnyFileChanged && F != FEnd;
1402 ++F) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001403 vfs::Status Status;
1404 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1405 // If we can't stat the file, assume that something horrible happened.
1406 AnyFileChanged = true;
1407 break;
1408 }
1409
1410 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1411 = OverriddenFiles.find(Status.getUniqueID());
Douglas Gregor0e119552010-07-31 00:40:00 +00001412 if (Overridden != OverriddenFiles.end()) {
1413 // This file was remapped; check whether the newly-mapped file
1414 // matches up with the previous mapping.
1415 if (Overridden->second != F->second)
1416 AnyFileChanged = true;
1417 continue;
1418 }
1419
1420 // The file was not remapped; check whether it has changed on disk.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001421 if (Status.getSize() != uint64_t(F->second.Size) ||
Pavel Labathac71c8e2016-11-09 10:52:22 +00001422 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1423 F->second.ModTime)
Douglas Gregor0e119552010-07-31 00:40:00 +00001424 AnyFileChanged = true;
1425 }
1426
1427 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001428 // Okay! We can re-use the precompiled preamble.
1429
1430 // Set the state of the diagnostic object to mimic its state
1431 // after parsing the preamble.
1432 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001433 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001434 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001435 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001436
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001437 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001438 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001439 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001440 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001441
1442 // If we aren't allowed to rebuild the precompiled preamble, just
1443 // return now.
1444 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001445 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001446
Douglas Gregor4dde7492010-07-23 23:58:40 +00001447 // We can't reuse the previously-computed preamble. Build a new one.
1448 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001449 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001450 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001451 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001452 } else if (!AllowRebuild) {
1453 // We aren't allowed to rebuild the precompiled preamble; just
1454 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001455 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001456 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001457
1458 // If the preamble rebuild counter > 1, it's because we previously
1459 // failed to build a preamble and we're not yet ready to try
1460 // again. Decrement the counter and return a failure.
1461 if (PreambleRebuildCounter > 1) {
1462 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001463 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001464 }
1465
Douglas Gregore10f0e52010-09-11 17:56:52 +00001466 // Create a temporary file for the precompiled preamble. In rare
1467 // circumstances, this can fail.
1468 std::string PreamblePCHPath = GetPreamblePCHPath();
1469 if (PreamblePCHPath.empty()) {
1470 // Try again next time.
1471 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001472 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001473 }
1474
Douglas Gregor4dde7492010-07-23 23:58:40 +00001475 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001476 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001477 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001478
Douglas Gregord9a30af2010-08-02 20:51:39 +00001479 // Save the preamble text for later; we'll need to compare against it for
1480 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001481 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001482 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001483 NewPreamble.Buffer->getBufferStart(),
1484 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1485 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001486
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001487 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001488 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001489
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001490 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001491 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001492 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001493
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001494 // Tell the compiler invocation to generate a temporary precompiled header.
1495 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001496 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001497 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001498 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1499 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001500
1501 // Create the compiler instance to use for building the precompiled preamble.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001502 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001503 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001504
1505 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001506 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1507 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001508
David Blaikieea4395e2017-01-06 19:49:01 +00001509 Clang->setInvocation(std::move(PreambleInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001510 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001511
Douglas Gregor8e984da2010-08-04 16:47:14 +00001512 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001513 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001514
1515 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001516 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001517 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001518 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001519 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001520 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001521 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001522 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001523 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001524 }
1525
1526 // Inform the target of the language options.
1527 //
1528 // FIXME: We shouldn't need to do this, the target should be immutable once
1529 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001530 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001531
Ted Kremenek84de4a12011-03-21 18:40:07 +00001532 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001533 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001534 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1535 InputKind::Source &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001536 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001537 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1538 InputKind::LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001539 "IR inputs not support here!");
1540
1541 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001542 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001543 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001544 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001545 TopLevelDecls.clear();
1546 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001547 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001548
1549 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1550 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1551 if (!VFS)
1552 return nullptr;
1553
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001555 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001556
1557 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001558 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001559 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001560
Ben Langmuir33c80902014-06-30 20:04:14 +00001561 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1562 Clang->addDependencyCollector(PreambleDepCollector);
1563
Ahmed Charlesb8984322014-03-07 20:03:18 +00001564 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001565 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001566 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001567 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001568 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001569 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001570 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001571 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001572 }
1573
1574 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001575
1576 // Transfer any diagnostics generated when parsing the preamble into the set
1577 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001578 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1579 E = stored_diag_end();
1580 I != E; ++I)
1581 PreambleDiagnostics.push_back(
1582 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001583
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001584 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001585
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001586 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1587
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001588 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001589 // The preamble PCH failed (e.g. there was a module loading fatal error),
1590 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001591 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001592 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001593 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001594 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001595 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001596 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001597 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001598 }
1599
1600 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001601 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001602 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001603
1604 // Keep track of all of the files that the source manager knows about,
1605 // so we can verify whether they have changed or not.
1606 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001607 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001608 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1609 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1610 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001611 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001612 if (time_t ModTime = File->getModificationTime()) {
1613 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001614 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001615 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001616 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001617 FilesInPreamble[File->getName()] =
1618 PreambleFileHash::createForMemoryBuffer(Buffer);
1619 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001620 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001621
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001622 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001623 PreprocessorOpts.RemappedFileBuffers.pop_back();
1624
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001625 // If the hash of top-level entities differs from the hash of the top-level
1626 // entities the last time we rebuilt the preamble, clear out the completion
1627 // cache.
1628 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1629 CompletionCacheTopLevelHashValue = 0;
1630 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1631 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001632
David Blaikied6902a12014-08-29 06:34:53 +00001633 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001634 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001635}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001636
Douglas Gregore9db88f2010-08-03 19:06:41 +00001637void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1638 std::vector<Decl *> Resolved;
1639 Resolved.reserve(TopLevelDeclsInPreamble.size());
1640 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001641 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001642 // Resolve the declaration ID to an actual declaration, possibly
1643 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001644 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001645 Resolved.push_back(D);
1646 }
1647 TopLevelDeclsInPreamble.clear();
1648 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1649}
1650
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001651void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001652 // Steal the created target, context, and preprocessor if they have been
1653 // created.
1654 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001655 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001656 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001657 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001658 if (CI.hasASTContext())
1659 Ctx = &CI.getASTContext();
1660 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001661 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001662 CI.setSourceManager(nullptr);
1663 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001664 if (CI.hasTarget())
1665 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001666 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001667 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001668}
1669
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001670StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001671 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1672 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1673 if (Input.isFile())
1674 return Input.getFile();
1675 else
1676 return Input.getBuffer()->getBufferIdentifier();
1677 }
1678
1679 if (SourceMgr) {
1680 if (const FileEntry *
1681 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1682 return FE->getName();
1683 }
1684
1685 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001686}
1687
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001688StringRef ASTUnit::getASTFileName() const {
1689 if (!isMainFileAST())
1690 return StringRef();
1691
1692 serialization::ModuleFile &
1693 Mod = Reader->getModuleManager().getPrimaryModule();
1694 return Mod.FileName;
1695}
1696
David Blaikieea4395e2017-01-06 19:49:01 +00001697std::unique_ptr<ASTUnit>
1698ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1699 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1700 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1701 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001702 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001703 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1704 createVFSFromCompilerInvocation(*CI, *Diags);
1705 if (!VFS)
1706 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001707 AST->Diagnostics = Diags;
1708 AST->FileSystemOpts = CI->getFileSystemOpts();
1709 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001710 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001711 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1712 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1713 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001714 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001715
David Blaikieea4395e2017-01-06 19:49:01 +00001716 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001717}
1718
Ahmed Charlesb8984322014-03-07 20:03:18 +00001719ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001720 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001721 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001722 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001723 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001724 bool OnlyLocalDecls, bool CaptureDiagnostics,
1725 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1726 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1727 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001728 assert(CI && "A CompilerInvocation is required");
1729
Ahmed Charlesb8984322014-03-07 20:03:18 +00001730 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001731 ASTUnit *AST = Unit;
1732 if (!AST) {
1733 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001734 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001735 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001736 if (!AST)
1737 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001738 }
1739
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001740 if (!ResourceFilesPath.empty()) {
1741 // Override the resources path.
1742 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1743 }
1744 AST->OnlyLocalDecls = OnlyLocalDecls;
1745 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001746 if (PrecompilePreambleAfterNParses > 0)
1747 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001748 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001749 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001750 AST->IncludeBriefCommentsInCodeCompletion
1751 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001752
1753 // Recover resources if we crash before exiting this method.
1754 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001755 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001756 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1757 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001758 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001759
1760 // We'll manage file buffers ourselves.
1761 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1762 CI->getFrontendOpts().DisableFree = false;
1763 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1764
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001765 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001766 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001767 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001768
1769 // Recover resources if we crash before exiting this method.
1770 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1771 CICleanup(Clang.get());
1772
David Blaikieea4395e2017-01-06 19:49:01 +00001773 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001774 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001775
1776 // Set up diagnostics, capturing any diagnostics that would
1777 // otherwise be dropped.
1778 Clang->setDiagnostics(&AST->getDiagnostics());
1779
1780 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001781 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001782 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001783 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001784 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001785
1786 // Inform the target of the language options.
1787 //
1788 // FIXME: We shouldn't need to do this, the target should be immutable once
1789 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001790 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001791
1792 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1793 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001794 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1795 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001796 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001797 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1798 InputKind::LLVM_IR &&
1799 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001800
1801 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001802 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001803 AST->Ctx = nullptr;
1804 AST->PP = nullptr;
1805 AST->Reader = nullptr;
1806
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001807 // Create a file manager object to provide access to and cache the filesystem.
1808 Clang->setFileManager(&AST->getFileManager());
1809
1810 // Create the source manager.
1811 Clang->setSourceManager(&AST->getSourceManager());
1812
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001813 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001814
Ahmed Charlesb8984322014-03-07 20:03:18 +00001815 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001816 if (!Act) {
1817 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1818 Act = TrackerAct.get();
1819 }
1820
1821 // Recover resources if we crash before exiting this method.
1822 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1823 ActCleanup(TrackerAct.get());
1824
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001825 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1826 AST->transferASTDataFromCompilerInstance(*Clang);
1827 if (OwnAST && ErrAST)
1828 ErrAST->swap(OwnAST);
1829
Craig Topper49a27902014-05-22 04:46:25 +00001830 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001831 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001832
1833 if (Persistent && !TrackerAct) {
1834 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001835 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1836 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001837 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001838 if (Clang->hasASTConsumer())
1839 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001840 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1841 *AST, AST->getCurrentTopLevelHashValue()));
1842 Clang->setASTConsumer(
1843 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001844 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001845 if (!Act->Execute()) {
1846 AST->transferASTDataFromCompilerInstance(*Clang);
1847 if (OwnAST && ErrAST)
1848 ErrAST->swap(OwnAST);
1849
Craig Topper49a27902014-05-22 04:46:25 +00001850 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001851 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001852
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001853 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001854 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001855
1856 Act->EndSourceFile();
1857
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001858 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001859 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001860 else
1861 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001862}
1863
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001864bool ASTUnit::LoadFromCompilerInvocation(
1865 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001866 unsigned PrecompilePreambleAfterNParses) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001867 if (!Invocation)
1868 return true;
1869
1870 // We'll manage file buffers ourselves.
1871 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1872 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001873 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001874 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001875
Rafael Espindola32482082014-08-18 16:23:45 +00001876 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001877 if (PrecompilePreambleAfterNParses > 0) {
1878 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001879 OverrideMainBuffer =
1880 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001881 getDiagnostics().Reset();
1882 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001883 }
1884
Douglas Gregor16896c42010-10-28 15:44:59 +00001885 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001886 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001887
Ted Kremenek022a4902011-03-22 01:15:24 +00001888 // Recover resources if we crash before exiting this method.
1889 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001890 MemBufferCleanup(OverrideMainBuffer.get());
1891
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001892 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001893}
1894
David Blaikie103a2de2014-04-25 17:01:33 +00001895std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001896 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001897 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001898 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001899 bool OnlyLocalDecls, bool CaptureDiagnostics,
1900 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1901 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1902 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001903 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001904 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001905 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001906 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001907 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001908 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001909 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001910 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001911 AST->IncludeBriefCommentsInCodeCompletion
1912 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001913 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001914 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1915 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001916 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001917
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001918 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001919 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1920 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001921 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1922 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001923 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001924
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001925 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001926 PrecompilePreambleAfterNParses))
David Blaikie103a2de2014-04-25 17:01:33 +00001927 return nullptr;
1928 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001929}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001930
Ahmed Charlesb8984322014-03-07 20:03:18 +00001931ASTUnit *ASTUnit::LoadFromCommandLine(
1932 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001933 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001934 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1935 bool OnlyLocalDecls, bool CaptureDiagnostics,
1936 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001937 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001938 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1939 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1940 bool UserFilesAreVolatile, bool ForSerialization,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001941 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001942 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001943
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001944 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001945
1946 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001947
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001948 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001949
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001950 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001951 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001952
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001953 CI = clang::createInvocationFromCommandLine(
David Blaikieea4395e2017-01-06 19:49:01 +00001954 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001955 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001956 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001957 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001958
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001959 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001960 for (const auto &RemappedFile : RemappedFiles) {
1961 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1962 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001963 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001964 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1965 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1966 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001967
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001968 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001969 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001970
Erik Verbruggen6e922512012-04-12 10:11:59 +00001971 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1972
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001973 if (ModuleFormat)
1974 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1975
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001976 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001977 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001978 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001979 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001980 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001981 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001982 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1983 createVFSFromCompilerInvocation(*CI, *Diags);
1984 if (!VFS)
1985 return nullptr;
1986 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001987 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001988 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001989 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001990 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001991 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001992 AST->IncludeBriefCommentsInCodeCompletion
1993 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001994 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001995 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001996 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001997 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001998 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001999 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00002000 // Zero out now to ease cleanup during crash recovery.
2001 CI = nullptr;
2002 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00002003
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002004 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002005 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2006 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002007
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002008 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00002009 PrecompilePreambleAfterNParses)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002010 // Some error occurred, if caller wants to examine diagnostics, pass it the
2011 // ASTUnit.
2012 if (ErrAST) {
2013 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2014 ErrAST->swap(AST);
2015 }
Craig Topper49a27902014-05-22 04:46:25 +00002016 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002017 }
2018
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002019 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002020}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002021
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002022bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2023 ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002024 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002025 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002026
2027 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002028
Douglas Gregor16896c42010-10-28 15:44:59 +00002029 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002030 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002031
Douglas Gregor0e119552010-07-31 00:40:00 +00002032 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002033 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002034 for (const auto &RB : PPOpts.RemappedFileBuffers)
2035 delete RB.second;
2036
Douglas Gregor0e119552010-07-31 00:40:00 +00002037 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002038 for (const auto &RemappedFile : RemappedFiles) {
2039 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2040 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002041 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002042
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002043 // If we have a preamble file lying around, or if we might try to
2044 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002045 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002046 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002047 OverrideMainBuffer =
2048 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2049
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002050 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00002051 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002052 getDiagnostics().Reset();
2053 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002054 if (OverrideMainBuffer)
2055 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002056
Douglas Gregor4dde7492010-07-23 23:58:40 +00002057 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002058 bool Result =
2059 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
Rafael Espindola32482082014-08-18 16:23:45 +00002060
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002061 // If we're caching global code-completion results, and the top-level
2062 // declarations have changed, clear out the code-completion cache.
2063 if (!Result && ShouldCacheCodeCompletionResults &&
2064 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2065 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002066
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002067 // We now need to clear out the completion info related to this translation
2068 // unit; it'll be recreated if necessary.
2069 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002070
Douglas Gregor4dde7492010-07-23 23:58:40 +00002071 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002072}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002073
Douglas Gregorb14904c2010-08-13 22:48:40 +00002074//----------------------------------------------------------------------------//
2075// Code completion
2076//----------------------------------------------------------------------------//
2077
2078namespace {
2079 /// \brief Code completion consumer that combines the cached code-completion
2080 /// results from an ASTUnit with the code-completion results provided to it,
2081 /// then passes the result on to
2082 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002083 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002084 ASTUnit &AST;
2085 CodeCompleteConsumer &Next;
2086
2087 public:
2088 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002089 const CodeCompleteOptions &CodeCompleteOpts)
2090 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2091 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002092 {
2093 // Compute the set of contexts in which we will look when we don't have
2094 // any information about the specific context.
2095 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002096 = (1LL << CodeCompletionContext::CCC_TopLevel)
2097 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2098 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2099 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2100 | (1LL << CodeCompletionContext::CCC_Statement)
2101 | (1LL << CodeCompletionContext::CCC_Expression)
2102 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2103 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2104 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2105 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2106 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2107 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2108 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002109
David Blaikiebbafb8a2012-03-11 07:00:24 +00002110 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002111 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2112 | (1LL << CodeCompletionContext::CCC_UnionTag)
2113 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002114 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002115
2116 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2117 CodeCompletionResult *Results,
2118 unsigned NumResults) override;
2119
2120 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2121 OverloadCandidate *Candidates,
2122 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002123 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2124 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002125
2126 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002127 return Next.getAllocator();
2128 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002129
Craig Topperafa7cb32014-03-13 06:07:04 +00002130 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002131 return Next.getCodeCompletionTUInfo();
2132 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002133 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002134} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00002135
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002136/// \brief Helper function that computes which global names are hidden by the
2137/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002138static void CalculateHiddenNames(const CodeCompletionContext &Context,
2139 CodeCompletionResult *Results,
2140 unsigned NumResults,
2141 ASTContext &Ctx,
2142 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002143 bool OnlyTagNames = false;
2144 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002145 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002146 case CodeCompletionContext::CCC_TopLevel:
2147 case CodeCompletionContext::CCC_ObjCInterface:
2148 case CodeCompletionContext::CCC_ObjCImplementation:
2149 case CodeCompletionContext::CCC_ObjCIvarList:
2150 case CodeCompletionContext::CCC_ClassStructUnion:
2151 case CodeCompletionContext::CCC_Statement:
2152 case CodeCompletionContext::CCC_Expression:
2153 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002154 case CodeCompletionContext::CCC_DotMemberAccess:
2155 case CodeCompletionContext::CCC_ArrowMemberAccess:
2156 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002157 case CodeCompletionContext::CCC_Namespace:
2158 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002159 case CodeCompletionContext::CCC_Name:
2160 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002161 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002162 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002163 break;
2164
2165 case CodeCompletionContext::CCC_EnumTag:
2166 case CodeCompletionContext::CCC_UnionTag:
2167 case CodeCompletionContext::CCC_ClassOrStructTag:
2168 OnlyTagNames = true;
2169 break;
2170
2171 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002172 case CodeCompletionContext::CCC_MacroName:
2173 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002174 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002175 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002176 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002177 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002178 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002179 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002180 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002181 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2182 case CodeCompletionContext::CCC_ObjCClassMessage:
2183 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002184 // We're looking for nothing, or we're looking for names that cannot
2185 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002186 return;
2187 }
2188
John McCall276321a2010-08-25 06:19:51 +00002189 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002190 for (unsigned I = 0; I != NumResults; ++I) {
2191 if (Results[I].Kind != Result::RK_Declaration)
2192 continue;
2193
2194 unsigned IDNS
2195 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2196
2197 bool Hiding = false;
2198 if (OnlyTagNames)
2199 Hiding = (IDNS & Decl::IDNS_Tag);
2200 else {
2201 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002202 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2203 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002204 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002205 HiddenIDNS |= Decl::IDNS_Tag;
2206 Hiding = (IDNS & HiddenIDNS);
2207 }
2208
2209 if (!Hiding)
2210 continue;
2211
2212 DeclarationName Name = Results[I].Declaration->getDeclName();
2213 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2214 HiddenNames.insert(Identifier->getName());
2215 else
2216 HiddenNames.insert(Name.getAsString());
2217 }
2218}
2219
Douglas Gregord46cf182010-08-16 20:01:48 +00002220void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2221 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002222 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002223 unsigned NumResults) {
2224 // Merge the results we were given with the results we cached.
2225 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002226 uint64_t InContexts =
2227 Context.getKind() == CodeCompletionContext::CCC_Recovery
2228 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002229 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002230 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002231 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002232 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002233 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002234 C = AST.cached_completion_begin(),
2235 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002236 C != CEnd; ++C) {
2237 // If the context we are in matches any of the contexts we are
2238 // interested in, we'll add this result.
2239 if ((C->ShowInContexts & InContexts) == 0)
2240 continue;
2241
2242 // If we haven't added any results previously, do so now.
2243 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002244 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2245 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002246 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2247 AddedResult = true;
2248 }
2249
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002250 // Determine whether this global completion result is hidden by a local
2251 // completion result. If so, skip it.
2252 if (C->Kind != CXCursor_MacroDefinition &&
2253 HiddenNames.count(C->Completion->getTypedText()))
2254 continue;
2255
Douglas Gregord46cf182010-08-16 20:01:48 +00002256 // Adjust priority based on similar type classes.
2257 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002258 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002259 if (!Context.getPreferredType().isNull()) {
2260 if (C->Kind == CXCursor_MacroDefinition) {
2261 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002262 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002263 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002264 } else if (C->Type) {
2265 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002266 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002267 Context.getPreferredType().getUnqualifiedType());
2268 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2269 if (ExpectedSTC == C->TypeClass) {
2270 // We know this type is similar; check for an exact match.
2271 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002272 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002273 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002274 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002275 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2276 Priority /= CCF_ExactTypeMatch;
2277 else
2278 Priority /= CCF_SimilarTypeMatch;
2279 }
2280 }
2281 }
2282
Douglas Gregor12785102010-08-24 20:21:13 +00002283 // Adjust the completion string, if required.
2284 if (C->Kind == CXCursor_MacroDefinition &&
2285 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2286 // Create a new code-completion string that just contains the
2287 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002288 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2289 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002290 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002291 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002292 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002293 }
2294
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002295 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002296 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002297 }
2298
2299 // If we did not add any cached completion results, just forward the
2300 // results we were given to the next consumer.
2301 if (!AddedResult) {
2302 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2303 return;
2304 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002305
Douglas Gregord46cf182010-08-16 20:01:48 +00002306 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2307 AllResults.size());
2308}
2309
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002310void ASTUnit::CodeComplete(
2311 StringRef File, unsigned Line, unsigned Column,
2312 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2313 bool IncludeCodePatterns, bool IncludeBriefComments,
2314 CodeCompleteConsumer &Consumer,
2315 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2316 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2317 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2318 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002319 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002320 return;
2321
Douglas Gregor16896c42010-10-28 15:44:59 +00002322 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002323 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002324 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002325
David Blaikieea4395e2017-01-06 19:49:01 +00002326 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002327
2328 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002329 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002330 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002331
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002332 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2333 CachedCompletionResults.empty();
2334 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2335 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2336 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2337
2338 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2339
Douglas Gregor8e984da2010-08-04 16:47:14 +00002340 FrontendOpts.CodeCompletionAt.FileName = File;
2341 FrontendOpts.CodeCompletionAt.Line = Line;
2342 FrontendOpts.CodeCompletionAt.Column = Column;
2343
2344 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002345 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002346
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002347 // Spell-checking and warnings are wasteful during code-completion.
2348 LangOpts.SpellChecking = false;
2349 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2350
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002351 std::unique_ptr<CompilerInstance> Clang(
2352 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002353
2354 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002355 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2356 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002357
David Blaikieea4395e2017-01-06 19:49:01 +00002358 auto &Inv = *CCInvocation;
2359 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002360 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002361
2362 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002363 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002364 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002365 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002366 StoredDiagnostics);
David Blaikieea4395e2017-01-06 19:49:01 +00002367 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2368
Douglas Gregor8e984da2010-08-04 16:47:14 +00002369 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002370 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002371 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002372 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002373 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002374 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002375 }
2376
2377 // Inform the target of the language options.
2378 //
2379 // FIXME: We shouldn't need to do this, the target should be immutable once
2380 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002381 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002382
Ted Kremenek84de4a12011-03-21 18:40:07 +00002383 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002384 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002385 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2386 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002387 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002388 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2389 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002390 "IR inputs not support here!");
Douglas Gregor8e984da2010-08-04 16:47:14 +00002391
2392 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002393 Clang->setFileManager(&FileMgr);
2394 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002395
2396 // Remap files.
2397 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002398 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002399 for (const auto &RemappedFile : RemappedFiles) {
2400 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2401 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002402 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002403
Douglas Gregorb14904c2010-08-13 22:48:40 +00002404 // Use the code completion consumer we were given, but adding any cached
2405 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002406 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002407 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002408 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002409
Douglas Gregor028d3e42010-08-09 20:45:32 +00002410 // If we have a precompiled preamble, try to use it. We only allow
2411 // the use of the precompiled preamble if we're if the completion
2412 // point is within the main file, after the end of the precompiled
2413 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002414 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002415 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002416 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002417 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002418
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002419 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002420 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002421 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002422 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002423 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002424 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
David Blaikieea4395e2017-01-06 19:49:01 +00002425 PCHContainerOps, Inv, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002426 }
2427 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002428 }
2429
2430 // If the main file has been overridden due to the use of a preamble,
2431 // make that override happen and introduce the preamble.
2432 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002433 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2434 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002435 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2436 PreprocessorOpts.PrecompiledPreambleBytes.second
2437 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002438 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002439 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002440
2441 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002442 } else {
2443 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2444 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002445 }
2446
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002447 // Disable the preprocessing record if modules are not enabled.
2448 if (!Clang->getLangOpts().Modules)
2449 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002450
2451 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002452 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002453 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002454 Act->Execute();
2455 Act->EndSourceFile();
2456 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002457}
Douglas Gregore9386682010-08-13 05:36:37 +00002458
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002459bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002460 if (HadModuleLoaderFatalFailure)
2461 return true;
2462
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002463 // Write to a temporary file and later rename it to the actual file, to avoid
2464 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002465 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002466 TempPath = File;
2467 TempPath += "-%%%%%%%%";
2468 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002469 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002470 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002471
Douglas Gregore9386682010-08-13 05:36:37 +00002472 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2473 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002474 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002475
2476 serialize(Out);
2477 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002478 if (Out.has_error()) {
2479 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002480 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002481 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002482
Yaron Keren92e1b622015-03-18 10:17:07 +00002483 if (llvm::sys::fs::rename(TempPath, File)) {
2484 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002485 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002486 }
2487
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002488 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002489}
2490
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002491static bool serializeUnit(ASTWriter &Writer,
2492 SmallVectorImpl<char> &Buffer,
2493 Sema &S,
2494 bool hasErrors,
2495 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002496 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002497
2498 // Write the generated bitstream to "Out".
2499 if (!Buffer.empty())
2500 OS.write(Buffer.data(), Buffer.size());
2501
2502 return false;
2503}
2504
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002505bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002506 // For serialization we are lenient if the errors were only warn-as-error kind.
2507 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002508
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002509 if (WriterData)
2510 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2511 getSema(), hasErrors, OS);
2512
Daniel Dunbar9a963862012-02-29 20:31:23 +00002513 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002514 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002515 MemoryBufferCache PCMCache;
2516 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002517 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002518}
Douglas Gregor925296b2011-07-19 16:10:42 +00002519
2520typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2521
Douglas Gregor925296b2011-07-19 16:10:42 +00002522void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002523 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002524 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002525 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002526 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002527 // Map the standalone diagnostic into the new source manager. We also need to
2528 // remap all the locations to the new view. This includes the diag location,
2529 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002530 // FIXME: There should be a cleaner way to do this.
2531
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002532 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002533 Result.reserve(Diags.size());
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002534 const FileEntry *PreviousFE = nullptr;
2535 FileID FID;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002536 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002537 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002538 if (SD.Filename.empty())
2539 continue;
2540 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2541 if (!FE)
2542 continue;
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002543 if (FE != PreviousFE) {
2544 FID = SrcMgr.translateFile(FE);
2545 PreviousFE = FE;
2546 }
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002547 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2548 if (FileLoc.isInvalid())
2549 continue;
2550 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002551 FullSourceLoc Loc(L, SrcMgr);
2552
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002553 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002554 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002555 for (const auto &Range : SD.Ranges) {
2556 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2557 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002558 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002559 }
2560
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002561 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002562 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002563 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002564 FixIts.push_back(FixItHint());
2565 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002566 FH.CodeToInsert = FixIt.CodeToInsert;
2567 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2568 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002569 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002570 }
2571
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002572 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2573 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002574 }
2575 Result.swap(Out);
2576}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002577
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002578void ASTUnit::addFileLevelDecl(Decl *D) {
2579 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002580
2581 // We only care about local declarations.
2582 if (D->isFromASTFile())
2583 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002584
2585 SourceManager &SM = *SourceMgr;
2586 SourceLocation Loc = D->getLocation();
2587 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2588 return;
2589
2590 // We only keep track of the file-level declarations of each file.
2591 if (!D->getLexicalDeclContext()->isFileContext())
2592 return;
2593
2594 SourceLocation FileLoc = SM.getFileLoc(Loc);
2595 assert(SM.isLocalSourceLocation(FileLoc));
2596 FileID FID;
2597 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002598 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002599 if (FID.isInvalid())
2600 return;
2601
2602 LocDeclsTy *&Decls = FileDecls[FID];
2603 if (!Decls)
2604 Decls = new LocDeclsTy();
2605
2606 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2607
2608 if (Decls->empty() || Decls->back().first <= Offset) {
2609 Decls->push_back(LocDecl);
2610 return;
2611 }
2612
Benjamin Kramer45025c02013-08-24 13:22:59 +00002613 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2614 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002615
2616 Decls->insert(I, LocDecl);
2617}
2618
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002619void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2620 SmallVectorImpl<Decl *> &Decls) {
2621 if (File.isInvalid())
2622 return;
2623
2624 if (SourceMgr->isLoadedFileID(File)) {
2625 assert(Ctx->getExternalSource() && "No external source!");
2626 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2627 Decls);
2628 }
2629
2630 FileDeclsTy::iterator I = FileDecls.find(File);
2631 if (I == FileDecls.end())
2632 return;
2633
2634 LocDeclsTy &LocDecls = *I->second;
2635 if (LocDecls.empty())
2636 return;
2637
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002638 LocDeclsTy::iterator BeginIt =
2639 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002640 std::make_pair(Offset, (Decl *)nullptr),
2641 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002642 if (BeginIt != LocDecls.begin())
2643 --BeginIt;
2644
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002645 // If we are pointing at a top-level decl inside an objc container, we need
2646 // to backtrack until we find it otherwise we will fail to report that the
2647 // region overlaps with an objc container.
2648 while (BeginIt != LocDecls.begin() &&
2649 BeginIt->second->isTopLevelDeclInObjCContainer())
2650 --BeginIt;
2651
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002652 LocDeclsTy::iterator EndIt = std::upper_bound(
2653 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002654 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002655 if (EndIt != LocDecls.end())
2656 ++EndIt;
2657
2658 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2659 Decls.push_back(DIt->second);
2660}
2661
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002662SourceLocation ASTUnit::getLocation(const FileEntry *File,
2663 unsigned Line, unsigned Col) const {
2664 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002665 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002666 return SM.getMacroArgExpandedLocation(Loc);
2667}
2668
2669SourceLocation ASTUnit::getLocation(const FileEntry *File,
2670 unsigned Offset) const {
2671 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002672 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002673 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2674}
2675
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002676/// \brief If \arg Loc is a loaded location from the preamble, returns
2677/// the corresponding local location of the main file, otherwise it returns
2678/// \arg Loc.
2679SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2680 FileID PreambleID;
2681 if (SourceMgr)
2682 PreambleID = SourceMgr->getPreambleFileID();
2683
2684 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2685 return Loc;
2686
2687 unsigned Offs;
2688 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2689 SourceLocation FileLoc
2690 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2691 return FileLoc.getLocWithOffset(Offs);
2692 }
2693
2694 return Loc;
2695}
2696
2697/// \brief If \arg Loc is a local location of the main file but inside the
2698/// preamble chunk, returns the corresponding loaded location from the
2699/// preamble, otherwise it returns \arg Loc.
2700SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2701 FileID PreambleID;
2702 if (SourceMgr)
2703 PreambleID = SourceMgr->getPreambleFileID();
2704
2705 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2706 return Loc;
2707
2708 unsigned Offs;
2709 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2710 Offs < Preamble.size()) {
2711 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2712 return FileLoc.getLocWithOffset(Offs);
2713 }
2714
2715 return Loc;
2716}
2717
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002718bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2719 FileID FID;
2720 if (SourceMgr)
2721 FID = SourceMgr->getPreambleFileID();
2722
2723 if (Loc.isInvalid() || FID.isInvalid())
2724 return false;
2725
2726 return SourceMgr->isInFileID(Loc, FID);
2727}
2728
2729bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2730 FileID FID;
2731 if (SourceMgr)
2732 FID = SourceMgr->getMainFileID();
2733
2734 if (Loc.isInvalid() || FID.isInvalid())
2735 return false;
2736
2737 return SourceMgr->isInFileID(Loc, FID);
2738}
2739
2740SourceLocation ASTUnit::getEndOfPreambleFileID() {
2741 FileID FID;
2742 if (SourceMgr)
2743 FID = SourceMgr->getPreambleFileID();
2744
2745 if (FID.isInvalid())
2746 return SourceLocation();
2747
2748 return SourceMgr->getLocForEndOfFile(FID);
2749}
2750
2751SourceLocation ASTUnit::getStartOfMainFileID() {
2752 FileID FID;
2753 if (SourceMgr)
2754 FID = SourceMgr->getMainFileID();
2755
2756 if (FID.isInvalid())
2757 return SourceLocation();
2758
2759 return SourceMgr->getLocForStartOfFile(FID);
2760}
2761
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002762llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002763ASTUnit::getLocalPreprocessingEntities() const {
2764 if (isMainFileAST()) {
2765 serialization::ModuleFile &
2766 Mod = Reader->getModuleManager().getPrimaryModule();
2767 return Reader->getModulePreprocessedEntities(Mod);
2768 }
2769
2770 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002771 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002772
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002773 return llvm::make_range(PreprocessingRecord::iterator(),
2774 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002775}
2776
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002777bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002778 if (isMainFileAST()) {
2779 serialization::ModuleFile &
2780 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002781 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2782 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002783 return false;
2784 }
2785
2786 return true;
2787 }
2788
2789 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2790 TLEnd = top_level_end();
2791 TL != TLEnd; ++TL) {
2792 if (!Fn(context, *TL))
2793 return false;
2794 }
2795
2796 return true;
2797}
2798
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002799const FileEntry *ASTUnit::getPCHFile() {
2800 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002801 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002802
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002803 serialization::ModuleFile *Mod = nullptr;
2804 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2805 switch (M.Kind) {
2806 case serialization::MK_ImplicitModule:
2807 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002808 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002809 return true; // skip dependencies.
2810 case serialization::MK_PCH:
2811 Mod = &M;
2812 return true; // found it.
2813 case serialization::MK_Preamble:
2814 return false; // look in dependencies.
2815 case serialization::MK_MainFile:
2816 return false; // look in dependencies.
2817 }
2818
2819 return true;
2820 });
2821 if (Mod)
2822 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002823
Craig Topper49a27902014-05-22 04:46:25 +00002824 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002825}
2826
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002827bool ASTUnit::isModuleFile() {
Richard Smithbbcc9f02016-08-26 00:14:38 +00002828 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002829}
2830
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002831void ASTUnit::PreambleData::countLines() const {
2832 NumLines = 0;
2833 if (empty())
2834 return;
2835
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002836 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2837
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002838 if (Buffer.back() != '\n')
2839 ++NumLines;
2840}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002841
2842#ifndef NDEBUG
2843ASTUnit::ConcurrencyState::ConcurrencyState() {
2844 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2845}
2846
2847ASTUnit::ConcurrencyState::~ConcurrencyState() {
2848 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2849}
2850
2851void ASTUnit::ConcurrencyState::start() {
2852 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2853 assert(acquired && "Concurrent access to ASTUnit!");
2854}
2855
2856void ASTUnit::ConcurrencyState::finish() {
2857 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2858}
2859
2860#else // NDEBUG
2861
Hans Wennborgdcfba332015-10-06 23:40:43 +00002862ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002863ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002864void ASTUnit::ConcurrencyState::start() {}
2865void ASTUnit::ConcurrencyState::finish() {}
2866
Hans Wennborgdcfba332015-10-06 23:40:43 +00002867#endif // NDEBUG