blob: f57a4bc01a4c1d36f94a940180be153c0fad065c [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"
Daniel Dunbar764c0822009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000032#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Serialization/ASTReader.h"
34#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000035#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000036#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000037#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000038#include "llvm/Support/Atomic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000040#include "llvm/Support/FileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/Path.h"
46#include "llvm/Support/Timer.h"
47#include "llvm/Support/raw_ostream.h"
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
Douglas Gregor0e119552010-07-31 00:40:00 +000050#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000082
83 struct OnDiskData {
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
86
Rafael Espindolabc7d9492013-06-26 03:52:38 +000087 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000088 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000089 SmallVector<std::string, 4> TemporaryFiles;
90
Ted Kremenek06b4f912011-10-27 17:55:18 +000091 /// \brief Erase temporary files.
92 void CleanTemporaryFiles();
93
94 /// \brief Erase the preamble file.
95 void CleanPreambleFile();
96
97 /// \brief Erase temporary files and the preamble file.
98 void Cleanup();
99 };
100}
101
Ted Kremenekbd307a52011-10-27 19:44:25 +0000102static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
103 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
104 return M;
105}
106
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000108
109typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
110static OnDiskDataMap &getOnDiskDataMap() {
111 static OnDiskDataMap M;
112 static bool hasRegisteredAtExit = false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit = true;
115 atexit(cleanupOnDiskMapAtExit);
116 }
117 return M;
118}
119
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000123 OnDiskDataMap &M = getOnDiskDataMap();
124 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
127 I->second->Cleanup();
128 }
129}
130
131static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000132 // We require the mutex since we are modifying the structure of the
133 // DenseMap.
134 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000135 OnDiskDataMap &M = getOnDiskDataMap();
136 OnDiskData *&D = M[AU];
137 if (!D)
138 D = new OnDiskData();
139 return *D;
140}
141
142static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
144}
145
146static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000147 // We require the mutex since we are modifying the structure of the
148 // DenseMap.
149 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
152 if (I != M.end()) {
153 I->second->Cleanup();
154 delete I->second;
155 M.erase(AU);
156 }
157}
158
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000159static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000160 getOnDiskData(AU).PreambleFile = preambleFile;
161}
162
163static const std::string &getPreambleFile(const ASTUnit *AU) {
164 return getOnDiskData(AU).PreambleFile;
165}
166
167void OnDiskData::CleanTemporaryFiles() {
168 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000169 llvm::sys::fs::remove(TemporaryFiles[I]);
170 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000171}
172
173void OnDiskData::CleanPreambleFile() {
174 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000175 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000176 PreambleFile.clear();
177 }
178}
179
180void OnDiskData::Cleanup() {
181 CleanTemporaryFiles();
182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000185struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
188 ASTWriter Writer;
189
190 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
191};
192
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000193void ASTUnit::clearFileLevelDecls() {
194 for (FileDeclsTy::iterator
195 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
196 delete I->second;
197 FileDecls.clear();
198}
199
Ted Kremenek06b4f912011-10-27 17:55:18 +0000200void ASTUnit::CleanTemporaryFiles() {
201 getOnDiskData(this).CleanTemporaryFiles();
202}
203
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000204void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000205 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000206}
207
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000208/// \brief After failing to build a precompiled preamble (due to
209/// errors in the source that occurs in the preamble), the number of
210/// reparses during which we'll skip even trying to precompile the
211/// preamble.
212const unsigned DefaultPreambleRebuildInterval = 5;
213
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000214/// \brief Tracks the number of ASTUnit objects that are currently active.
215///
216/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000217static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000218
Douglas Gregord03e8232010-04-05 21:10:19 +0000219ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000220 : Reader(0), HadModuleLoaderFatalFailure(false),
221 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000222 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000223 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000224 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000225 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000226 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis85b4a372011-11-29 18:18:33 +0000227 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000228 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000229 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000230 CompletionCacheTopLevelHashValue(0),
231 PreambleTopLevelHashValue(0),
232 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000233 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000234 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000235 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Reid Klecknerc50b4bf2014-02-03 22:20:24 +0000236 fprintf(stderr, "+++ %d translation units\n", (int)ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000237 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000238}
Douglas Gregord03e8232010-04-05 21:10:19 +0000239
Daniel Dunbar764c0822009-12-01 09:51:01 +0000240ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000241 // If we loaded from an AST file, balance out the BeginSourceFile call.
242 if (MainFileIsAST && getDiagnostics().getClient()) {
243 getDiagnostics().getClient()->EndSourceFile();
244 }
245
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000246 clearFileLevelDecls();
247
Ted Kremenek06b4f912011-10-27 17:55:18 +0000248 // Clean up the temporary files and the preamble file.
249 removeOnDiskEntry(this);
250
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000251 // Free the buffers associated with remapped files. We are required to
252 // perform this operation here because we explicitly request that the
253 // compiler instance *not* free these buffers for each invocation of the
254 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000255 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000256 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
257 for (PreprocessorOptions::remapped_file_buffer_iterator
258 FB = PPOpts.remapped_file_buffer_begin(),
259 FBEnd = PPOpts.remapped_file_buffer_end();
260 FB != FBEnd;
261 ++FB)
262 delete FB->second;
263 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000264
265 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000266 delete PreambleBuffer;
267
Douglas Gregor16896c42010-10-28 15:44:59 +0000268 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000269
270 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000271 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Reid Klecknerc50b4bf2014-02-03 22:20:24 +0000272 fprintf(stderr, "--- %d translation units\n", (int)ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000273 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000274}
275
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000276void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
277
Douglas Gregor39982192010-08-15 06:18:01 +0000278/// \brief Determine the set of code-completion contexts in which this
279/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000280static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000281 const LangOptions &LangOpts,
282 bool &IsNestedNameSpecifier) {
283 IsNestedNameSpecifier = false;
284
Douglas Gregor39982192010-08-15 06:18:01 +0000285 if (isa<UsingShadowDecl>(ND))
286 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
287 if (!ND)
288 return 0;
289
Richard Smith697cc9e2012-08-14 03:13:00 +0000290 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000291 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
292 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
293 // Types can appear in these contexts.
294 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000295 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
296 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
297 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
298 | (1LL << CodeCompletionContext::CCC_Statement)
299 | (1LL << CodeCompletionContext::CCC_Type)
300 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000301
302 // In C++, types can appear in expressions contexts (for functional casts).
303 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000304 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000305
306 // In Objective-C, message sends can send interfaces. In Objective-C++,
307 // all types are available due to functional casts.
308 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000310
311 // In Objective-C, you can only be a subclass of another Objective-C class
312 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000313 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000314
315 // Deal with tag names.
316 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000318
Douglas Gregor59cab552010-08-16 23:05:20 +0000319 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000320 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000321 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000322 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000323 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000325 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000326 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000327
Douglas Gregor39982192010-08-15 06:18:01 +0000328 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000330 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000332 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
333 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
335 | (1LL << CodeCompletionContext::CCC_Expression)
336 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
337 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000338 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000340 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000342 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000343 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000344
345 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000346 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000347 }
348
349 return Contexts;
350}
351
Douglas Gregorb14904c2010-08-13 22:48:40 +0000352void ASTUnit::CacheCodeCompletionResults() {
353 if (!TheSema)
354 return;
355
Douglas Gregor16896c42010-10-28 15:44:59 +0000356 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000357 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000358
359 // Clear out the previous results.
360 ClearCachedCompletionResults();
361
362 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000363 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000364 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000365 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000366 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000367 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000368 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000369
370 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000371 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
372
Douglas Gregorb14904c2010-08-13 22:48:40 +0000373 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
374 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000375 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000376 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000377 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000378 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000379 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000380 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000381 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000382 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000383 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000384 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000385 CachedResult.Priority = Results[I].Priority;
386 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000387 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000388
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000389 // Keep track of the type of this completion in an ASTContext-agnostic
390 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000391 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000392 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000393 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000394 CachedResult.Type = 0;
395 } else {
396 CanQualType CanUsageType
397 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
398 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
399
400 // Determine whether we have already seen this type. If so, we save
401 // ourselves the work of formatting the type string by using the
402 // temporary, CanQualType-based hash table to find the associated value.
403 unsigned &TypeValue = CompletionTypes[CanUsageType];
404 if (TypeValue == 0) {
405 TypeValue = CompletionTypes.size();
406 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
407 = TypeValue;
408 }
409
410 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000411 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000412
Douglas Gregor39982192010-08-15 06:18:01 +0000413 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000414
415 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000416 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000417 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
418 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000419 uint64_t NNSContexts
420 = (1LL << CodeCompletionContext::CCC_TopLevel)
421 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
422 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
423 | (1LL << CodeCompletionContext::CCC_Statement)
424 | (1LL << CodeCompletionContext::CCC_Expression)
425 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
426 | (1LL << CodeCompletionContext::CCC_EnumTag)
427 | (1LL << CodeCompletionContext::CCC_UnionTag)
428 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
429 | (1LL << CodeCompletionContext::CCC_Type)
430 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
431 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000432
433 if (isa<NamespaceDecl>(Results[I].Declaration) ||
434 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000435 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000436
437 if (unsigned RemainingContexts
438 = NNSContexts & ~CachedResult.ShowInContexts) {
439 // If there any contexts where this completion can be a
440 // nested-name-specifier but isn't already an option, create a
441 // nested-name-specifier completion.
442 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000443 CachedResult.Completion
444 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000445 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000446 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000447 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000448 CachedResult.ShowInContexts = RemainingContexts;
449 CachedResult.Priority = CCP_NestedNameSpecifier;
450 CachedResult.TypeClass = STC_Void;
451 CachedResult.Type = 0;
452 CachedCompletionResults.push_back(CachedResult);
453 }
454 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000455 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000456 }
457
Douglas Gregorb14904c2010-08-13 22:48:40 +0000458 case Result::RK_Keyword:
459 case Result::RK_Pattern:
460 // Ignore keywords and patterns; we don't care, since they are so
461 // easily regenerated.
462 break;
463
464 case Result::RK_Macro: {
465 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000466 CachedResult.Completion
467 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000468 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000469 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000470 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000471 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000472 = (1LL << CodeCompletionContext::CCC_TopLevel)
473 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
474 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
475 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
476 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
477 | (1LL << CodeCompletionContext::CCC_Statement)
478 | (1LL << CodeCompletionContext::CCC_Expression)
479 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
480 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
481 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
482 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
483 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000484
Douglas Gregorb14904c2010-08-13 22:48:40 +0000485 CachedResult.Priority = Results[I].Priority;
486 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000487 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000488 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000489 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000490 CachedCompletionResults.push_back(CachedResult);
491 break;
492 }
493 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000494 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000495
496 // Save the current top-level hash value.
497 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000498}
499
500void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000501 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000502 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000503 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000504}
505
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506namespace {
507
Sebastian Redl2c499f62010-08-18 23:56:43 +0000508/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000509/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000510class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000511 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000512 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 LangOptions &LangOpt;
Douglas Gregorcb177f12012-10-16 23:40:58 +0000514 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregore8bbc122011-09-02 00:18:52 +0000518 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000519public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000520 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregorcb177f12012-10-16 23:40:58 +0000521 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000522 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000523 unsigned &Counter)
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000524 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000525 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000526 Counter(Counter),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000527 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000528
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000529 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000530 bool Complain) {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000531 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000532 return false;
533
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000534 LangOpt = LangOpts;
535 InitializedLanguage = true;
536
537 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000538 return false;
539 }
Mike Stump11289f42009-09-09 15:08:12 +0000540
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000541 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000542 bool Complain) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000543 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000544 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000545 return false;
546
Douglas Gregorcb177f12012-10-16 23:40:58 +0000547 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregorf8715de2012-11-16 04:24:59 +0000548 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
549 &*this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000550
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000551 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000552 return false;
553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +0000555 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000556 Counter = Value;
557 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000558
559private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000560 void updated() {
561 if (!Target || !InitializedLanguage)
562 return;
563
564 // Inform the target of the language options.
565 //
566 // FIXME: We shouldn't need to do this, the target should be immutable once
567 // created. This complexity should be lifted elsewhere.
568 Target->setForcedLangOptions(LangOpt);
569
570 // Initialize the preprocessor.
571 PP.Initialize(*Target);
572
573 // Initialize the ASTContext
574 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000575
576 // We didn't have access to the comment options when the ASTContext was
577 // constructed, so register them now.
578 Context.getCommentCommandTraits().registerCommentOptions(
579 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000580 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000581};
582
Douglas Gregor6b930962013-05-03 22:58:43 +0000583 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000584class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000585 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000586 SourceManager *SourceMgr;
587
Douglas Gregor33cdd812010-02-18 18:08:43 +0000588public:
David Blaikief18d91a2011-09-26 00:01:39 +0000589 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000590 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor6b930962013-05-03 22:58:43 +0000591 : StoredDiags(StoredDiags), SourceMgr(0) { }
592
593 virtual void BeginSourceFile(const LangOptions &LangOpts,
594 const Preprocessor *PP = 0) {
595 if (PP)
596 SourceMgr = &PP->getSourceManager();
597 }
598
David Blaikie9c902b52011-09-25 23:23:43 +0000599 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000600 const Diagnostic &Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000601};
602
603/// \brief RAII object that optionally captures diagnostics, if
604/// there is no diagnostic client to capture them already.
605class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000606 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000607 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000608 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000609
610public:
David Blaikie9c902b52011-09-25 23:23:43 +0000611 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000612 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000613 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000614 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000615 if (RequestCapture || Diags.getClient() == 0) {
616 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000617 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000618 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000619 }
620
621 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000622 if (Diags.getClient() == &Client) {
623 Diags.takeClient();
624 Diags.setClient(PreviousClient);
625 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000626 }
627};
628
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000629} // anonymous namespace
630
David Blaikief18d91a2011-09-26 00:01:39 +0000631void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000632 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000633 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000634 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000635
Douglas Gregor6b930962013-05-03 22:58:43 +0000636 // Only record the diagnostic if it's part of the source manager we know
637 // about. This effectively drops diagnostics from modules we're building.
638 // FIXME: In the long run, ee don't want to drop source managers from modules.
639 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
640 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000641}
642
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000643ASTMutationListener *ASTUnit::getASTMutationListener() {
644 if (WriterData)
645 return &WriterData->Writer;
646 return 0;
647}
648
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000649ASTDeserializationListener *ASTUnit::getDeserializationListener() {
650 if (WriterData)
651 return &WriterData->Writer;
652 return 0;
653}
654
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000655llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000656 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000657 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000658 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000659}
660
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000661/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000662void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000663 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000664 ASTUnit &AST, bool CaptureDiagnostics) {
665 if (!Diags.getPtr()) {
666 // No diagnostics engine was provided, so create our own diagnostics object
667 // with the default options.
David Blaikiee2eefae2011-09-25 23:39:51 +0000668 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000669 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000670 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000671 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000672 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000673 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000674 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000675 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000676 }
677}
678
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000679ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000680 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000681 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000682 bool OnlyLocalDecls,
Dmitri Gribenko2febd212014-02-07 15:00:22 +0000683 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000684 bool CaptureDiagnostics,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000685 bool AllowPCHWithCompilerErrors,
686 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000687 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000688
689 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000690 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
691 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000692 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
693 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000694 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000695
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000696 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000697
Douglas Gregor16bef852009-10-16 20:01:17 +0000698 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000699 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000700 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000701 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000702 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000703 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000704 AST->getFileManager(),
705 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000706 AST->HSOpts = new HeaderSearchOptions();
707
708 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000709 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000710 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000711 AST->ASTFileLangOpts,
712 /*Target=*/0));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000713
Dmitri Gribenko2febd212014-02-07 15:00:22 +0000714 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000715 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
716 if (const llvm::MemoryBuffer *
717 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
718 // Create the file entry for the file that we're mapping from.
719 const FileEntry *FromFile
720 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
721 memBuf->getBufferSize(),
722 0);
723 if (!FromFile) {
724 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
725 << RemappedFiles[I].first;
726 delete memBuf;
727 continue;
728 }
729
730 // Override the contents of the "from" file with the contents of
731 // the "to" file.
732 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
733
734 } else {
735 const char *fname = fileOrBuf.get<const char *>();
736 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
737 if (!ToFile) {
738 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
739 << RemappedFiles[I].first << fname;
740 continue;
741 }
742
743 // Create the file entry for the file that we're mapping from.
744 const FileEntry *FromFile
745 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
746 ToFile->getSize(),
747 0);
748 if (!FromFile) {
749 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
750 << RemappedFiles[I].first;
751 delete memBuf;
752 continue;
753 }
754
755 // Override the contents of the "from" file with the contents of
756 // the "to" file.
757 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000758 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000759 }
760
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000761 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000762
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000763 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000764 unsigned Counter;
765
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000766 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000767
Douglas Gregor1452ff12012-10-24 17:46:57 +0000768 AST->PP = new Preprocessor(new PreprocessorOptions(),
769 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor83297df2011-09-01 23:39:15 +0000770 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
771 *AST,
772 /*IILookup=*/0,
773 /*OwnsHeaderSearch=*/false,
774 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000775 Preprocessor &PP = *AST->PP;
776
777 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
778 AST->getSourceManager(),
779 /*Target=*/0,
780 PP.getIdentifierTable(),
781 PP.getSelectorTable(),
782 PP.getBuiltinInfo(),
783 /* size_reserve = */0,
784 /*DelayInitialization=*/true);
785 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000786
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000787 bool disableValid = false;
788 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
789 disableValid = true;
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000790 Reader.reset(new ASTReader(PP, Context,
791 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000792 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000793 AllowPCHWithCompilerErrors));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000794
795 // Recover resources if we crash before exiting this method.
796 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
797 ReaderCleanup(Reader.get());
798
Douglas Gregore8bbc122011-09-02 00:18:52 +0000799 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000800 AST->ASTFileLangOpts,
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000801 AST->TargetOpts, AST->Target,
Douglas Gregord02437c2012-10-25 00:09:28 +0000802 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000803
Douglas Gregor4b29c162012-10-22 23:51:00 +0000804 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000805 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000806 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000807 break;
Mike Stump11289f42009-09-09 15:08:12 +0000808
Sebastian Redl2c499f62010-08-18 23:56:43 +0000809 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000810 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000811 case ASTReader::OutOfDate:
812 case ASTReader::VersionMismatch:
813 case ASTReader::ConfigurationMismatch:
814 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000815 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000816 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Daniel Dunbara8a50932009-12-02 08:44:16 +0000819 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
820
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000821 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000822
Sebastian Redl2c499f62010-08-18 23:56:43 +0000823 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000824 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000825 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000826 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000827 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000828
829 // Unregister the cleanup for ASTReader. It will get cleaned up
830 // by the ASTUnit cleanup.
831 ReaderCleanup.unregister();
832
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000833 Context.setExternalSource(Source);
834
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000835 // Create an AST consumer, even though it isn't used.
836 AST->Consumer.reset(new ASTConsumer);
837
Sebastian Redl2c499f62010-08-18 23:56:43 +0000838 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000839 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
840 AST->TheSema->Initialize();
841 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000842 AST->Reader = ReaderPtr;
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000843
Douglas Gregor6b930962013-05-03 22:58:43 +0000844 // Tell the diagnostic client that we have started a source file.
845 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
846
Mike Stump11289f42009-09-09 15:08:12 +0000847 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000848}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000849
850namespace {
851
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852/// \brief Preprocessor callback class that updates a hash value with the names
853/// of all macros that have been defined by the translation unit.
854class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
855 unsigned &Hash;
856
857public:
858 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
859
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000860 virtual void MacroDefined(const Token &MacroNameTok,
861 const MacroDirective *MD) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000862 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
863 }
864};
865
866/// \brief Add the given declaration to the hash of all top-level entities.
867void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
868 if (!D)
869 return;
870
871 DeclContext *DC = D->getDeclContext();
872 if (!DC)
873 return;
874
875 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
876 return;
877
878 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000879 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
880 // For an unscoped enum include the enumerators in the hash since they
881 // enter the top-level namespace.
882 if (!EnumD->isScoped()) {
883 for (EnumDecl::enumerator_iterator EI = EnumD->enumerator_begin(),
884 EE = EnumD->enumerator_end(); EI != EE; ++EI) {
885 if ((*EI)->getIdentifier())
886 Hash = llvm::HashString((*EI)->getIdentifier()->getName(), Hash);
887 }
888 }
889 }
890
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000891 if (ND->getIdentifier())
892 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
893 else if (DeclarationName Name = ND->getDeclName()) {
894 std::string NameStr = Name.getAsString();
895 Hash = llvm::HashString(NameStr, Hash);
896 }
897 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000898 }
899
900 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
901 if (Module *Mod = ImportD->getImportedModule()) {
902 std::string ModName = Mod->getFullModuleName();
903 Hash = llvm::HashString(ModName, Hash);
904 }
905 return;
906 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000907}
908
Daniel Dunbar644dca02009-12-04 08:17:33 +0000909class TopLevelDeclTrackerConsumer : public ASTConsumer {
910 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000911 unsigned &Hash;
912
Daniel Dunbar644dca02009-12-04 08:17:33 +0000913public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000914 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
915 : Unit(_Unit), Hash(Hash) {
916 Hash = 0;
917 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000918
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000919 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000920 if (!D)
921 return;
922
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000923 // FIXME: Currently ObjC method declarations are incorrectly being
924 // reported as top-level declarations, even though their DeclContext
925 // is the containing ObjC @interface/@implementation. This is a
926 // fundamental problem in the parser right now.
927 if (isa<ObjCMethodDecl>(D))
928 return;
929
930 AddTopLevelDeclarationToHash(D, Hash);
931 Unit.addTopLevelDecl(D);
932
933 handleFileLevelDecl(D);
934 }
935
936 void handleFileLevelDecl(Decl *D) {
937 Unit.addFileLevelDecl(D);
938 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
939 for (NamespaceDecl::decl_iterator
940 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
941 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000942 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000943 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000944
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000945 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000946 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
947 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000948 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000949 }
950
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000951 // We're not interested in "interesting" decls.
952 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000953
954 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
955 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
956 handleTopLevelDecl(*it);
957 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000958
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000959 virtual ASTMutationListener *GetASTMutationListener() {
960 return Unit.getASTMutationListener();
961 }
962
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000963 virtual ASTDeserializationListener *GetASTDeserializationListener() {
964 return Unit.getDeserializationListener();
965 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000966};
967
968class TopLevelDeclTrackerAction : public ASTFrontendAction {
969public:
970 ASTUnit &Unit;
971
Daniel Dunbar764c0822009-12-01 09:51:01 +0000972 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000973 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000974 CI.getPreprocessor().addPPCallbacks(
975 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
976 return new TopLevelDeclTrackerConsumer(Unit,
977 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000978 }
979
980public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000981 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
982
Daniel Dunbar764c0822009-12-01 09:51:01 +0000983 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000984 virtual TranslationUnitKind getTranslationUnitKind() {
985 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000986 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000987};
988
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000989class PrecompilePreambleAction : public ASTFrontendAction {
990 ASTUnit &Unit;
991 bool HasEmittedPreamblePCH;
992
993public:
994 explicit PrecompilePreambleAction(ASTUnit &Unit)
995 : Unit(Unit), HasEmittedPreamblePCH(false) {}
996
997 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
998 StringRef InFile);
999 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
1000 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
1001 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
1002
1003 virtual bool hasCodeCompletionSupport() const { return false; }
1004 virtual bool hasASTFileSupport() const { return false; }
1005 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
1006};
1007
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +00001008class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001009 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001010 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001011 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001012 PrecompilePreambleAction *Action;
1013
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001014public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001015 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
1016 const Preprocessor &PP, StringRef isysroot,
1017 raw_ostream *Out)
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001018 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001019 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001020 Hash = 0;
1021 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001022
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +00001023 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001024 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
1025 Decl *D = *it;
1026 // FIXME: Currently ObjC method declarations are incorrectly being
1027 // reported as top-level declarations, even though their DeclContext
1028 // is the containing ObjC @interface/@implementation. This is a
1029 // fundamental problem in the parser right now.
1030 if (isa<ObjCMethodDecl>(D))
1031 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001032 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001033 TopLevelDecls.push_back(D);
1034 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +00001035 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001036 }
1037
1038 virtual void HandleTranslationUnit(ASTContext &Ctx) {
1039 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001040 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001041 // Translate the top-level declarations we captured during
1042 // parsing into declaration IDs in the precompiled
1043 // preamble. This will allow us to deserialize those top-level
1044 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00001045 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
1046 Decl *D = TopLevelDecls[I];
1047 // Invalid top-level decls may not have been serialized.
1048 if (D->isInvalidDecl())
1049 continue;
1050 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
1051 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001052
1053 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001054 }
1055 }
1056};
1057
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001058}
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001059
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001060ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1061 StringRef InFile) {
1062 std::string Sysroot;
1063 std::string OutputFile;
1064 raw_ostream *OS = 0;
1065 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1066 OutputFile, OS))
1067 return 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001068
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001069 if (!CI.getFrontendOpts().RelocatablePCH)
1070 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001071
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001072 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1073 Unit.getCurrentTopLevelHashValue()));
1074 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1075 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +00001076}
1077
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001078static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1079 return StoredDiag.getLocation().isValid();
1080}
1081
1082static void
1083checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001084 // Get rid of stored diagnostics except the ones from the driver which do not
1085 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001086 StoredDiags.erase(
1087 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1088 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001089}
1090
1091static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1092 StoredDiagnostics,
1093 SourceManager &SM) {
1094 // The stored diagnostic has the old source manager in it; update
1095 // the locations to refer into the new source manager. Since we've
1096 // been careful to make sure that the source manager's state
1097 // before and after are identical, so that we can reuse the source
1098 // location itself.
1099 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1100 if (StoredDiagnostics[I].getLocation().isValid()) {
1101 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1102 StoredDiagnostics[I].setLocation(Loc);
1103 }
1104 }
1105}
1106
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001107/// Parse the source file into a translation unit using the given compiler
1108/// invocation, replacing the current translation unit.
1109///
1110/// \returns True if a failure occurred that causes the ASTUnit not to
1111/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001112bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001113 delete SavedMainFileBuffer;
1114 SavedMainFileBuffer = 0;
1115
Ted Kremenek5e14d392011-03-21 18:40:17 +00001116 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001117 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001118 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001119 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001120
Daniel Dunbar764c0822009-12-01 09:51:01 +00001121 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001122 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001123
1124 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001125 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1126 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001127
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001128 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001129 CCInvocation(new CompilerInvocation(*Invocation));
1130
1131 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001132 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001133
Douglas Gregor8e984da2010-08-04 16:47:14 +00001134 // Set up diagnostics, capturing any diagnostics that would
1135 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001136 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001137
Daniel Dunbar764c0822009-12-01 09:51:01 +00001138 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001139 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001140 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001141 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001142 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001143 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001144 }
1145
Daniel Dunbar764c0822009-12-01 09:51:01 +00001146 // Inform the target of the language options.
1147 //
1148 // FIXME: We shouldn't need to do this, the target should be immutable once
1149 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001150 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001151
Ted Kremenek84de4a12011-03-21 18:40:07 +00001152 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001153 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001154 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001155 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001156 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001157 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001158
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001159 // Configure the various subsystems.
1160 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001161 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001162 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001163 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001164 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1165 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001166 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001167 Ctx = 0;
1168 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001169 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001170
1171 // Clear out old caches and data.
1172 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001173 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001174 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001175
Douglas Gregor7b02b582010-08-20 00:02:33 +00001176 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001177 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001178 TopLevelDeclsInPreamble.clear();
1179 }
1180
Daniel Dunbar764c0822009-12-01 09:51:01 +00001181 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001182 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001183
Daniel Dunbar764c0822009-12-01 09:51:01 +00001184 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001185 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001186
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001187 // If the main file has been overridden due to the use of a preamble,
1188 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001189 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001190 if (OverrideMainBuffer) {
1191 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1192 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1193 PreprocessorOpts.PrecompiledPreambleBytes.second
1194 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001195 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001196 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001197
Douglas Gregord9a30af2010-08-02 20:51:39 +00001198 // The stored diagnostic has the old source manager in it; update
1199 // the locations to refer into the new source manager. Since we've
1200 // been careful to make sure that the source manager's state
1201 // before and after are identical, so that we can reuse the source
1202 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001203 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001204
1205 // Keep track of the override buffer;
1206 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001207 }
1208
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001209 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001210 new TopLevelDeclTrackerAction(*this));
1211
1212 // Recover resources if we crash before exiting this method.
1213 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1214 ActCleanup(Act.get());
1215
Douglas Gregor32fbe312012-01-20 16:28:04 +00001216 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001217 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001218
1219 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001220 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001221 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1222 getSourceManager(), PreambleDiagnostics,
1223 StoredDiagnostics);
1224 }
1225
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001226 if (!Act->Execute())
1227 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001228
1229 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001230
Daniel Dunbar644dca02009-12-04 08:17:33 +00001231 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001232
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001233 FailedParseDiagnostics.clear();
1234
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001235 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001236
Daniel Dunbar764c0822009-12-01 09:51:01 +00001237error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001238 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001239 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001240 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001241 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001242 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001243
1244 // Keep the ownership of the data in the ASTUnit because the client may
1245 // want to see the diagnostics.
1246 transferASTDataFromCompilerInstance(*Clang);
1247 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001248 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001249 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001250 return true;
1251}
1252
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001253/// \brief Simple function to retrieve a path for a preamble precompiled header.
1254static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001255 // FIXME: This is a hack so that we can override the preamble file during
1256 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001257 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001258 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1259 if (TmpFile)
1260 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001261
1262 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001263 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001264
1265 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001266}
1267
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001268/// \brief Compute the preamble for the main file, providing the source buffer
1269/// that corresponds to the main file along with a pair (bytes, start-of-line)
1270/// that describes the preamble.
1271std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001272ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1273 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001274 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001275 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001276 CreatedBuffer = false;
1277
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001278 // Try to determine if the main file has been remapped, either from the
1279 // command line (to another file) or directly through the compiler invocation
1280 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001281 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001282 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001283 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001284 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001285 // Check whether there is a file-file remapping of the main file
1286 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001287 M = PreprocessorOpts.remapped_file_begin(),
1288 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001289 M != E;
1290 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001291 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001292 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001293 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001294 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001295 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001296 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001297 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001298 CreatedBuffer = false;
1299 }
1300
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001301 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001302 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001303 return std::make_pair((llvm::MemoryBuffer*)0,
1304 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001305 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001306 }
1307 }
1308 }
1309
1310 // Check whether there is a file-buffer remapping. It supercedes the
1311 // file-file remapping.
1312 for (PreprocessorOptions::remapped_file_buffer_iterator
1313 M = PreprocessorOpts.remapped_file_buffer_begin(),
1314 E = PreprocessorOpts.remapped_file_buffer_end();
1315 M != E;
1316 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001317 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001318 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001319 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001320 if (MainFileID == MID) {
1321 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001323 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001324 CreatedBuffer = false;
1325 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001326
Douglas Gregor4dde7492010-07-23 23:58:40 +00001327 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001328 }
1329 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001330 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001331 }
1332
1333 // If the main source file was not remapped, load it now.
1334 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001335 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001336 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001337 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001338
1339 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001340 }
1341
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001342 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001343 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001344 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001345}
1346
Douglas Gregor6481ef12010-07-24 00:38:13 +00001347static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001348 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001349 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001350 llvm::MemoryBuffer *Result
1351 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1352 memcpy(const_cast<char*>(Result->getBufferStart()),
1353 Old->getBufferStart(), Old->getBufferSize());
1354 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001355 ' ', NewSize - Old->getBufferSize() - 1);
1356 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001357
Douglas Gregor6481ef12010-07-24 00:38:13 +00001358 return Result;
1359}
1360
Dmitri Gribenko47652522013-12-20 00:16:25 +00001361ASTUnit::PreambleFileHash
1362ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1363 PreambleFileHash Result;
1364 Result.Size = Size;
1365 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001366 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001367 return Result;
1368}
1369
1370ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1371 const llvm::MemoryBuffer *Buffer) {
1372 PreambleFileHash Result;
1373 Result.Size = Buffer->getBufferSize();
1374 Result.ModTime = 0;
1375
1376 llvm::MD5 MD5Ctx;
1377 MD5Ctx.update(Buffer->getBuffer().data());
1378 MD5Ctx.final(Result.MD5);
1379
1380 return Result;
1381}
1382
1383namespace clang {
1384bool operator==(const ASTUnit::PreambleFileHash &LHS,
1385 const ASTUnit::PreambleFileHash &RHS) {
1386 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001387 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001388}
1389} // namespace clang
1390
Douglas Gregor4dde7492010-07-23 23:58:40 +00001391/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1392/// the source file.
1393///
1394/// This routine will compute the preamble of the main source file. If a
1395/// non-trivial preamble is found, it will precompile that preamble into a
1396/// precompiled header so that the precompiled preamble can be used to reduce
1397/// reparsing time. If a precompiled preamble has already been constructed,
1398/// this routine will determine if it is still valid and, if so, avoid
1399/// rebuilding the precompiled preamble.
1400///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001401/// \param AllowRebuild When true (the default), this routine is
1402/// allowed to rebuild the precompiled preamble if it is found to be
1403/// out-of-date.
1404///
1405/// \param MaxLines When non-zero, the maximum number of lines that
1406/// can occur within the preamble.
1407///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001408/// \returns If the precompiled preamble can be used, returns a newly-allocated
1409/// buffer that should be used in place of the main file when doing so.
1410/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001411llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001412 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001413 bool AllowRebuild,
1414 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001415
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001416 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001417 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1418 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001419 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001420 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001421
1422 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001423 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001424 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001425
Douglas Gregor925296b2011-07-19 16:10:42 +00001426 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001427 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001428 if (CreatedPreambleBuffer)
1429 OwnedPreambleBuffer.reset(NewPreamble.first);
1430
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001431 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001432 // We couldn't find a preamble in the main source. Clear out the current
1433 // preamble, if we have one. It's obviously no good any more.
1434 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001435 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001436
1437 // The next time we actually see a preamble, precompile it.
1438 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001439 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001440 }
1441
1442 if (!Preamble.empty()) {
1443 // We've previously computed a preamble. Check whether we have the same
1444 // preamble now that we did before, and that there's enough space in
1445 // the main-file buffer within the precompiled preamble to fit the
1446 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001447 if (Preamble.size() == NewPreamble.second.first &&
1448 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001449 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001450 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001451 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001452 // The preamble has not changed. We may be able to re-use the precompiled
1453 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001454
Douglas Gregor0e119552010-07-31 00:40:00 +00001455 // Check that none of the files used by the preamble have changed.
1456 bool AnyFileChanged = false;
1457
1458 // First, make a record of those files that have been overridden via
1459 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001460 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregor0e119552010-07-31 00:40:00 +00001461 for (PreprocessorOptions::remapped_file_iterator
1462 R = PreprocessorOpts.remapped_file_begin(),
1463 REnd = PreprocessorOpts.remapped_file_end();
1464 !AnyFileChanged && R != REnd;
1465 ++R) {
Rafael Espindolae4777f42013-07-29 18:22:23 +00001466 llvm::sys::fs::file_status Status;
1467 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001468 // If we can't stat the file we're remapping to, assume that something
1469 // horrible happened.
1470 AnyFileChanged = true;
1471 break;
1472 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001473
Dmitri Gribenko47652522013-12-20 00:16:25 +00001474 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001475 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001476 }
1477 for (PreprocessorOptions::remapped_file_buffer_iterator
1478 R = PreprocessorOpts.remapped_file_buffer_begin(),
1479 REnd = PreprocessorOpts.remapped_file_buffer_end();
1480 !AnyFileChanged && R != REnd;
1481 ++R) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001482 OverriddenFiles[R->first] =
1483 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001484 }
1485
1486 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001487 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001488 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1489 !AnyFileChanged && F != FEnd;
1490 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001491 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001492 = OverriddenFiles.find(F->first());
1493 if (Overridden != OverriddenFiles.end()) {
1494 // This file was remapped; check whether the newly-mapped file
1495 // matches up with the previous mapping.
1496 if (Overridden->second != F->second)
1497 AnyFileChanged = true;
1498 continue;
1499 }
1500
1501 // The file was not remapped; check whether it has changed on disk.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001502 llvm::sys::fs::file_status Status;
1503 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001504 // If we can't stat the file, assume that something horrible happened.
1505 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001506 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001507 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001508 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001509 AnyFileChanged = true;
1510 }
1511
1512 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001513 // Okay! We can re-use the precompiled preamble.
1514
1515 // Set the state of the diagnostic object to mimic its state
1516 // after parsing the preamble.
1517 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001518 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001519 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001520 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001521
1522 // Create a version of the main file buffer that is padded to
1523 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001524 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001525 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001526 FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001527 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001528 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001529
1530 // If we aren't allowed to rebuild the precompiled preamble, just
1531 // return now.
1532 if (!AllowRebuild)
1533 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001534
Douglas Gregor4dde7492010-07-23 23:58:40 +00001535 // We can't reuse the previously-computed preamble. Build a new one.
1536 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001537 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001538 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001539 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001540 } else if (!AllowRebuild) {
1541 // We aren't allowed to rebuild the precompiled preamble; just
1542 // return now.
1543 return 0;
1544 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001545
1546 // If the preamble rebuild counter > 1, it's because we previously
1547 // failed to build a preamble and we're not yet ready to try
1548 // again. Decrement the counter and return a failure.
1549 if (PreambleRebuildCounter > 1) {
1550 --PreambleRebuildCounter;
1551 return 0;
1552 }
1553
Douglas Gregore10f0e52010-09-11 17:56:52 +00001554 // Create a temporary file for the precompiled preamble. In rare
1555 // circumstances, this can fail.
1556 std::string PreamblePCHPath = GetPreamblePCHPath();
1557 if (PreamblePCHPath.empty()) {
1558 // Try again next time.
1559 PreambleRebuildCounter = 1;
1560 return 0;
1561 }
1562
Douglas Gregor4dde7492010-07-23 23:58:40 +00001563 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001564 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001565 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001566
1567 // Create a new buffer that stores the preamble. The buffer also contains
1568 // extra space for the original contents of the file (which will be present
1569 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001570 // grows.
1571 PreambleReservedSize = NewPreamble.first->getBufferSize();
1572 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001573 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001574 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001575 PreambleReservedSize *= 2;
1576
Douglas Gregord9a30af2010-08-02 20:51:39 +00001577 // Save the preamble text for later; we'll need to compare against it for
1578 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001579 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001580 Preamble.assign(FileMgr->getFile(MainFilename),
1581 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001582 NewPreamble.first->getBufferStart()
1583 + NewPreamble.second.first);
1584 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1585
Douglas Gregora0734c52010-08-19 01:33:06 +00001586 delete PreambleBuffer;
1587 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001588 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001589 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001590 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001591 NewPreamble.first->getBufferStart(), Preamble.size());
1592 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001593 ' ', PreambleReservedSize - Preamble.size() - 1);
1594 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001595
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001596 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001597 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1598 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1599
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001600 // Tell the compiler invocation to generate a temporary precompiled header.
1601 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001602 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001603 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001604 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1605 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001606
1607 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001608 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001609
1610 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001611 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1612 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001613
Douglas Gregor3cc15812011-07-01 18:22:13 +00001614 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001615 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001616
Douglas Gregor8e984da2010-08-04 16:47:14 +00001617 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001618 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001619
1620 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001621 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001622 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001623 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001624 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001625 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001626 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001627 PreprocessorOpts.eraseRemappedFile(
1628 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001629 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001630 }
1631
1632 // Inform the target of the language options.
1633 //
1634 // FIXME: We shouldn't need to do this, the target should be immutable once
1635 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001636 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001637
Ted Kremenek84de4a12011-03-21 18:40:07 +00001638 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001639 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001640 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001641 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001642 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001643 "IR inputs not support here!");
1644
1645 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001646 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001647 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001648 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001649 TopLevelDecls.clear();
1650 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001651
1652 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001653 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001654
1655 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001656 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001657 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001658
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001659 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001660 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001661 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001662 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001663 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001664 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001665 PreprocessorOpts.eraseRemappedFile(
1666 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001667 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001668 }
1669
1670 Act->Execute();
1671 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001672
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001673 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001674 // The preamble PCH failed (e.g. there was a module loading fatal error),
1675 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001676 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001677 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001678 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001679 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001680 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001681 PreprocessorOpts.eraseRemappedFile(
1682 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001683 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001684 }
1685
Douglas Gregor925296b2011-07-19 16:10:42 +00001686 // Transfer any diagnostics generated when parsing the preamble into the set
1687 // of preamble diagnostics.
1688 PreambleDiagnostics.clear();
1689 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001690 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001691 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001692
Douglas Gregor4dde7492010-07-23 23:58:40 +00001693 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001694 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001695 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001696
1697 // Keep track of all of the files that the source manager knows about,
1698 // so we can verify whether they have changed or not.
1699 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001700 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001701 const llvm::MemoryBuffer *MainFileBuffer
1702 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1703 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1704 FEnd = SourceMgr.fileinfo_end();
1705 F != FEnd;
1706 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001707 const FileEntry *File = F->second->OrigEntry;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001708 if (!File)
Douglas Gregor0e119552010-07-31 00:40:00 +00001709 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001710 const llvm::MemoryBuffer *Buffer = F->second->getRawBuffer();
1711 if (Buffer == MainFileBuffer)
1712 continue;
1713
1714 if (time_t ModTime = File->getModificationTime()) {
1715 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1716 F->second->getSize(), ModTime);
1717 } else {
1718 assert(F->second->getSize() == Buffer->getBufferSize());
1719 FilesInPreamble[File->getName()] =
1720 PreambleFileHash::createForMemoryBuffer(Buffer);
1721 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001722 }
1723
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001724 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001725 PreprocessorOpts.eraseRemappedFile(
1726 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001727
1728 // If the hash of top-level entities differs from the hash of the top-level
1729 // entities the last time we rebuilt the preamble, clear out the completion
1730 // cache.
1731 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1732 CompletionCacheTopLevelHashValue = 0;
1733 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1734 }
1735
Douglas Gregor6481ef12010-07-24 00:38:13 +00001736 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001737 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001738 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001739}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001740
Douglas Gregore9db88f2010-08-03 19:06:41 +00001741void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1742 std::vector<Decl *> Resolved;
1743 Resolved.reserve(TopLevelDeclsInPreamble.size());
1744 ExternalASTSource &Source = *getASTContext().getExternalSource();
1745 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1746 // Resolve the declaration ID to an actual declaration, possibly
1747 // deserializing the declaration in the process.
1748 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1749 if (D)
1750 Resolved.push_back(D);
1751 }
1752 TopLevelDeclsInPreamble.clear();
1753 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1754}
1755
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001756void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1757 // Steal the created target, context, and preprocessor.
1758 TheSema.reset(CI.takeSema());
1759 Consumer.reset(CI.takeASTConsumer());
1760 Ctx = &CI.getASTContext();
1761 PP = &CI.getPreprocessor();
1762 CI.setSourceManager(0);
1763 CI.setFileManager(0);
1764 Target = &CI.getTarget();
1765 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001766 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001767}
1768
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001769StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001770 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1771 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1772 if (Input.isFile())
1773 return Input.getFile();
1774 else
1775 return Input.getBuffer()->getBufferIdentifier();
1776 }
1777
1778 if (SourceMgr) {
1779 if (const FileEntry *
1780 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1781 return FE->getName();
1782 }
1783
1784 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001785}
1786
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001787StringRef ASTUnit::getASTFileName() const {
1788 if (!isMainFileAST())
1789 return StringRef();
1790
1791 serialization::ModuleFile &
1792 Mod = Reader->getModuleManager().getPrimaryModule();
1793 return Mod.FileName;
1794}
1795
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001796ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001797 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001798 bool CaptureDiagnostics,
1799 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001800 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001801 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001802 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001803 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001804 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001805 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001806 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001807 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1808 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1809 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001810
1811 return AST.take();
1812}
1813
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001814ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001815 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001816 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001817 ASTUnit *Unit,
1818 bool Persistent,
1819 StringRef ResourceFilesPath,
1820 bool OnlyLocalDecls,
1821 bool CaptureDiagnostics,
1822 bool PrecompilePreamble,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001823 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001824 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001825 bool UserFilesAreVolatile,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001826 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001827 assert(CI && "A CompilerInvocation is required");
1828
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001829 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001830 ASTUnit *AST = Unit;
1831 if (!AST) {
1832 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001833 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001834 AST = OwnAST.get();
1835 }
1836
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001837 if (!ResourceFilesPath.empty()) {
1838 // Override the resources path.
1839 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1840 }
1841 AST->OnlyLocalDecls = OnlyLocalDecls;
1842 AST->CaptureDiagnostics = CaptureDiagnostics;
1843 if (PrecompilePreamble)
1844 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001845 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001846 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001847 AST->IncludeBriefCommentsInCodeCompletion
1848 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001849
1850 // Recover resources if we crash before exiting this method.
1851 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001852 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001853 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1854 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001855 DiagCleanup(Diags.getPtr());
1856
1857 // We'll manage file buffers ourselves.
1858 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1859 CI->getFrontendOpts().DisableFree = false;
1860 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1861
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001862 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001863 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001864
1865 // Recover resources if we crash before exiting this method.
1866 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1867 CICleanup(Clang.get());
1868
1869 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001870 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001871
1872 // Set up diagnostics, capturing any diagnostics that would
1873 // otherwise be dropped.
1874 Clang->setDiagnostics(&AST->getDiagnostics());
1875
1876 // Create the target instance.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001877 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001878 &Clang->getTargetOpts()));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001879 if (!Clang->hasTarget())
1880 return 0;
1881
1882 // Inform the target of the language options.
1883 //
1884 // FIXME: We shouldn't need to do this, the target should be immutable once
1885 // created. This complexity should be lifted elsewhere.
1886 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1887
1888 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1889 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001890 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001891 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001892 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001893 "IR inputs not supported here!");
1894
1895 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001896 AST->TheSema.reset();
1897 AST->Ctx = 0;
1898 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001899 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001900
1901 // Create a file manager object to provide access to and cache the filesystem.
1902 Clang->setFileManager(&AST->getFileManager());
1903
1904 // Create the source manager.
1905 Clang->setSourceManager(&AST->getSourceManager());
1906
1907 ASTFrontendAction *Act = Action;
1908
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001909 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001910 if (!Act) {
1911 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1912 Act = TrackerAct.get();
1913 }
1914
1915 // Recover resources if we crash before exiting this method.
1916 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1917 ActCleanup(TrackerAct.get());
1918
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001919 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1920 AST->transferASTDataFromCompilerInstance(*Clang);
1921 if (OwnAST && ErrAST)
1922 ErrAST->swap(OwnAST);
1923
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001924 return 0;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001925 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001926
1927 if (Persistent && !TrackerAct) {
1928 Clang->getPreprocessor().addPPCallbacks(
1929 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1930 std::vector<ASTConsumer*> Consumers;
1931 if (Clang->hasASTConsumer())
1932 Consumers.push_back(Clang->takeASTConsumer());
1933 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1934 AST->getCurrentTopLevelHashValue()));
1935 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1936 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001937 if (!Act->Execute()) {
1938 AST->transferASTDataFromCompilerInstance(*Clang);
1939 if (OwnAST && ErrAST)
1940 ErrAST->swap(OwnAST);
1941
1942 return 0;
1943 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001944
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001945 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001946 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001947
1948 Act->EndSourceFile();
1949
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001950 if (OwnAST)
1951 return OwnAST.take();
1952 else
1953 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001954}
1955
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001956bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1957 if (!Invocation)
1958 return true;
1959
1960 // We'll manage file buffers ourselves.
1961 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1962 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001963 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001964
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001965 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001966 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001967 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001968 OverrideMainBuffer
1969 = getMainBufferWithPrecompiledPreamble(*Invocation);
1970 }
1971
Douglas Gregor16896c42010-10-28 15:44:59 +00001972 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001973 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001974
Ted Kremenek022a4902011-03-22 01:15:24 +00001975 // Recover resources if we crash before exiting this method.
1976 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1977 MemBufferCleanup(OverrideMainBuffer);
1978
Douglas Gregor16896c42010-10-28 15:44:59 +00001979 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001980}
1981
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001982ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001983 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001984 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001985 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001986 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001987 TranslationUnitKind TUKind,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001988 bool CacheCodeCompletionResults,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001989 bool IncludeBriefCommentsInCodeCompletion,
1990 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001991 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001992 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001993 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001994 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001995 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001996 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001997 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001998 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001999 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002000 AST->IncludeBriefCommentsInCodeCompletion
2001 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002002 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00002003 AST->FileSystemOpts = CI->getFileSystemOpts();
2004 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002005 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002006
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002007 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002008 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2009 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00002010 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2011 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00002012 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002013
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002014 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00002015}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002016
2017ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
2018 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002019 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002020 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002021 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002022 bool CaptureDiagnostics,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002023 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00002024 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00002025 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00002026 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002027 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002028 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002029 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6e922512012-04-12 10:11:59 +00002030 bool SkipFunctionBodies,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002031 bool UserFilesAreVolatile,
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002032 bool ForSerialization,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002033 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00002034 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00002035 // No diagnostics engine was provided, so create our own diagnostics object
2036 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00002037 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00002038 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002039
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002040 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002041
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002042 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002043
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002044 {
Douglas Gregor925296b2011-07-19 16:10:42 +00002045
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002046 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002047 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00002048
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00002049 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002050 llvm::makeArrayRef(ArgBegin, ArgEnd),
2051 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00002052 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00002053 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002054 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002055
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002056 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002057 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002058 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2059 if (const llvm::MemoryBuffer *
2060 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2061 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2062 } else {
2063 const char *fname = fileOrBuf.get<const char *>();
2064 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2065 }
2066 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002067 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2068 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2069 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002070
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002071 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002072 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002073
Erik Verbruggen6e922512012-04-12 10:11:59 +00002074 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2075
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002076 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002077 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002078 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002079 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002080 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00002081 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002082 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00002083 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002084 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002085 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002086 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002087 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002088 AST->IncludeBriefCommentsInCodeCompletion
2089 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002090 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002091 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002092 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002093 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002094 if (ForSerialization)
2095 AST->WriterData.reset(new ASTWriterData());
Ted Kremenek25047602011-11-17 23:01:17 +00002096 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002097
2098 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002099 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2100 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002101
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002102 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2103 // Some error occurred, if caller wants to examine diagnostics, pass it the
2104 // ASTUnit.
2105 if (ErrAST) {
2106 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2107 ErrAST->swap(AST);
2108 }
2109 return 0;
2110 }
2111
2112 return AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002113}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002114
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002115bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002116 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002117 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002118
2119 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002120
Douglas Gregor16896c42010-10-28 15:44:59 +00002121 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002122 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002123
Douglas Gregor0e119552010-07-31 00:40:00 +00002124 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002125 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2126 for (PreprocessorOptions::remapped_file_buffer_iterator
2127 R = PPOpts.remapped_file_buffer_begin(),
2128 REnd = PPOpts.remapped_file_buffer_end();
2129 R != REnd;
2130 ++R) {
2131 delete R->second;
2132 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002133 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002134 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002135 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2136 if (const llvm::MemoryBuffer *
2137 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2138 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2139 memBuf);
2140 } else {
2141 const char *fname = fileOrBuf.get<const char *>();
2142 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2143 fname);
2144 }
2145 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002146
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002147 // If we have a preamble file lying around, or if we might try to
2148 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00002149 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002150 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002151 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002152
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002153 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002154 getDiagnostics().Reset();
2155 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002156 if (OverrideMainBuffer)
2157 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002158
Douglas Gregor4dde7492010-07-23 23:58:40 +00002159 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002160 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002161
2162 // If we're caching global code-completion results, and the top-level
2163 // declarations have changed, clear out the code-completion cache.
2164 if (!Result && ShouldCacheCodeCompletionResults &&
2165 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2166 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002167
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002168 // We now need to clear out the completion info related to this translation
2169 // unit; it'll be recreated if necessary.
2170 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002171
Douglas Gregor4dde7492010-07-23 23:58:40 +00002172 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002173}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002174
Douglas Gregorb14904c2010-08-13 22:48:40 +00002175//----------------------------------------------------------------------------//
2176// Code completion
2177//----------------------------------------------------------------------------//
2178
2179namespace {
2180 /// \brief Code completion consumer that combines the cached code-completion
2181 /// results from an ASTUnit with the code-completion results provided to it,
2182 /// then passes the result on to
2183 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002184 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002185 ASTUnit &AST;
2186 CodeCompleteConsumer &Next;
2187
2188 public:
2189 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002190 const CodeCompleteOptions &CodeCompleteOpts)
2191 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2192 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002193 {
2194 // Compute the set of contexts in which we will look when we don't have
2195 // any information about the specific context.
2196 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002197 = (1LL << CodeCompletionContext::CCC_TopLevel)
2198 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2199 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2200 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2201 | (1LL << CodeCompletionContext::CCC_Statement)
2202 | (1LL << CodeCompletionContext::CCC_Expression)
2203 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2204 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2205 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2206 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2207 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2208 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2209 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002210
David Blaikiebbafb8a2012-03-11 07:00:24 +00002211 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002212 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2213 | (1LL << CodeCompletionContext::CCC_UnionTag)
2214 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002215 }
2216
2217 virtual void ProcessCodeCompleteResults(Sema &S,
2218 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002219 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002220 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002221
2222 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2223 OverloadCandidate *Candidates,
2224 unsigned NumCandidates) {
2225 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2226 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002227
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002228 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002229 return Next.getAllocator();
2230 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002231
2232 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2233 return Next.getCodeCompletionTUInfo();
2234 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002235 };
2236}
Douglas Gregord46cf182010-08-16 20:01:48 +00002237
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002238/// \brief Helper function that computes which global names are hidden by the
2239/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002240static void CalculateHiddenNames(const CodeCompletionContext &Context,
2241 CodeCompletionResult *Results,
2242 unsigned NumResults,
2243 ASTContext &Ctx,
2244 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002245 bool OnlyTagNames = false;
2246 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002247 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002248 case CodeCompletionContext::CCC_TopLevel:
2249 case CodeCompletionContext::CCC_ObjCInterface:
2250 case CodeCompletionContext::CCC_ObjCImplementation:
2251 case CodeCompletionContext::CCC_ObjCIvarList:
2252 case CodeCompletionContext::CCC_ClassStructUnion:
2253 case CodeCompletionContext::CCC_Statement:
2254 case CodeCompletionContext::CCC_Expression:
2255 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002256 case CodeCompletionContext::CCC_DotMemberAccess:
2257 case CodeCompletionContext::CCC_ArrowMemberAccess:
2258 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002259 case CodeCompletionContext::CCC_Namespace:
2260 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002261 case CodeCompletionContext::CCC_Name:
2262 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002263 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002264 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002265 break;
2266
2267 case CodeCompletionContext::CCC_EnumTag:
2268 case CodeCompletionContext::CCC_UnionTag:
2269 case CodeCompletionContext::CCC_ClassOrStructTag:
2270 OnlyTagNames = true;
2271 break;
2272
2273 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002274 case CodeCompletionContext::CCC_MacroName:
2275 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002276 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002277 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002278 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002279 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002280 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002281 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002282 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002283 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2284 case CodeCompletionContext::CCC_ObjCClassMessage:
2285 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002286 // We're looking for nothing, or we're looking for names that cannot
2287 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002288 return;
2289 }
2290
John McCall276321a2010-08-25 06:19:51 +00002291 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002292 for (unsigned I = 0; I != NumResults; ++I) {
2293 if (Results[I].Kind != Result::RK_Declaration)
2294 continue;
2295
2296 unsigned IDNS
2297 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2298
2299 bool Hiding = false;
2300 if (OnlyTagNames)
2301 Hiding = (IDNS & Decl::IDNS_Tag);
2302 else {
2303 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002304 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2305 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002306 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002307 HiddenIDNS |= Decl::IDNS_Tag;
2308 Hiding = (IDNS & HiddenIDNS);
2309 }
2310
2311 if (!Hiding)
2312 continue;
2313
2314 DeclarationName Name = Results[I].Declaration->getDeclName();
2315 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2316 HiddenNames.insert(Identifier->getName());
2317 else
2318 HiddenNames.insert(Name.getAsString());
2319 }
2320}
2321
2322
Douglas Gregord46cf182010-08-16 20:01:48 +00002323void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2324 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002325 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002326 unsigned NumResults) {
2327 // Merge the results we were given with the results we cached.
2328 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002329 uint64_t InContexts =
2330 Context.getKind() == CodeCompletionContext::CCC_Recovery
2331 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002332 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002333 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002334 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002335 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002336 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002337 C = AST.cached_completion_begin(),
2338 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002339 C != CEnd; ++C) {
2340 // If the context we are in matches any of the contexts we are
2341 // interested in, we'll add this result.
2342 if ((C->ShowInContexts & InContexts) == 0)
2343 continue;
2344
2345 // If we haven't added any results previously, do so now.
2346 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002347 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2348 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002349 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2350 AddedResult = true;
2351 }
2352
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002353 // Determine whether this global completion result is hidden by a local
2354 // completion result. If so, skip it.
2355 if (C->Kind != CXCursor_MacroDefinition &&
2356 HiddenNames.count(C->Completion->getTypedText()))
2357 continue;
2358
Douglas Gregord46cf182010-08-16 20:01:48 +00002359 // Adjust priority based on similar type classes.
2360 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002361 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002362 if (!Context.getPreferredType().isNull()) {
2363 if (C->Kind == CXCursor_MacroDefinition) {
2364 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002365 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002366 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002367 } else if (C->Type) {
2368 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002369 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002370 Context.getPreferredType().getUnqualifiedType());
2371 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2372 if (ExpectedSTC == C->TypeClass) {
2373 // We know this type is similar; check for an exact match.
2374 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002375 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002376 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002377 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002378 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2379 Priority /= CCF_ExactTypeMatch;
2380 else
2381 Priority /= CCF_SimilarTypeMatch;
2382 }
2383 }
2384 }
2385
Douglas Gregor12785102010-08-24 20:21:13 +00002386 // Adjust the completion string, if required.
2387 if (C->Kind == CXCursor_MacroDefinition &&
2388 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2389 // Create a new code-completion string that just contains the
2390 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002391 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2392 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002393 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002394 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002395 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002396 }
2397
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002398 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002399 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002400 }
2401
2402 // If we did not add any cached completion results, just forward the
2403 // results we were given to the next consumer.
2404 if (!AddedResult) {
2405 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2406 return;
2407 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002408
Douglas Gregord46cf182010-08-16 20:01:48 +00002409 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2410 AllResults.size());
2411}
2412
2413
2414
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002415void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002416 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002417 bool IncludeMacros,
2418 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002419 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002420 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002421 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002422 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002423 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2424 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002425 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002426 return;
2427
Douglas Gregor16896c42010-10-28 15:44:59 +00002428 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002429 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002430 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002431
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002432 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002433 CCInvocation(new CompilerInvocation(*Invocation));
2434
2435 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002436 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002437 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002438
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002439 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2440 CachedCompletionResults.empty();
2441 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2442 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2443 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2444
2445 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2446
Douglas Gregor8e984da2010-08-04 16:47:14 +00002447 FrontendOpts.CodeCompletionAt.FileName = File;
2448 FrontendOpts.CodeCompletionAt.Line = Line;
2449 FrontendOpts.CodeCompletionAt.Column = Column;
2450
2451 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002452 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002453
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002454 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002455
2456 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002457 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2458 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002459
Ted Kremenek5e14d392011-03-21 18:40:17 +00002460 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002461 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002462
2463 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002464 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002465 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002466 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002467 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002468 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002469
2470 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002471 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00002472 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002473 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002474 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002475 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002476 }
2477
2478 // Inform the target of the language options.
2479 //
2480 // FIXME: We shouldn't need to do this, the target should be immutable once
2481 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002482 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002483
Ted Kremenek84de4a12011-03-21 18:40:07 +00002484 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002485 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002486 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002487 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002488 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002489 "IR inputs not support here!");
2490
2491
2492 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002493 Clang->setFileManager(&FileMgr);
2494 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002495
2496 // Remap files.
2497 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002498 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002499 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002500 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2501 if (const llvm::MemoryBuffer *
2502 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2503 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2504 OwnedBuffers.push_back(memBuf);
2505 } else {
2506 const char *fname = fileOrBuf.get<const char *>();
2507 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2508 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002509 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002510
Douglas Gregorb14904c2010-08-13 22:48:40 +00002511 // Use the code completion consumer we were given, but adding any cached
2512 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002513 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002514 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002515 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002516
Douglas Gregor028d3e42010-08-09 20:45:32 +00002517 // If we have a precompiled preamble, try to use it. We only allow
2518 // the use of the precompiled preamble if we're if the completion
2519 // point is within the main file, after the end of the precompiled
2520 // preamble.
2521 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002522 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002523 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002524 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002525
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002526 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002527 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002528 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002529 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002530 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002531 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002532 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002533 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002534 }
2535 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002536 }
2537
2538 // If the main file has been overridden due to the use of a preamble,
2539 // make that override happen and introduce the preamble.
2540 if (OverrideMainBuffer) {
2541 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2542 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2543 PreprocessorOpts.PrecompiledPreambleBytes.second
2544 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002545 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002546 PreprocessorOpts.DisablePCHValidation = true;
2547
Douglas Gregorb97b6662010-08-20 00:59:43 +00002548 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002549 } else {
2550 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2551 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002552 }
2553
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002554 // Disable the preprocessing record if modules are not enabled.
2555 if (!Clang->getLangOpts().Modules)
2556 PreprocessorOpts.DetailedRecord = false;
Douglas Gregor998caea2011-05-06 16:33:08 +00002557
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002558 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002559 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002560 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002561 Act->Execute();
2562 Act->EndSourceFile();
2563 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002564}
Douglas Gregore9386682010-08-13 05:36:37 +00002565
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002566bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002567 if (HadModuleLoaderFatalFailure)
2568 return true;
2569
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002570 // Write to a temporary file and later rename it to the actual file, to avoid
2571 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002572 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002573 TempPath = File;
2574 TempPath += "-%%%%%%%%";
2575 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002576 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002577 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002578
Douglas Gregore9386682010-08-13 05:36:37 +00002579 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2580 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002581 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002582
2583 serialize(Out);
2584 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002585 if (Out.has_error()) {
2586 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002587 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002588 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002589
Rafael Espindola65e025c2011-12-25 01:18:52 +00002590 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002591 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002592 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002593 }
2594
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002595 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002596}
2597
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002598static bool serializeUnit(ASTWriter &Writer,
2599 SmallVectorImpl<char> &Buffer,
2600 Sema &S,
2601 bool hasErrors,
2602 raw_ostream &OS) {
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00002603 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002604
2605 // Write the generated bitstream to "Out".
2606 if (!Buffer.empty())
2607 OS.write(Buffer.data(), Buffer.size());
2608
2609 return false;
2610}
2611
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002612bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002613 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002614
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002615 if (WriterData)
2616 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2617 getSema(), hasErrors, OS);
2618
Daniel Dunbar9a963862012-02-29 20:31:23 +00002619 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002620 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002621 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002622 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002623}
Douglas Gregor925296b2011-07-19 16:10:42 +00002624
2625typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2626
2627static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2628 unsigned Raw = L.getRawEncoding();
2629 const unsigned MacroBit = 1U << 31;
2630 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2631 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2632}
2633
2634void ASTUnit::TranslateStoredDiagnostics(
2635 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002636 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002637 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002638 const SmallVectorImpl<StoredDiagnostic> &Diags,
2639 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002640 // The stored diagnostic has the old source manager in it; update
2641 // the locations to refer into the new source manager. We also need to remap
2642 // all the locations to the new view. This includes the diag location, any
2643 // associated source ranges, and the source ranges of associated fix-its.
2644 // FIXME: There should be a cleaner way to do this.
2645
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002646 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002647 Result.reserve(Diags.size());
2648 assert(MMan && "Don't have a module manager");
Douglas Gregorde3ef502011-11-30 23:21:26 +00002649 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002650 assert(Mod && "Don't have preamble module");
2651 SLocRemap &Remap = Mod->SLocRemap;
2652 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2653 // Rebuild the StoredDiagnostic.
2654 const StoredDiagnostic &SD = Diags[I];
2655 SourceLocation L = SD.getLocation();
2656 TranslateSLoc(L, Remap);
2657 FullSourceLoc Loc(L, SrcMgr);
2658
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002659 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002660 Ranges.reserve(SD.range_size());
2661 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2662 E = SD.range_end();
2663 I != E; ++I) {
2664 SourceLocation BL = I->getBegin();
2665 TranslateSLoc(BL, Remap);
2666 SourceLocation EL = I->getEnd();
2667 TranslateSLoc(EL, Remap);
2668 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2669 }
2670
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002671 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002672 FixIts.reserve(SD.fixit_size());
2673 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2674 E = SD.fixit_end();
2675 I != E; ++I) {
2676 FixIts.push_back(FixItHint());
2677 FixItHint &FH = FixIts.back();
2678 FH.CodeToInsert = I->CodeToInsert;
2679 SourceLocation BL = I->RemoveRange.getBegin();
2680 TranslateSLoc(BL, Remap);
2681 SourceLocation EL = I->RemoveRange.getEnd();
2682 TranslateSLoc(EL, Remap);
2683 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2684 I->RemoveRange.isTokenRange());
2685 }
2686
2687 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2688 SD.getMessage(), Loc, Ranges, FixIts));
2689 }
2690 Result.swap(Out);
2691}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002692
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002693void ASTUnit::addFileLevelDecl(Decl *D) {
2694 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002695
2696 // We only care about local declarations.
2697 if (D->isFromASTFile())
2698 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002699
2700 SourceManager &SM = *SourceMgr;
2701 SourceLocation Loc = D->getLocation();
2702 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2703 return;
2704
2705 // We only keep track of the file-level declarations of each file.
2706 if (!D->getLexicalDeclContext()->isFileContext())
2707 return;
2708
2709 SourceLocation FileLoc = SM.getFileLoc(Loc);
2710 assert(SM.isLocalSourceLocation(FileLoc));
2711 FileID FID;
2712 unsigned Offset;
2713 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2714 if (FID.isInvalid())
2715 return;
2716
2717 LocDeclsTy *&Decls = FileDecls[FID];
2718 if (!Decls)
2719 Decls = new LocDeclsTy();
2720
2721 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2722
2723 if (Decls->empty() || Decls->back().first <= Offset) {
2724 Decls->push_back(LocDecl);
2725 return;
2726 }
2727
Benjamin Kramer45025c02013-08-24 13:22:59 +00002728 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2729 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002730
2731 Decls->insert(I, LocDecl);
2732}
2733
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002734void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2735 SmallVectorImpl<Decl *> &Decls) {
2736 if (File.isInvalid())
2737 return;
2738
2739 if (SourceMgr->isLoadedFileID(File)) {
2740 assert(Ctx->getExternalSource() && "No external source!");
2741 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2742 Decls);
2743 }
2744
2745 FileDeclsTy::iterator I = FileDecls.find(File);
2746 if (I == FileDecls.end())
2747 return;
2748
2749 LocDeclsTy &LocDecls = *I->second;
2750 if (LocDecls.empty())
2751 return;
2752
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002753 LocDeclsTy::iterator BeginIt =
2754 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002755 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002756 if (BeginIt != LocDecls.begin())
2757 --BeginIt;
2758
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002759 // If we are pointing at a top-level decl inside an objc container, we need
2760 // to backtrack until we find it otherwise we will fail to report that the
2761 // region overlaps with an objc container.
2762 while (BeginIt != LocDecls.begin() &&
2763 BeginIt->second->isTopLevelDeclInObjCContainer())
2764 --BeginIt;
2765
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002766 LocDeclsTy::iterator EndIt = std::upper_bound(
2767 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002768 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002769 if (EndIt != LocDecls.end())
2770 ++EndIt;
2771
2772 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2773 Decls.push_back(DIt->second);
2774}
2775
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002776SourceLocation ASTUnit::getLocation(const FileEntry *File,
2777 unsigned Line, unsigned Col) const {
2778 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002779 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002780 return SM.getMacroArgExpandedLocation(Loc);
2781}
2782
2783SourceLocation ASTUnit::getLocation(const FileEntry *File,
2784 unsigned Offset) const {
2785 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002786 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002787 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2788}
2789
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002790/// \brief If \arg Loc is a loaded location from the preamble, returns
2791/// the corresponding local location of the main file, otherwise it returns
2792/// \arg Loc.
2793SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2794 FileID PreambleID;
2795 if (SourceMgr)
2796 PreambleID = SourceMgr->getPreambleFileID();
2797
2798 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2799 return Loc;
2800
2801 unsigned Offs;
2802 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2803 SourceLocation FileLoc
2804 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2805 return FileLoc.getLocWithOffset(Offs);
2806 }
2807
2808 return Loc;
2809}
2810
2811/// \brief If \arg Loc is a local location of the main file but inside the
2812/// preamble chunk, returns the corresponding loaded location from the
2813/// preamble, otherwise it returns \arg Loc.
2814SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2815 FileID PreambleID;
2816 if (SourceMgr)
2817 PreambleID = SourceMgr->getPreambleFileID();
2818
2819 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2820 return Loc;
2821
2822 unsigned Offs;
2823 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2824 Offs < Preamble.size()) {
2825 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2826 return FileLoc.getLocWithOffset(Offs);
2827 }
2828
2829 return Loc;
2830}
2831
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002832bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2833 FileID FID;
2834 if (SourceMgr)
2835 FID = SourceMgr->getPreambleFileID();
2836
2837 if (Loc.isInvalid() || FID.isInvalid())
2838 return false;
2839
2840 return SourceMgr->isInFileID(Loc, FID);
2841}
2842
2843bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2844 FileID FID;
2845 if (SourceMgr)
2846 FID = SourceMgr->getMainFileID();
2847
2848 if (Loc.isInvalid() || FID.isInvalid())
2849 return false;
2850
2851 return SourceMgr->isInFileID(Loc, FID);
2852}
2853
2854SourceLocation ASTUnit::getEndOfPreambleFileID() {
2855 FileID FID;
2856 if (SourceMgr)
2857 FID = SourceMgr->getPreambleFileID();
2858
2859 if (FID.isInvalid())
2860 return SourceLocation();
2861
2862 return SourceMgr->getLocForEndOfFile(FID);
2863}
2864
2865SourceLocation ASTUnit::getStartOfMainFileID() {
2866 FileID FID;
2867 if (SourceMgr)
2868 FID = SourceMgr->getMainFileID();
2869
2870 if (FID.isInvalid())
2871 return SourceLocation();
2872
2873 return SourceMgr->getLocForStartOfFile(FID);
2874}
2875
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002876std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2877ASTUnit::getLocalPreprocessingEntities() const {
2878 if (isMainFileAST()) {
2879 serialization::ModuleFile &
2880 Mod = Reader->getModuleManager().getPrimaryModule();
2881 return Reader->getModulePreprocessedEntities(Mod);
2882 }
2883
2884 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2885 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2886
2887 return std::make_pair(PreprocessingRecord::iterator(),
2888 PreprocessingRecord::iterator());
2889}
2890
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002891bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002892 if (isMainFileAST()) {
2893 serialization::ModuleFile &
2894 Mod = Reader->getModuleManager().getPrimaryModule();
2895 ASTReader::ModuleDeclIterator MDI, MDE;
2896 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2897 for (; MDI != MDE; ++MDI) {
2898 if (!Fn(context, *MDI))
2899 return false;
2900 }
2901
2902 return true;
2903 }
2904
2905 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2906 TLEnd = top_level_end();
2907 TL != TLEnd; ++TL) {
2908 if (!Fn(context, *TL))
2909 return false;
2910 }
2911
2912 return true;
2913}
2914
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002915namespace {
2916struct PCHLocatorInfo {
2917 serialization::ModuleFile *Mod;
2918 PCHLocatorInfo() : Mod(0) {}
2919};
2920}
2921
2922static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2923 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2924 switch (M.Kind) {
2925 case serialization::MK_Module:
2926 return true; // skip dependencies.
2927 case serialization::MK_PCH:
2928 Info.Mod = &M;
2929 return true; // found it.
2930 case serialization::MK_Preamble:
2931 return false; // look in dependencies.
2932 case serialization::MK_MainFile:
2933 return false; // look in dependencies.
2934 }
2935
2936 return true;
2937}
2938
2939const FileEntry *ASTUnit::getPCHFile() {
2940 if (!Reader)
2941 return 0;
2942
2943 PCHLocatorInfo Info;
2944 Reader->getModuleManager().visit(PCHLocator, &Info);
2945 if (Info.Mod)
2946 return Info.Mod->File;
2947
2948 return 0;
2949}
2950
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002951bool ASTUnit::isModuleFile() {
2952 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2953}
2954
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002955void ASTUnit::PreambleData::countLines() const {
2956 NumLines = 0;
2957 if (empty())
2958 return;
2959
2960 for (std::vector<char>::const_iterator
2961 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2962 if (*I == '\n')
2963 ++NumLines;
2964 }
2965 if (Buffer.back() != '\n')
2966 ++NumLines;
2967}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002968
2969#ifndef NDEBUG
2970ASTUnit::ConcurrencyState::ConcurrencyState() {
2971 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2972}
2973
2974ASTUnit::ConcurrencyState::~ConcurrencyState() {
2975 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2976}
2977
2978void ASTUnit::ConcurrencyState::start() {
2979 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2980 assert(acquired && "Concurrent access to ASTUnit!");
2981}
2982
2983void ASTUnit::ConcurrencyState::finish() {
2984 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2985}
2986
2987#else // NDEBUG
2988
Alp Tokerb159c132013-11-22 07:49:39 +00002989ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002990ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2991void ASTUnit::ConcurrencyState::start() {}
2992void ASTUnit::ConcurrencyState::finish() {}
2993
2994#endif