blob: 9505c0769fedc21ed841a93e22f4c9469ddf7ed0 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
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"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#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>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor16896c42010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000060 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000064 }
65
Chris Lattner0e62c1c2011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000069 }
70
Douglas Gregor16896c42010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
Rafael Espindolabc7d9492013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek06b4f912011-10-27 17:55:18 +000090 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremenekbd307a52011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000107
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 M.erase(AU);
155 }
156}
157
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000168 llvm::sys::fs::remove(TemporaryFiles[I]);
169 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000174 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000193 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000194}
195
Ted Kremenek06b4f912011-10-27 17:55:18 +0000196void ASTUnit::CleanTemporaryFiles() {
197 getOnDiskData(this).CleanTemporaryFiles();
198}
199
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000200void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000201 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000202}
203
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000204/// \brief After failing to build a precompiled preamble (due to
205/// errors in the source that occurs in the preamble), the number of
206/// reparses during which we'll skip even trying to precompile the
207/// preamble.
208const unsigned DefaultPreambleRebuildInterval = 5;
209
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000210/// \brief Tracks the number of ASTUnit objects that are currently active.
211///
212/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000213static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000214
Douglas Gregord03e8232010-04-05 21:10:19 +0000215ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000216 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000217 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000218 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000219 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000220 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000221 NumStoredDiagnosticsFromDriver(0),
Craig Topper49a27902014-05-22 04:46:25 +0000222 PreambleRebuildCounter(0), SavedMainFileBuffer(nullptr),
223 PreambleBuffer(nullptr), NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000224 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000225 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000226 CompletionCacheTopLevelHashValue(0),
227 PreambleTopLevelHashValue(0),
228 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000229 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000230 if (getenv("LIBCLANG_OBJTRACKING"))
231 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000232}
Douglas Gregord03e8232010-04-05 21:10:19 +0000233
Daniel Dunbar764c0822009-12-01 09:51:01 +0000234ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000235 // If we loaded from an AST file, balance out the BeginSourceFile call.
236 if (MainFileIsAST && getDiagnostics().getClient()) {
237 getDiagnostics().getClient()->EndSourceFile();
238 }
239
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000240 clearFileLevelDecls();
241
Ted Kremenek06b4f912011-10-27 17:55:18 +0000242 // Clean up the temporary files and the preamble file.
243 removeOnDiskEntry(this);
244
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000245 // Free the buffers associated with remapped files. We are required to
246 // perform this operation here because we explicitly request that the
247 // compiler instance *not* free these buffers for each invocation of the
248 // parser.
Alp Tokerf994cef2014-07-05 03:08:06 +0000249 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000250 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000251 for (const auto &RB : PPOpts.RemappedFileBuffers)
252 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000253 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000254
255 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000256 delete PreambleBuffer;
257
Douglas Gregor16896c42010-10-28 15:44:59 +0000258 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000259
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000260 if (getenv("LIBCLANG_OBJTRACKING"))
261 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000262}
263
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000264void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
265
Douglas Gregor39982192010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000268static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor39982192010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
Richard Smith697cc9e2012-08-14 03:13:00 +0000278 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
284 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
285 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
286 | (1LL << CodeCompletionContext::CCC_Statement)
287 | (1LL << CodeCompletionContext::CCC_Type)
288 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000306
Douglas Gregor59cab552010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000308 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000310 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000311 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000312 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000313 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000315
Douglas Gregor39982192010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000322 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
323 | (1LL << CodeCompletionContext::CCC_Expression)
324 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
325 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000326 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000329 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor16896c42010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000353 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000354 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000355 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000356 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000357
358 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000359 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
360
Douglas Gregorb14904c2010-08-13 22:48:40 +0000361 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
362 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000363 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000364 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000365 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000366 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000367 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000368 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000369 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000370 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000371 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000372 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000373 CachedResult.Priority = Results[I].Priority;
374 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000375 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000376
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000377 // Keep track of the type of this completion in an ASTContext-agnostic
378 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000379 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000380 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000381 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000382 CachedResult.Type = 0;
383 } else {
384 CanQualType CanUsageType
385 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
386 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
387
388 // Determine whether we have already seen this type. If so, we save
389 // ourselves the work of formatting the type string by using the
390 // temporary, CanQualType-based hash table to find the associated value.
391 unsigned &TypeValue = CompletionTypes[CanUsageType];
392 if (TypeValue == 0) {
393 TypeValue = CompletionTypes.size();
394 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
395 = TypeValue;
396 }
397
398 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000399 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000400
Douglas Gregor39982192010-08-15 06:18:01 +0000401 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000402
403 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000404 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000405 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
406 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000407 uint64_t NNSContexts
408 = (1LL << CodeCompletionContext::CCC_TopLevel)
409 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
410 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
411 | (1LL << CodeCompletionContext::CCC_Statement)
412 | (1LL << CodeCompletionContext::CCC_Expression)
413 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
414 | (1LL << CodeCompletionContext::CCC_EnumTag)
415 | (1LL << CodeCompletionContext::CCC_UnionTag)
416 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
417 | (1LL << CodeCompletionContext::CCC_Type)
418 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
419 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000420
421 if (isa<NamespaceDecl>(Results[I].Declaration) ||
422 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000423 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000424
425 if (unsigned RemainingContexts
426 = NNSContexts & ~CachedResult.ShowInContexts) {
427 // If there any contexts where this completion can be a
428 // nested-name-specifier but isn't already an option, create a
429 // nested-name-specifier completion.
430 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000431 CachedResult.Completion
432 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000433 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000434 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000435 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000436 CachedResult.ShowInContexts = RemainingContexts;
437 CachedResult.Priority = CCP_NestedNameSpecifier;
438 CachedResult.TypeClass = STC_Void;
439 CachedResult.Type = 0;
440 CachedCompletionResults.push_back(CachedResult);
441 }
442 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000444 }
445
Douglas Gregorb14904c2010-08-13 22:48:40 +0000446 case Result::RK_Keyword:
447 case Result::RK_Pattern:
448 // Ignore keywords and patterns; we don't care, since they are so
449 // easily regenerated.
450 break;
451
452 case Result::RK_Macro: {
453 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000454 CachedResult.Completion
455 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000456 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000457 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000458 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000459 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000460 = (1LL << CodeCompletionContext::CCC_TopLevel)
461 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
462 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
463 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
464 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
465 | (1LL << CodeCompletionContext::CCC_Statement)
466 | (1LL << CodeCompletionContext::CCC_Expression)
467 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
468 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
469 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
470 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
471 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000472
Douglas Gregorb14904c2010-08-13 22:48:40 +0000473 CachedResult.Priority = Results[I].Priority;
474 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000475 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000476 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000477 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478 CachedCompletionResults.push_back(CachedResult);
479 break;
480 }
481 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000483
484 // Save the current top-level hash value.
485 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000486}
487
488void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000489 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000490 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000491 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000492}
493
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494namespace {
495
Sebastian Redl2c499f62010-08-18 23:56:43 +0000496/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000498class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000499 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000500 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000501 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000502 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000503 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000504 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregore8bbc122011-09-02 00:18:52 +0000506 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000507public:
Alp Toker80758082014-07-06 05:26:44 +0000508 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
509 std::shared_ptr<TargetOptions> &TargetOpts,
510 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
511 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
512 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000513
Craig Topperafa7cb32014-03-13 06:07:04 +0000514 bool ReadLanguageOptions(const LangOptions &LangOpts,
515 bool Complain) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000516 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000517 return false;
518
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000519 LangOpt = LangOpts;
520 InitializedLanguage = true;
521
522 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000523 return false;
524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Craig Topperafa7cb32014-03-13 06:07:04 +0000526 bool ReadTargetOptions(const TargetOptions &TargetOpts,
527 bool Complain) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000528 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000529 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000530 return false;
Alp Toker80758082014-07-06 05:26:44 +0000531
532 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
533 Target =
534 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000535
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000536 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000537 return false;
538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Craig Topperafa7cb32014-03-13 06:07:04 +0000540 void ReadCounter(const serialization::ModuleFile &M,
541 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000542 Counter = Value;
543 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000544
545private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000546 void updated() {
547 if (!Target || !InitializedLanguage)
548 return;
549
550 // Inform the target of the language options.
551 //
552 // FIXME: We shouldn't need to do this, the target should be immutable once
553 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000554 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000555
556 // Initialize the preprocessor.
557 PP.Initialize(*Target);
558
559 // Initialize the ASTContext
560 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000561
562 // We didn't have access to the comment options when the ASTContext was
563 // constructed, so register them now.
564 Context.getCommentCommandTraits().registerCommentOptions(
565 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000566 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000567};
568
Douglas Gregor6b930962013-05-03 22:58:43 +0000569 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000570class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000571 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000572 SourceManager *SourceMgr;
573
Douglas Gregor33cdd812010-02-18 18:08:43 +0000574public:
David Blaikief18d91a2011-09-26 00:01:39 +0000575 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000576 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000577 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000578
Craig Topperafa7cb32014-03-13 06:07:04 +0000579 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000580 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000581 if (PP)
582 SourceMgr = &PP->getSourceManager();
583 }
584
Craig Topperafa7cb32014-03-13 06:07:04 +0000585 void HandleDiagnostic(DiagnosticsEngine::Level Level,
586 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000587};
588
589/// \brief RAII object that optionally captures diagnostics, if
590/// there is no diagnostic client to capture them already.
591class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000592 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000593 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000594 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595
596public:
David Blaikie9c902b52011-09-25 23:23:43 +0000597 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000598 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000599 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000600 {
Craig Topper49a27902014-05-22 04:46:25 +0000601 if (RequestCapture || Diags.getClient() == nullptr) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000602 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000604 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000605 }
606
607 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000608 if (Diags.getClient() == &Client) {
609 Diags.takeClient();
610 Diags.setClient(PreviousClient);
611 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000612 }
613};
614
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000615} // anonymous namespace
616
David Blaikief18d91a2011-09-26 00:01:39 +0000617void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000618 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000619 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000620 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000621
Douglas Gregor6b930962013-05-03 22:58:43 +0000622 // Only record the diagnostic if it's part of the source manager we know
623 // about. This effectively drops diagnostics from modules we're building.
624 // FIXME: In the long run, ee don't want to drop source managers from modules.
625 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
626 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000627}
628
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000629ASTMutationListener *ASTUnit::getASTMutationListener() {
630 if (WriterData)
631 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000632 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000633}
634
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000635ASTDeserializationListener *ASTUnit::getDeserializationListener() {
636 if (WriterData)
637 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000638 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000639}
640
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000641llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000642 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000643 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000644 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000645}
646
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000647/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000648void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000649 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000650 ASTUnit &AST, bool CaptureDiagnostics) {
Alp Tokerf994cef2014-07-05 03:08:06 +0000651 if (!Diags.get()) {
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000652 // No diagnostics engine was provided, so create our own diagnostics object
653 // with the default options.
Craig Topper49a27902014-05-22 04:46:25 +0000654 DiagnosticConsumer *Client = nullptr;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000655 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000656 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000657 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000658 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000659 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000660 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000661 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000662 }
663}
664
David Blaikie6f7382d2014-08-10 19:08:04 +0000665std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
666 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
667 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
668 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
669 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000670 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000671
672 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000673 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
674 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000675 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
676 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000677 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000678
Craig Topper49a27902014-05-22 04:46:25 +0000679 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000680
Douglas Gregor16bef852009-10-16 20:01:17 +0000681 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000682 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000683 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000684 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
685 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000686 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000687 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000688 AST->getFileManager(),
689 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000690 AST->HSOpts = new HeaderSearchOptions();
Craig Topper49a27902014-05-22 04:46:25 +0000691
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000692 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000693 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000694 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000695 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000696 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000697
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000698 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000699
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000700 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
701 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000702
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000703 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000704
David Blaikie6f7382d2014-08-10 19:08:04 +0000705 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000706 unsigned Counter;
707
Alp Toker96637802014-05-02 03:43:38 +0000708 AST->PP =
709 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
710 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000711 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000712 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 Preprocessor &PP = *AST->PP;
714
Alp Toker08043432014-05-03 03:46:04 +0000715 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
716 PP.getIdentifierTable(), PP.getSelectorTable(),
717 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000718 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000719
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000720 bool disableValid = false;
721 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
722 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000723 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000724 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000725 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000726 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000727
David Blaikie2721c322014-08-10 16:54:39 +0000728 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
729 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
730 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000731
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000732 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000733 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000734 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000735 break;
Mike Stump11289f42009-09-09 15:08:12 +0000736
Sebastian Redl2c499f62010-08-18 23:56:43 +0000737 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000738 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000739 case ASTReader::OutOfDate:
740 case ASTReader::VersionMismatch:
741 case ASTReader::ConfigurationMismatch:
742 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000743 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000744 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000745 }
Mike Stump11289f42009-09-09 15:08:12 +0000746
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000747 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000748
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000749 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Sebastian Redl2c499f62010-08-18 23:56:43 +0000751 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000752 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000753 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000754 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000755
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000756 // Create an AST consumer, even though it isn't used.
757 AST->Consumer.reset(new ASTConsumer);
758
Sebastian Redl2c499f62010-08-18 23:56:43 +0000759 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000760 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
761 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000762 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000763
Douglas Gregor6b930962013-05-03 22:58:43 +0000764 // Tell the diagnostic client that we have started a source file.
765 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
766
David Blaikie6f7382d2014-08-10 19:08:04 +0000767 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000768}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000769
770namespace {
771
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000772/// \brief Preprocessor callback class that updates a hash value with the names
773/// of all macros that have been defined by the translation unit.
774class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
775 unsigned &Hash;
776
777public:
778 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000779
780 void MacroDefined(const Token &MacroNameTok,
781 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000782 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
783 }
784};
785
786/// \brief Add the given declaration to the hash of all top-level entities.
787void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
788 if (!D)
789 return;
790
791 DeclContext *DC = D->getDeclContext();
792 if (!DC)
793 return;
794
795 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
796 return;
797
798 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000799 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
800 // For an unscoped enum include the enumerators in the hash since they
801 // enter the top-level namespace.
802 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000803 for (const auto *EI : EnumD->enumerators()) {
804 if (EI->getIdentifier())
805 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000806 }
807 }
808 }
809
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000810 if (ND->getIdentifier())
811 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
812 else if (DeclarationName Name = ND->getDeclName()) {
813 std::string NameStr = Name.getAsString();
814 Hash = llvm::HashString(NameStr, Hash);
815 }
816 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000817 }
818
819 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
820 if (Module *Mod = ImportD->getImportedModule()) {
821 std::string ModName = Mod->getFullModuleName();
822 Hash = llvm::HashString(ModName, Hash);
823 }
824 return;
825 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000826}
827
Daniel Dunbar644dca02009-12-04 08:17:33 +0000828class TopLevelDeclTrackerConsumer : public ASTConsumer {
829 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000830 unsigned &Hash;
831
Daniel Dunbar644dca02009-12-04 08:17:33 +0000832public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000833 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
834 : Unit(_Unit), Hash(Hash) {
835 Hash = 0;
836 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000837
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000838 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000839 if (!D)
840 return;
841
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000842 // FIXME: Currently ObjC method declarations are incorrectly being
843 // reported as top-level declarations, even though their DeclContext
844 // is the containing ObjC @interface/@implementation. This is a
845 // fundamental problem in the parser right now.
846 if (isa<ObjCMethodDecl>(D))
847 return;
848
849 AddTopLevelDeclarationToHash(D, Hash);
850 Unit.addTopLevelDecl(D);
851
852 handleFileLevelDecl(D);
853 }
854
855 void handleFileLevelDecl(Decl *D) {
856 Unit.addFileLevelDecl(D);
857 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000858 for (auto *I : NSD->decls())
859 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000860 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000861 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000862
Craig Topperafa7cb32014-03-13 06:07:04 +0000863 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000864 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
865 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000866 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000867 }
868
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000869 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000870 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000871
Craig Topperafa7cb32014-03-13 06:07:04 +0000872 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000873 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
874 handleTopLevelDecl(*it);
875 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000876
Craig Topperafa7cb32014-03-13 06:07:04 +0000877 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000878 return Unit.getASTMutationListener();
879 }
880
Craig Topperafa7cb32014-03-13 06:07:04 +0000881 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000882 return Unit.getDeserializationListener();
883 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000884};
885
886class TopLevelDeclTrackerAction : public ASTFrontendAction {
887public:
888 ASTUnit &Unit;
889
David Blaikie62a56f32014-07-17 22:34:12 +0000890 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
891 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000892 CI.getPreprocessor().addPPCallbacks(
893 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
David Blaikie62a56f32014-07-17 22:34:12 +0000894 return new TopLevelDeclTrackerConsumer(Unit,
895 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000896 }
897
898public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000899 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
900
Craig Topperafa7cb32014-03-13 06:07:04 +0000901 bool hasCodeCompletionSupport() const override { return false; }
902 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000903 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000904 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000905};
906
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000907class PrecompilePreambleAction : public ASTFrontendAction {
908 ASTUnit &Unit;
909 bool HasEmittedPreamblePCH;
910
911public:
912 explicit PrecompilePreambleAction(ASTUnit &Unit)
913 : Unit(Unit), HasEmittedPreamblePCH(false) {}
914
David Blaikie62a56f32014-07-17 22:34:12 +0000915 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
916 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000917 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
918 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000919 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000920
Craig Topperafa7cb32014-03-13 06:07:04 +0000921 bool hasCodeCompletionSupport() const override { return false; }
922 bool hasASTFileSupport() const override { return false; }
923 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000924};
925
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000926class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000927 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000928 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000929 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000930 PrecompilePreambleAction *Action;
931
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000932public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000933 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
934 const Preprocessor &PP, StringRef isysroot,
935 raw_ostream *Out)
Craig Topper49a27902014-05-22 04:46:25 +0000936 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000937 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000938 Hash = 0;
939 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000940
Craig Topperafa7cb32014-03-13 06:07:04 +0000941 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000942 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
943 Decl *D = *it;
944 // FIXME: Currently ObjC method declarations are incorrectly being
945 // reported as top-level declarations, even though their DeclContext
946 // is the containing ObjC @interface/@implementation. This is a
947 // fundamental problem in the parser right now.
948 if (isa<ObjCMethodDecl>(D))
949 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000950 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000951 TopLevelDecls.push_back(D);
952 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000953 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000954 }
955
Craig Topperafa7cb32014-03-13 06:07:04 +0000956 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000957 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000958 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000959 // Translate the top-level declarations we captured during
960 // parsing into declaration IDs in the precompiled
961 // preamble. This will allow us to deserialize those top-level
962 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000963 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
964 Decl *D = TopLevelDecls[I];
965 // Invalid top-level decls may not have been serialized.
966 if (D->isInvalidDecl())
967 continue;
968 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
969 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000970
971 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000972 }
973 }
974};
975
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000976}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000977
David Blaikie62a56f32014-07-17 22:34:12 +0000978ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
979 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000980 std::string Sysroot;
981 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000982 raw_ostream *OS = nullptr;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000983 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
984 OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000985 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000986
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000987 if (!CI.getFrontendOpts().RelocatablePCH)
988 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000989
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000990 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
991 Unit.getCurrentTopLevelHashValue()));
David Blaikie62a56f32014-07-17 22:34:12 +0000992 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
993 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000994}
995
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000996static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
997 return StoredDiag.getLocation().isValid();
998}
999
1000static void
1001checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001002 // Get rid of stored diagnostics except the ones from the driver which do not
1003 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001004 StoredDiags.erase(
1005 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1006 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001007}
1008
1009static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1010 StoredDiagnostics,
1011 SourceManager &SM) {
1012 // The stored diagnostic has the old source manager in it; update
1013 // the locations to refer into the new source manager. Since we've
1014 // been careful to make sure that the source manager's state
1015 // before and after are identical, so that we can reuse the source
1016 // location itself.
1017 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1018 if (StoredDiagnostics[I].getLocation().isValid()) {
1019 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1020 StoredDiagnostics[I].setLocation(Loc);
1021 }
1022 }
1023}
1024
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001025/// Parse the source file into a translation unit using the given compiler
1026/// invocation, replacing the current translation unit.
1027///
1028/// \returns True if a failure occurred that causes the ASTUnit not to
1029/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001030bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001031 delete SavedMainFileBuffer;
Craig Topper49a27902014-05-22 04:46:25 +00001032 SavedMainFileBuffer = nullptr;
1033
Ted Kremenek5e14d392011-03-21 18:40:17 +00001034 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001035 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001036 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001037 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001038
Daniel Dunbar764c0822009-12-01 09:51:01 +00001039 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001040 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001041
1042 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001043 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1044 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001045
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001046 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001047 CCInvocation(new CompilerInvocation(*Invocation));
1048
Alp Tokerf994cef2014-07-05 03:08:06 +00001049 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001050 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001051
Douglas Gregor8e984da2010-08-04 16:47:14 +00001052 // Set up diagnostics, capturing any diagnostics that would
1053 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001054 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001055
Daniel Dunbar764c0822009-12-01 09:51:01 +00001056 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001057 Clang->setTarget(TargetInfo::CreateTargetInfo(
1058 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001059 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001060 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001061 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001062 }
1063
Daniel Dunbar764c0822009-12-01 09:51:01 +00001064 // Inform the target of the language options.
1065 //
1066 // FIXME: We shouldn't need to do this, the target should be immutable once
1067 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001068 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001069
Ted Kremenek84de4a12011-03-21 18:40:07 +00001070 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001071 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001072 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001073 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001074 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001075 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001076
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001077 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001078 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001079 FileSystemOpts = Clang->getFileSystemOpts();
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001080 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1081 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1082 if (!VFS) {
1083 delete OverrideMainBuffer;
1084 return true;
1085 }
1086 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001087 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1088 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001089 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001090 Ctx = nullptr;
1091 PP = nullptr;
1092 Reader = nullptr;
1093
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001094 // Clear out old caches and data.
1095 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001096 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001097 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001098
Douglas Gregor7b02b582010-08-20 00:02:33 +00001099 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001100 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001101 TopLevelDeclsInPreamble.clear();
1102 }
1103
Daniel Dunbar764c0822009-12-01 09:51:01 +00001104 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001105 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001106
Daniel Dunbar764c0822009-12-01 09:51:01 +00001107 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001108 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001109
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001110 // If the main file has been overridden due to the use of a preamble,
1111 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001112 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001113 if (OverrideMainBuffer) {
1114 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1115 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1116 PreprocessorOpts.PrecompiledPreambleBytes.second
1117 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001118 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001119 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001120
Douglas Gregord9a30af2010-08-02 20:51:39 +00001121 // The stored diagnostic has the old source manager in it; update
1122 // the locations to refer into the new source manager. Since we've
1123 // been careful to make sure that the source manager's state
1124 // before and after are identical, so that we can reuse the source
1125 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001126 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001127
1128 // Keep track of the override buffer;
1129 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001130 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001131
1132 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1133 new TopLevelDeclTrackerAction(*this));
1134
Ted Kremenek022a4902011-03-22 01:15:24 +00001135 // Recover resources if we crash before exiting this method.
1136 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1137 ActCleanup(Act.get());
1138
Douglas Gregor32fbe312012-01-20 16:28:04 +00001139 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001140 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001141
1142 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001143 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001144 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1145 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001146 }
1147
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001148 if (!Act->Execute())
1149 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001150
1151 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001152
Daniel Dunbar644dca02009-12-04 08:17:33 +00001153 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001154
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001155 FailedParseDiagnostics.clear();
1156
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001157 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001158
Daniel Dunbar764c0822009-12-01 09:51:01 +00001159error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001160 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001161 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001162 delete OverrideMainBuffer;
Craig Topper49a27902014-05-22 04:46:25 +00001163 SavedMainFileBuffer = nullptr;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001164 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001165
1166 // Keep the ownership of the data in the ASTUnit because the client may
1167 // want to see the diagnostics.
1168 transferASTDataFromCompilerInstance(*Clang);
1169 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001170 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001171 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001172 return true;
1173}
1174
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001175/// \brief Simple function to retrieve a path for a preamble precompiled header.
1176static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001177 // FIXME: This is a hack so that we can override the preamble file during
1178 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001179 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001180 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1181 if (TmpFile)
1182 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001183
1184 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001185 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001186
1187 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001188}
1189
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001190/// \brief Compute the preamble for the main file, providing the source buffer
1191/// that corresponds to the main file along with a pair (bytes, start-of-line)
1192/// that describes the preamble.
1193std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001194ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1195 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001196 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001197 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001198 CreatedBuffer = false;
1199
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001200 // Try to determine if the main file has been remapped, either from the
1201 // command line (to another file) or directly through the compiler invocation
1202 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001203 llvm::MemoryBuffer *Buffer = nullptr;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001204 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001205 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001206 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001208 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1209 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001210 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001211 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001212 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001213 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001214 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001215 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001216 CreatedBuffer = false;
1217 }
Alp Toker1b070d22014-07-07 07:47:20 +00001218
1219 Buffer = getBufferForFile(RF.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001220 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001221 return std::make_pair(nullptr, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001222 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001223 }
1224 }
1225 }
1226
1227 // Check whether there is a file-buffer remapping. It supercedes the
1228 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001229 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1230 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001231 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001232 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001233 if (MainFileID == MID) {
1234 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001235 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001237 CreatedBuffer = false;
1238 }
Alp Toker1b070d22014-07-07 07:47:20 +00001239
1240 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001241 }
1242 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001243 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001244 }
1245
1246 // If the main source file was not remapped, load it now.
1247 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001248 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001249 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001250 return std::make_pair(nullptr, std::make_pair(0, true));
1251
Douglas Gregor4dde7492010-07-23 23:58:40 +00001252 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001253 }
1254
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001255 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001256 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001257 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001258}
1259
Dmitri Gribenko47652522013-12-20 00:16:25 +00001260ASTUnit::PreambleFileHash
1261ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1262 PreambleFileHash Result;
1263 Result.Size = Size;
1264 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001265 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001266 return Result;
1267}
1268
1269ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1270 const llvm::MemoryBuffer *Buffer) {
1271 PreambleFileHash Result;
1272 Result.Size = Buffer->getBufferSize();
1273 Result.ModTime = 0;
1274
1275 llvm::MD5 MD5Ctx;
1276 MD5Ctx.update(Buffer->getBuffer().data());
1277 MD5Ctx.final(Result.MD5);
1278
1279 return Result;
1280}
1281
1282namespace clang {
1283bool operator==(const ASTUnit::PreambleFileHash &LHS,
1284 const ASTUnit::PreambleFileHash &RHS) {
1285 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001286 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001287}
1288} // namespace clang
1289
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001290static std::pair<unsigned, unsigned>
1291makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1292 const LangOptions &LangOpts) {
1293 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1294 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1295 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1296 return std::make_pair(Offset, EndOffset);
1297}
1298
1299static void makeStandaloneFixIt(const SourceManager &SM,
1300 const LangOptions &LangOpts,
1301 const FixItHint &InFix,
1302 ASTUnit::StandaloneFixIt &OutFix) {
1303 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1304 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1305 LangOpts);
1306 OutFix.CodeToInsert = InFix.CodeToInsert;
1307 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1308}
1309
1310static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1311 const StoredDiagnostic &InDiag,
1312 ASTUnit::StandaloneDiagnostic &OutDiag) {
1313 OutDiag.ID = InDiag.getID();
1314 OutDiag.Level = InDiag.getLevel();
1315 OutDiag.Message = InDiag.getMessage();
1316 OutDiag.LocOffset = 0;
1317 if (InDiag.getLocation().isInvalid())
1318 return;
1319 const SourceManager &SM = InDiag.getLocation().getManager();
1320 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1321 OutDiag.Filename = SM.getFilename(FileLoc);
1322 if (OutDiag.Filename.empty())
1323 return;
1324 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1325 for (StoredDiagnostic::range_iterator
1326 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1327 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1328 }
1329 for (StoredDiagnostic::fixit_iterator
1330 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1331 ASTUnit::StandaloneFixIt Fix;
1332 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1333 OutDiag.FixIts.push_back(Fix);
1334 }
1335}
1336
Douglas Gregor4dde7492010-07-23 23:58:40 +00001337/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1338/// the source file.
1339///
1340/// This routine will compute the preamble of the main source file. If a
1341/// non-trivial preamble is found, it will precompile that preamble into a
1342/// precompiled header so that the precompiled preamble can be used to reduce
1343/// reparsing time. If a precompiled preamble has already been constructed,
1344/// this routine will determine if it is still valid and, if so, avoid
1345/// rebuilding the precompiled preamble.
1346///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001347/// \param AllowRebuild When true (the default), this routine is
1348/// allowed to rebuild the precompiled preamble if it is found to be
1349/// out-of-date.
1350///
1351/// \param MaxLines When non-zero, the maximum number of lines that
1352/// can occur within the preamble.
1353///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001354/// \returns If the precompiled preamble can be used, returns a newly-allocated
1355/// buffer that should be used in place of the main file when doing so.
1356/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001357llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001358 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001359 bool AllowRebuild,
1360 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001361
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001362 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001363 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1364 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001365 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001366 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001367
1368 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001369 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001370 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001371
Douglas Gregor925296b2011-07-19 16:10:42 +00001372 // If ComputePreamble() Take ownership of the preamble buffer.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001373 std::unique_ptr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001374 if (CreatedPreambleBuffer)
1375 OwnedPreambleBuffer.reset(NewPreamble.first);
1376
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001377 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001378 // We couldn't find a preamble in the main source. Clear out the current
1379 // preamble, if we have one. It's obviously no good any more.
1380 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001381 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001382
1383 // The next time we actually see a preamble, precompile it.
1384 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001385 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001386 }
1387
1388 if (!Preamble.empty()) {
1389 // We've previously computed a preamble. Check whether we have the same
1390 // preamble now that we did before, and that there's enough space in
1391 // the main-file buffer within the precompiled preamble to fit the
1392 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001393 if (Preamble.size() == NewPreamble.second.first &&
1394 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001395 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001396 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001397 // The preamble has not changed. We may be able to re-use the precompiled
1398 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001399
Douglas Gregor0e119552010-07-31 00:40:00 +00001400 // Check that none of the files used by the preamble have changed.
1401 bool AnyFileChanged = false;
1402
1403 // First, make a record of those files that have been overridden via
1404 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001405 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001406 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1407 if (AnyFileChanged)
1408 break;
1409
Ben Langmuirc8130a72014-02-20 21:59:23 +00001410 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001411 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001412 // If we can't stat the file we're remapping to, assume that something
1413 // horrible happened.
1414 AnyFileChanged = true;
1415 break;
1416 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001417
Alp Toker1b070d22014-07-07 07:47:20 +00001418 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001419 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001420 }
Alp Toker1b070d22014-07-07 07:47:20 +00001421
1422 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1423 if (AnyFileChanged)
1424 break;
1425 OverriddenFiles[RB.first] =
1426 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001427 }
1428
1429 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001430 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001431 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1432 !AnyFileChanged && F != FEnd;
1433 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001434 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001435 = OverriddenFiles.find(F->first());
1436 if (Overridden != OverriddenFiles.end()) {
1437 // This file was remapped; check whether the newly-mapped file
1438 // matches up with the previous mapping.
1439 if (Overridden->second != F->second)
1440 AnyFileChanged = true;
1441 continue;
1442 }
1443
1444 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001445 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001446 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001447 // If we can't stat the file, assume that something horrible happened.
1448 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001449 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001450 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001451 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001452 AnyFileChanged = true;
1453 }
1454
1455 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001456 // Okay! We can re-use the precompiled preamble.
1457
1458 // Set the state of the diagnostic object to mimic its state
1459 // after parsing the preamble.
1460 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001461 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001462 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001463 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001464
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001465 return llvm::MemoryBuffer::getMemBufferCopy(
1466 NewPreamble.first->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001467 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001468 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001469
1470 // If we aren't allowed to rebuild the precompiled preamble, just
1471 // return now.
1472 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001473 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001474
Douglas Gregor4dde7492010-07-23 23:58:40 +00001475 // We can't reuse the previously-computed preamble. Build a new one.
1476 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001477 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001478 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001479 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001480 } else if (!AllowRebuild) {
1481 // We aren't allowed to rebuild the precompiled preamble; just
1482 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001483 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001484 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001485
1486 // If the preamble rebuild counter > 1, it's because we previously
1487 // failed to build a preamble and we're not yet ready to try
1488 // again. Decrement the counter and return a failure.
1489 if (PreambleRebuildCounter > 1) {
1490 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001491 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001492 }
1493
Douglas Gregore10f0e52010-09-11 17:56:52 +00001494 // Create a temporary file for the precompiled preamble. In rare
1495 // circumstances, this can fail.
1496 std::string PreamblePCHPath = GetPreamblePCHPath();
1497 if (PreamblePCHPath.empty()) {
1498 // Try again next time.
1499 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001500 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001501 }
1502
Douglas Gregor4dde7492010-07-23 23:58:40 +00001503 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001504 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001505 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001506
Douglas Gregord9a30af2010-08-02 20:51:39 +00001507 // Save the preamble text for later; we'll need to compare against it for
1508 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001509 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001510 Preamble.assign(FileMgr->getFile(MainFilename),
1511 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001512 NewPreamble.first->getBufferStart()
1513 + NewPreamble.second.first);
1514 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1515
Douglas Gregora0734c52010-08-19 01:33:06 +00001516 delete PreambleBuffer;
1517 PreambleBuffer
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001518 = llvm::MemoryBuffer::getMemBufferCopy(
1519 NewPreamble.first->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001520
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001521 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001522 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1523 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1524
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001525 // Tell the compiler invocation to generate a temporary precompiled header.
1526 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001527 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001528 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001529 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1530 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001531
1532 // Create the compiler instance to use for building the precompiled preamble.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001533 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001534
1535 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001536 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1537 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001538
Douglas Gregor3cc15812011-07-01 18:22:13 +00001539 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001540 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001541
Douglas Gregor8e984da2010-08-04 16:47:14 +00001542 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001543 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001544
1545 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001546 Clang->setTarget(TargetInfo::CreateTargetInfo(
1547 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001548 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001549 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001550 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001551 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001552 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001553 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554 }
1555
1556 // Inform the target of the language options.
1557 //
1558 // FIXME: We shouldn't need to do this, the target should be immutable once
1559 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001560 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001561
Ted Kremenek84de4a12011-03-21 18:40:07 +00001562 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001563 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001564 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001565 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001566 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001567 "IR inputs not support here!");
1568
1569 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001570 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001571 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001572 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001573 TopLevelDecls.clear();
1574 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001575 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001576
1577 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1578 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1579 if (!VFS)
1580 return nullptr;
1581
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001582 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001583 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001584
1585 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001586 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001587 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001588
Ben Langmuir33c80902014-06-30 20:04:14 +00001589 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1590 Clang->addDependencyCollector(PreambleDepCollector);
1591
Ahmed Charlesb8984322014-03-07 20:03:18 +00001592 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001593 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001594 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001595 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001596 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001597 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001598 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001599 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001600 }
1601
1602 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001603
1604 // Transfer any diagnostics generated when parsing the preamble into the set
1605 // of preamble diagnostics.
1606 for (stored_diag_iterator
1607 I = stored_diag_afterDriver_begin(),
1608 E = stored_diag_end(); I != E; ++I) {
1609 StandaloneDiagnostic Diag;
1610 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1611 PreambleDiagnostics.push_back(Diag);
1612 }
1613
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001614 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001615
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001616 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1617
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001618 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001619 // The preamble PCH failed (e.g. there was a module loading fatal error),
1620 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001621 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001622 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001623 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001624 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001625 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001626 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001627 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001628 }
1629
1630 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001631 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001632 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001633
1634 // Keep track of all of the files that the source manager knows about,
1635 // so we can verify whether they have changed or not.
1636 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001637 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001638 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1639 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1640 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001641 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001642 if (time_t ModTime = File->getModificationTime()) {
1643 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001644 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001645 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001646 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001647 FilesInPreamble[File->getName()] =
1648 PreambleFileHash::createForMemoryBuffer(Buffer);
1649 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001650 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001651
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001652 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001653 PreprocessorOpts.RemappedFileBuffers.pop_back();
1654
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001655 // If the hash of top-level entities differs from the hash of the top-level
1656 // entities the last time we rebuilt the preamble, clear out the completion
1657 // cache.
1658 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1659 CompletionCacheTopLevelHashValue = 0;
1660 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1661 }
1662
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001663 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.first->getBuffer(),
1664 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001665}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001666
Douglas Gregore9db88f2010-08-03 19:06:41 +00001667void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1668 std::vector<Decl *> Resolved;
1669 Resolved.reserve(TopLevelDeclsInPreamble.size());
1670 ExternalASTSource &Source = *getASTContext().getExternalSource();
1671 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1672 // Resolve the declaration ID to an actual declaration, possibly
1673 // deserializing the declaration in the process.
1674 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1675 if (D)
1676 Resolved.push_back(D);
1677 }
1678 TopLevelDeclsInPreamble.clear();
1679 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1680}
1681
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001682void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001683 // Steal the created target, context, and preprocessor if they have been
1684 // created.
1685 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001686 LangOpts = CI.getInvocation().LangOpts;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001687 TheSema.reset(CI.takeSema());
David Blaikie62a56f32014-07-17 22:34:12 +00001688 Consumer.reset(CI.takeASTConsumer());
Ben Langmuir532fdc02014-04-18 20:39:48 +00001689 if (CI.hasASTContext())
1690 Ctx = &CI.getASTContext();
1691 if (CI.hasPreprocessor())
1692 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001693 CI.setSourceManager(nullptr);
1694 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001695 if (CI.hasTarget())
1696 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001697 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001698 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001699}
1700
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001701StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001702 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1703 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1704 if (Input.isFile())
1705 return Input.getFile();
1706 else
1707 return Input.getBuffer()->getBufferIdentifier();
1708 }
1709
1710 if (SourceMgr) {
1711 if (const FileEntry *
1712 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1713 return FE->getName();
1714 }
1715
1716 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001717}
1718
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001719StringRef ASTUnit::getASTFileName() const {
1720 if (!isMainFileAST())
1721 return StringRef();
1722
1723 serialization::ModuleFile &
1724 Mod = Reader->getModuleManager().getPrimaryModule();
1725 return Mod.FileName;
1726}
1727
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001728ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001729 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001730 bool CaptureDiagnostics,
1731 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001732 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001733 AST.reset(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001734 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001735 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001736 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001737 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001738 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1739 createVFSFromCompilerInvocation(*CI, *Diags);
1740 if (!VFS)
1741 return nullptr;
1742 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001743 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1744 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1745 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001746
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001747 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001748}
1749
Ahmed Charlesb8984322014-03-07 20:03:18 +00001750ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1751 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1752 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1753 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1754 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1755 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1756 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001757 assert(CI && "A CompilerInvocation is required");
1758
Ahmed Charlesb8984322014-03-07 20:03:18 +00001759 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001760 ASTUnit *AST = Unit;
1761 if (!AST) {
1762 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001763 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001764 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001765 if (!AST)
1766 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001767 }
1768
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001769 if (!ResourceFilesPath.empty()) {
1770 // Override the resources path.
1771 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1772 }
1773 AST->OnlyLocalDecls = OnlyLocalDecls;
1774 AST->CaptureDiagnostics = CaptureDiagnostics;
1775 if (PrecompilePreamble)
1776 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001777 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001778 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001779 AST->IncludeBriefCommentsInCodeCompletion
1780 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001781
1782 // Recover resources if we crash before exiting this method.
1783 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001784 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001785 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1786 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001787 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001788
1789 // We'll manage file buffers ourselves.
1790 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1791 CI->getFrontendOpts().DisableFree = false;
1792 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1793
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001794 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001795 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001796
1797 // Recover resources if we crash before exiting this method.
1798 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1799 CICleanup(Clang.get());
1800
1801 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001802 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001803
1804 // Set up diagnostics, capturing any diagnostics that would
1805 // otherwise be dropped.
1806 Clang->setDiagnostics(&AST->getDiagnostics());
1807
1808 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001809 Clang->setTarget(TargetInfo::CreateTargetInfo(
1810 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001811 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001812 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001813
1814 // Inform the target of the language options.
1815 //
1816 // FIXME: We shouldn't need to do this, the target should be immutable once
1817 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001818 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001819
1820 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1821 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001822 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001823 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001824 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001825 "IR inputs not supported here!");
1826
1827 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001828 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001829 AST->Ctx = nullptr;
1830 AST->PP = nullptr;
1831 AST->Reader = nullptr;
1832
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001833 // Create a file manager object to provide access to and cache the filesystem.
1834 Clang->setFileManager(&AST->getFileManager());
1835
1836 // Create the source manager.
1837 Clang->setSourceManager(&AST->getSourceManager());
1838
1839 ASTFrontendAction *Act = Action;
1840
Ahmed Charlesb8984322014-03-07 20:03:18 +00001841 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001842 if (!Act) {
1843 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1844 Act = TrackerAct.get();
1845 }
1846
1847 // Recover resources if we crash before exiting this method.
1848 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1849 ActCleanup(TrackerAct.get());
1850
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001851 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1852 AST->transferASTDataFromCompilerInstance(*Clang);
1853 if (OwnAST && ErrAST)
1854 ErrAST->swap(OwnAST);
1855
Craig Topper49a27902014-05-22 04:46:25 +00001856 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001857 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001858
1859 if (Persistent && !TrackerAct) {
1860 Clang->getPreprocessor().addPPCallbacks(
1861 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
David Blaikie62a56f32014-07-17 22:34:12 +00001862 std::vector<ASTConsumer*> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001863 if (Clang->hasASTConsumer())
1864 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie62a56f32014-07-17 22:34:12 +00001865 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1866 AST->getCurrentTopLevelHashValue()));
1867 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001868 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001869 if (!Act->Execute()) {
1870 AST->transferASTDataFromCompilerInstance(*Clang);
1871 if (OwnAST && ErrAST)
1872 ErrAST->swap(OwnAST);
1873
Craig Topper49a27902014-05-22 04:46:25 +00001874 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001875 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001876
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001877 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001878 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001879
1880 Act->EndSourceFile();
1881
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001882 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001883 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001884 else
1885 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001886}
1887
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001888bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1889 if (!Invocation)
1890 return true;
1891
1892 // We'll manage file buffers ourselves.
1893 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1894 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001895 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001896
Craig Topper49a27902014-05-22 04:46:25 +00001897 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001898 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001899 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001900 OverrideMainBuffer
1901 = getMainBufferWithPrecompiledPreamble(*Invocation);
1902 }
1903
Douglas Gregor16896c42010-10-28 15:44:59 +00001904 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001905 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001906
Ted Kremenek022a4902011-03-22 01:15:24 +00001907 // Recover resources if we crash before exiting this method.
1908 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1909 MemBufferCleanup(OverrideMainBuffer);
1910
Douglas Gregor16896c42010-10-28 15:44:59 +00001911 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001912}
1913
David Blaikie103a2de2014-04-25 17:01:33 +00001914std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1915 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1916 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1917 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1918 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001919 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001920 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001921 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001922 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001923 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001924 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001925 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001926 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001927 AST->IncludeBriefCommentsInCodeCompletion
1928 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001929 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001930 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001931 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1932 createVFSFromCompilerInvocation(*CI, *Diags);
1933 if (!VFS)
1934 return nullptr;
1935 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001936 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001937
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001938 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001939 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1940 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001941 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1942 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001943 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001944
David Blaikie103a2de2014-04-25 17:01:33 +00001945 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1946 return nullptr;
1947 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001948}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001949
Ahmed Charlesb8984322014-03-07 20:03:18 +00001950ASTUnit *ASTUnit::LoadFromCommandLine(
1951 const char **ArgBegin, const char **ArgEnd,
1952 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1953 bool OnlyLocalDecls, bool CaptureDiagnostics,
1954 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1955 bool PrecompilePreamble, TranslationUnitKind TUKind,
1956 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1957 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1958 bool UserFilesAreVolatile, bool ForSerialization,
1959 std::unique_ptr<ASTUnit> *ErrAST) {
Alp Tokerf994cef2014-07-05 03:08:06 +00001960 if (!Diags.get()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001961 // No diagnostics engine was provided, so create our own diagnostics object
1962 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00001963 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00001964 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001965
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001966 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001967
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001968 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001969
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001970 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001971
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001972 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001973 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001974
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001975 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001976 llvm::makeArrayRef(ArgBegin, ArgEnd),
1977 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001978 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001979 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001980 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001981
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001982 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001983 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001984 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1985 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001986 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001987 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1988 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1989 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001990
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001991 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001992 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001993
Erik Verbruggen6e922512012-04-12 10:11:59 +00001994 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1995
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001996 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001997 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001998 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001999 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002000 AST->Diagnostics = Diags;
Craig Topper49a27902014-05-22 04:46:25 +00002001 Diags = nullptr; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002002 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00002003 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2004 createVFSFromCompilerInvocation(*CI, *Diags);
2005 if (!VFS)
2006 return nullptr;
2007 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002008 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002009 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002010 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002011 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002012 AST->IncludeBriefCommentsInCodeCompletion
2013 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002014 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002015 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002016 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002017 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002018 if (ForSerialization)
2019 AST->WriterData.reset(new ASTWriterData());
Craig Topper49a27902014-05-22 04:46:25 +00002020 CI = nullptr; // Zero out now to ease cleanup during crash recovery.
2021
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002022 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002023 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2024 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002025
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002026 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2027 // Some error occurred, if caller wants to examine diagnostics, pass it the
2028 // ASTUnit.
2029 if (ErrAST) {
2030 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2031 ErrAST->swap(AST);
2032 }
Craig Topper49a27902014-05-22 04:46:25 +00002033 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002034 }
2035
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002036 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002037}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002038
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002039bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002040 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002041 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002042
2043 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002044
Douglas Gregor16896c42010-10-28 15:44:59 +00002045 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002046 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002047
Douglas Gregor0e119552010-07-31 00:40:00 +00002048 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002049 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002050 for (const auto &RB : PPOpts.RemappedFileBuffers)
2051 delete RB.second;
2052
Douglas Gregor0e119552010-07-31 00:40:00 +00002053 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002054 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002055 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2056 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002057 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002058
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002059 // If we have a preamble file lying around, or if we might try to
2060 // build a precompiled preamble, do so now.
Craig Topper49a27902014-05-22 04:46:25 +00002061 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002062 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002063 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002064
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002065 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002066 getDiagnostics().Reset();
2067 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002068 if (OverrideMainBuffer)
2069 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002070
Douglas Gregor4dde7492010-07-23 23:58:40 +00002071 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002072 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002073
2074 // If we're caching global code-completion results, and the top-level
2075 // declarations have changed, clear out the code-completion cache.
2076 if (!Result && ShouldCacheCodeCompletionResults &&
2077 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2078 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002079
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002080 // We now need to clear out the completion info related to this translation
2081 // unit; it'll be recreated if necessary.
2082 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002083
Douglas Gregor4dde7492010-07-23 23:58:40 +00002084 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002085}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002086
Douglas Gregorb14904c2010-08-13 22:48:40 +00002087//----------------------------------------------------------------------------//
2088// Code completion
2089//----------------------------------------------------------------------------//
2090
2091namespace {
2092 /// \brief Code completion consumer that combines the cached code-completion
2093 /// results from an ASTUnit with the code-completion results provided to it,
2094 /// then passes the result on to
2095 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002096 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002097 ASTUnit &AST;
2098 CodeCompleteConsumer &Next;
2099
2100 public:
2101 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002102 const CodeCompleteOptions &CodeCompleteOpts)
2103 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2104 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002105 {
2106 // Compute the set of contexts in which we will look when we don't have
2107 // any information about the specific context.
2108 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002109 = (1LL << CodeCompletionContext::CCC_TopLevel)
2110 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2111 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2112 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2113 | (1LL << CodeCompletionContext::CCC_Statement)
2114 | (1LL << CodeCompletionContext::CCC_Expression)
2115 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2116 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2117 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2118 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2119 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2120 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2121 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002122
David Blaikiebbafb8a2012-03-11 07:00:24 +00002123 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002124 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2125 | (1LL << CodeCompletionContext::CCC_UnionTag)
2126 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002127 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002128
2129 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2130 CodeCompletionResult *Results,
2131 unsigned NumResults) override;
2132
2133 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2134 OverloadCandidate *Candidates,
2135 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002136 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2137 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002138
2139 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002140 return Next.getAllocator();
2141 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002142
Craig Topperafa7cb32014-03-13 06:07:04 +00002143 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002144 return Next.getCodeCompletionTUInfo();
2145 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002146 };
2147}
Douglas Gregord46cf182010-08-16 20:01:48 +00002148
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002149/// \brief Helper function that computes which global names are hidden by the
2150/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002151static void CalculateHiddenNames(const CodeCompletionContext &Context,
2152 CodeCompletionResult *Results,
2153 unsigned NumResults,
2154 ASTContext &Ctx,
2155 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002156 bool OnlyTagNames = false;
2157 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002158 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002159 case CodeCompletionContext::CCC_TopLevel:
2160 case CodeCompletionContext::CCC_ObjCInterface:
2161 case CodeCompletionContext::CCC_ObjCImplementation:
2162 case CodeCompletionContext::CCC_ObjCIvarList:
2163 case CodeCompletionContext::CCC_ClassStructUnion:
2164 case CodeCompletionContext::CCC_Statement:
2165 case CodeCompletionContext::CCC_Expression:
2166 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002167 case CodeCompletionContext::CCC_DotMemberAccess:
2168 case CodeCompletionContext::CCC_ArrowMemberAccess:
2169 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002170 case CodeCompletionContext::CCC_Namespace:
2171 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002172 case CodeCompletionContext::CCC_Name:
2173 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002174 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002175 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002176 break;
2177
2178 case CodeCompletionContext::CCC_EnumTag:
2179 case CodeCompletionContext::CCC_UnionTag:
2180 case CodeCompletionContext::CCC_ClassOrStructTag:
2181 OnlyTagNames = true;
2182 break;
2183
2184 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002185 case CodeCompletionContext::CCC_MacroName:
2186 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002187 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002188 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002189 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002190 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002191 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002192 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002193 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002194 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2195 case CodeCompletionContext::CCC_ObjCClassMessage:
2196 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002197 // We're looking for nothing, or we're looking for names that cannot
2198 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002199 return;
2200 }
2201
John McCall276321a2010-08-25 06:19:51 +00002202 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002203 for (unsigned I = 0; I != NumResults; ++I) {
2204 if (Results[I].Kind != Result::RK_Declaration)
2205 continue;
2206
2207 unsigned IDNS
2208 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2209
2210 bool Hiding = false;
2211 if (OnlyTagNames)
2212 Hiding = (IDNS & Decl::IDNS_Tag);
2213 else {
2214 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002215 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2216 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002217 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002218 HiddenIDNS |= Decl::IDNS_Tag;
2219 Hiding = (IDNS & HiddenIDNS);
2220 }
2221
2222 if (!Hiding)
2223 continue;
2224
2225 DeclarationName Name = Results[I].Declaration->getDeclName();
2226 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2227 HiddenNames.insert(Identifier->getName());
2228 else
2229 HiddenNames.insert(Name.getAsString());
2230 }
2231}
2232
2233
Douglas Gregord46cf182010-08-16 20:01:48 +00002234void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2235 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002236 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002237 unsigned NumResults) {
2238 // Merge the results we were given with the results we cached.
2239 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002240 uint64_t InContexts =
2241 Context.getKind() == CodeCompletionContext::CCC_Recovery
2242 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002243 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002244 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002245 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002247 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002248 C = AST.cached_completion_begin(),
2249 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002250 C != CEnd; ++C) {
2251 // If the context we are in matches any of the contexts we are
2252 // interested in, we'll add this result.
2253 if ((C->ShowInContexts & InContexts) == 0)
2254 continue;
2255
2256 // If we haven't added any results previously, do so now.
2257 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002258 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2259 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002260 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2261 AddedResult = true;
2262 }
2263
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002264 // Determine whether this global completion result is hidden by a local
2265 // completion result. If so, skip it.
2266 if (C->Kind != CXCursor_MacroDefinition &&
2267 HiddenNames.count(C->Completion->getTypedText()))
2268 continue;
2269
Douglas Gregord46cf182010-08-16 20:01:48 +00002270 // Adjust priority based on similar type classes.
2271 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002272 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002273 if (!Context.getPreferredType().isNull()) {
2274 if (C->Kind == CXCursor_MacroDefinition) {
2275 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002276 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002277 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002278 } else if (C->Type) {
2279 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002280 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002281 Context.getPreferredType().getUnqualifiedType());
2282 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2283 if (ExpectedSTC == C->TypeClass) {
2284 // We know this type is similar; check for an exact match.
2285 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002286 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002287 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002288 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002289 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2290 Priority /= CCF_ExactTypeMatch;
2291 else
2292 Priority /= CCF_SimilarTypeMatch;
2293 }
2294 }
2295 }
2296
Douglas Gregor12785102010-08-24 20:21:13 +00002297 // Adjust the completion string, if required.
2298 if (C->Kind == CXCursor_MacroDefinition &&
2299 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2300 // Create a new code-completion string that just contains the
2301 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002302 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2303 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002304 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002305 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002306 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002307 }
2308
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002309 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002310 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002311 }
2312
2313 // If we did not add any cached completion results, just forward the
2314 // results we were given to the next consumer.
2315 if (!AddedResult) {
2316 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2317 return;
2318 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002319
Douglas Gregord46cf182010-08-16 20:01:48 +00002320 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2321 AllResults.size());
2322}
2323
2324
2325
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002326void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002327 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002328 bool IncludeMacros,
2329 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002330 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002331 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002332 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002333 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002334 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2335 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002336 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002337 return;
2338
Douglas Gregor16896c42010-10-28 15:44:59 +00002339 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002340 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002341 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002342
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002343 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002344 CCInvocation(new CompilerInvocation(*Invocation));
2345
2346 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002347 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002348 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002349
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002350 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2351 CachedCompletionResults.empty();
2352 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2353 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2354 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2355
2356 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2357
Douglas Gregor8e984da2010-08-04 16:47:14 +00002358 FrontendOpts.CodeCompletionAt.FileName = File;
2359 FrontendOpts.CodeCompletionAt.Line = Line;
2360 FrontendOpts.CodeCompletionAt.Column = Column;
2361
2362 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002363 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002364
Ahmed Charlesb8984322014-03-07 20:03:18 +00002365 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002366
2367 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002368 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2369 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002370
Ted Kremenek5e14d392011-03-21 18:40:17 +00002371 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002372 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002373
2374 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002375 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002376 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002377 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002378 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002379 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002380
2381 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002382 Clang->setTarget(TargetInfo::CreateTargetInfo(
2383 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002384 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002385 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002386 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002387 }
2388
2389 // Inform the target of the language options.
2390 //
2391 // FIXME: We shouldn't need to do this, the target should be immutable once
2392 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002393 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002394
Ted Kremenek84de4a12011-03-21 18:40:07 +00002395 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002396 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002397 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002398 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002399 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002400 "IR inputs not support here!");
2401
2402
2403 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002404 Clang->setFileManager(&FileMgr);
2405 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002406
2407 // Remap files.
2408 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002409 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002410 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002411 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2412 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002413 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002414 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002415
Douglas Gregorb14904c2010-08-13 22:48:40 +00002416 // Use the code completion consumer we were given, but adding any cached
2417 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002418 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002419 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002420 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002421
Douglas Gregor028d3e42010-08-09 20:45:32 +00002422 // If we have a precompiled preamble, try to use it. We only allow
2423 // the use of the precompiled preamble if we're if the completion
2424 // point is within the main file, after the end of the precompiled
2425 // preamble.
Craig Topper49a27902014-05-22 04:46:25 +00002426 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002427 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002428 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002429 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002430
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002431 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002432 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002433 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002434 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002435 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002436 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002437 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002438 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002439 }
2440 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002441 }
2442
2443 // If the main file has been overridden due to the use of a preamble,
2444 // make that override happen and introduce the preamble.
2445 if (OverrideMainBuffer) {
2446 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2447 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2448 PreprocessorOpts.PrecompiledPreambleBytes.second
2449 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002450 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002451 PreprocessorOpts.DisablePCHValidation = true;
2452
Douglas Gregorb97b6662010-08-20 00:59:43 +00002453 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002454 } else {
2455 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2456 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002457 }
2458
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002459 // Disable the preprocessing record if modules are not enabled.
2460 if (!Clang->getLangOpts().Modules)
2461 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002462
2463 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002464 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002465 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002466 Act->Execute();
2467 Act->EndSourceFile();
2468 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002469}
Douglas Gregore9386682010-08-13 05:36:37 +00002470
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002471bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002472 if (HadModuleLoaderFatalFailure)
2473 return true;
2474
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002475 // Write to a temporary file and later rename it to the actual file, to avoid
2476 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002477 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002478 TempPath = File;
2479 TempPath += "-%%%%%%%%";
2480 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002481 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002482 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002483
Douglas Gregore9386682010-08-13 05:36:37 +00002484 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2485 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002486 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002487
2488 serialize(Out);
2489 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002490 if (Out.has_error()) {
2491 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002492 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002493 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002494
Rafael Espindola65e025c2011-12-25 01:18:52 +00002495 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002496 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002497 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002498 }
2499
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002500 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002501}
2502
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002503static bool serializeUnit(ASTWriter &Writer,
2504 SmallVectorImpl<char> &Buffer,
2505 Sema &S,
2506 bool hasErrors,
2507 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002508 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002509
2510 // Write the generated bitstream to "Out".
2511 if (!Buffer.empty())
2512 OS.write(Buffer.data(), Buffer.size());
2513
2514 return false;
2515}
2516
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002517bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002518 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002519
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002520 if (WriterData)
2521 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2522 getSema(), hasErrors, OS);
2523
Daniel Dunbar9a963862012-02-29 20:31:23 +00002524 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002525 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002526 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002527 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002528}
Douglas Gregor925296b2011-07-19 16:10:42 +00002529
2530typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2531
Douglas Gregor925296b2011-07-19 16:10:42 +00002532void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002533 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002534 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002535 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002536 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002537 // Map the standalone diagnostic into the new source manager. We also need to
2538 // remap all the locations to the new view. This includes the diag location,
2539 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002540 // FIXME: There should be a cleaner way to do this.
2541
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002542 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002543 Result.reserve(Diags.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00002544 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2545 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002546 const StandaloneDiagnostic &SD = Diags[I];
2547 if (SD.Filename.empty())
2548 continue;
2549 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2550 if (!FE)
2551 continue;
2552 FileID FID = SrcMgr.translateFile(FE);
2553 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2554 if (FileLoc.isInvalid())
2555 continue;
2556 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002557 FullSourceLoc Loc(L, SrcMgr);
2558
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002559 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002560 Ranges.reserve(SD.Ranges.size());
2561 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2562 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2563 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2564 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2565 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002566 }
2567
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002568 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002569 FixIts.reserve(SD.FixIts.size());
2570 for (std::vector<StandaloneFixIt>::const_iterator
2571 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregor925296b2011-07-19 16:10:42 +00002572 I != E; ++I) {
2573 FixIts.push_back(FixItHint());
2574 FixItHint &FH = FixIts.back();
2575 FH.CodeToInsert = I->CodeToInsert;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002576 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2577 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2578 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002579 }
2580
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002581 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2582 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002583 }
2584 Result.swap(Out);
2585}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002586
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002587void ASTUnit::addFileLevelDecl(Decl *D) {
2588 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002589
2590 // We only care about local declarations.
2591 if (D->isFromASTFile())
2592 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002593
2594 SourceManager &SM = *SourceMgr;
2595 SourceLocation Loc = D->getLocation();
2596 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2597 return;
2598
2599 // We only keep track of the file-level declarations of each file.
2600 if (!D->getLexicalDeclContext()->isFileContext())
2601 return;
2602
2603 SourceLocation FileLoc = SM.getFileLoc(Loc);
2604 assert(SM.isLocalSourceLocation(FileLoc));
2605 FileID FID;
2606 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002607 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002608 if (FID.isInvalid())
2609 return;
2610
2611 LocDeclsTy *&Decls = FileDecls[FID];
2612 if (!Decls)
2613 Decls = new LocDeclsTy();
2614
2615 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2616
2617 if (Decls->empty() || Decls->back().first <= Offset) {
2618 Decls->push_back(LocDecl);
2619 return;
2620 }
2621
Benjamin Kramer45025c02013-08-24 13:22:59 +00002622 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2623 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002624
2625 Decls->insert(I, LocDecl);
2626}
2627
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002628void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2629 SmallVectorImpl<Decl *> &Decls) {
2630 if (File.isInvalid())
2631 return;
2632
2633 if (SourceMgr->isLoadedFileID(File)) {
2634 assert(Ctx->getExternalSource() && "No external source!");
2635 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2636 Decls);
2637 }
2638
2639 FileDeclsTy::iterator I = FileDecls.find(File);
2640 if (I == FileDecls.end())
2641 return;
2642
2643 LocDeclsTy &LocDecls = *I->second;
2644 if (LocDecls.empty())
2645 return;
2646
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002647 LocDeclsTy::iterator BeginIt =
2648 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002649 std::make_pair(Offset, (Decl *)nullptr),
2650 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002651 if (BeginIt != LocDecls.begin())
2652 --BeginIt;
2653
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002654 // If we are pointing at a top-level decl inside an objc container, we need
2655 // to backtrack until we find it otherwise we will fail to report that the
2656 // region overlaps with an objc container.
2657 while (BeginIt != LocDecls.begin() &&
2658 BeginIt->second->isTopLevelDeclInObjCContainer())
2659 --BeginIt;
2660
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002661 LocDeclsTy::iterator EndIt = std::upper_bound(
2662 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002663 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002664 if (EndIt != LocDecls.end())
2665 ++EndIt;
2666
2667 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2668 Decls.push_back(DIt->second);
2669}
2670
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002671SourceLocation ASTUnit::getLocation(const FileEntry *File,
2672 unsigned Line, unsigned Col) const {
2673 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002674 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002675 return SM.getMacroArgExpandedLocation(Loc);
2676}
2677
2678SourceLocation ASTUnit::getLocation(const FileEntry *File,
2679 unsigned Offset) const {
2680 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002681 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002682 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2683}
2684
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002685/// \brief If \arg Loc is a loaded location from the preamble, returns
2686/// the corresponding local location of the main file, otherwise it returns
2687/// \arg Loc.
2688SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2689 FileID PreambleID;
2690 if (SourceMgr)
2691 PreambleID = SourceMgr->getPreambleFileID();
2692
2693 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2694 return Loc;
2695
2696 unsigned Offs;
2697 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2698 SourceLocation FileLoc
2699 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2700 return FileLoc.getLocWithOffset(Offs);
2701 }
2702
2703 return Loc;
2704}
2705
2706/// \brief If \arg Loc is a local location of the main file but inside the
2707/// preamble chunk, returns the corresponding loaded location from the
2708/// preamble, otherwise it returns \arg Loc.
2709SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2710 FileID PreambleID;
2711 if (SourceMgr)
2712 PreambleID = SourceMgr->getPreambleFileID();
2713
2714 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2715 return Loc;
2716
2717 unsigned Offs;
2718 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2719 Offs < Preamble.size()) {
2720 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2721 return FileLoc.getLocWithOffset(Offs);
2722 }
2723
2724 return Loc;
2725}
2726
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002727bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2728 FileID FID;
2729 if (SourceMgr)
2730 FID = SourceMgr->getPreambleFileID();
2731
2732 if (Loc.isInvalid() || FID.isInvalid())
2733 return false;
2734
2735 return SourceMgr->isInFileID(Loc, FID);
2736}
2737
2738bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2739 FileID FID;
2740 if (SourceMgr)
2741 FID = SourceMgr->getMainFileID();
2742
2743 if (Loc.isInvalid() || FID.isInvalid())
2744 return false;
2745
2746 return SourceMgr->isInFileID(Loc, FID);
2747}
2748
2749SourceLocation ASTUnit::getEndOfPreambleFileID() {
2750 FileID FID;
2751 if (SourceMgr)
2752 FID = SourceMgr->getPreambleFileID();
2753
2754 if (FID.isInvalid())
2755 return SourceLocation();
2756
2757 return SourceMgr->getLocForEndOfFile(FID);
2758}
2759
2760SourceLocation ASTUnit::getStartOfMainFileID() {
2761 FileID FID;
2762 if (SourceMgr)
2763 FID = SourceMgr->getMainFileID();
2764
2765 if (FID.isInvalid())
2766 return SourceLocation();
2767
2768 return SourceMgr->getLocForStartOfFile(FID);
2769}
2770
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002771std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2772ASTUnit::getLocalPreprocessingEntities() const {
2773 if (isMainFileAST()) {
2774 serialization::ModuleFile &
2775 Mod = Reader->getModuleManager().getPrimaryModule();
2776 return Reader->getModulePreprocessedEntities(Mod);
2777 }
2778
2779 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2780 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2781
2782 return std::make_pair(PreprocessingRecord::iterator(),
2783 PreprocessingRecord::iterator());
2784}
2785
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002786bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002787 if (isMainFileAST()) {
2788 serialization::ModuleFile &
2789 Mod = Reader->getModuleManager().getPrimaryModule();
2790 ASTReader::ModuleDeclIterator MDI, MDE;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002791 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002792 for (; MDI != MDE; ++MDI) {
2793 if (!Fn(context, *MDI))
2794 return false;
2795 }
2796
2797 return true;
2798 }
2799
2800 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2801 TLEnd = top_level_end();
2802 TL != TLEnd; ++TL) {
2803 if (!Fn(context, *TL))
2804 return false;
2805 }
2806
2807 return true;
2808}
2809
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002810namespace {
2811struct PCHLocatorInfo {
2812 serialization::ModuleFile *Mod;
Craig Topper49a27902014-05-22 04:46:25 +00002813 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002814};
2815}
2816
2817static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2818 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2819 switch (M.Kind) {
2820 case serialization::MK_Module:
2821 return true; // skip dependencies.
2822 case serialization::MK_PCH:
2823 Info.Mod = &M;
2824 return true; // found it.
2825 case serialization::MK_Preamble:
2826 return false; // look in dependencies.
2827 case serialization::MK_MainFile:
2828 return false; // look in dependencies.
2829 }
2830
2831 return true;
2832}
2833
2834const FileEntry *ASTUnit::getPCHFile() {
2835 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002836 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002837
2838 PCHLocatorInfo Info;
2839 Reader->getModuleManager().visit(PCHLocator, &Info);
2840 if (Info.Mod)
2841 return Info.Mod->File;
2842
Craig Topper49a27902014-05-22 04:46:25 +00002843 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002844}
2845
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002846bool ASTUnit::isModuleFile() {
2847 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2848}
2849
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002850void ASTUnit::PreambleData::countLines() const {
2851 NumLines = 0;
2852 if (empty())
2853 return;
2854
2855 for (std::vector<char>::const_iterator
2856 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2857 if (*I == '\n')
2858 ++NumLines;
2859 }
2860 if (Buffer.back() != '\n')
2861 ++NumLines;
2862}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002863
2864#ifndef NDEBUG
2865ASTUnit::ConcurrencyState::ConcurrencyState() {
2866 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2867}
2868
2869ASTUnit::ConcurrencyState::~ConcurrencyState() {
2870 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2871}
2872
2873void ASTUnit::ConcurrencyState::start() {
2874 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2875 assert(acquired && "Concurrent access to ASTUnit!");
2876}
2877
2878void ASTUnit::ConcurrencyState::finish() {
2879 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2880}
2881
2882#else // NDEBUG
2883
Alp Tokerb159c132013-11-22 07:49:39 +00002884ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002885ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2886void ASTUnit::ConcurrencyState::start() {}
2887void ASTUnit::ConcurrencyState::finish() {}
2888
2889#endif