blob: d617b368065c0e8801645ef5dadbb72e6cbbd8bc [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Ben Langmuir090610d32014-02-19 00:10:30 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000039#include "llvm/Support/Atomic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/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));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000713
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000714 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000715
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000716 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
717 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000718
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000720
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000721 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000722 unsigned Counter;
723
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000724 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000725
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000726 AST->PP = new Preprocessor(PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +0000727 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor83297df2011-09-01 23:39:15 +0000728 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
729 *AST,
730 /*IILookup=*/0,
731 /*OwnsHeaderSearch=*/false,
732 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000733 Preprocessor &PP = *AST->PP;
734
735 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
736 AST->getSourceManager(),
737 /*Target=*/0,
738 PP.getIdentifierTable(),
739 PP.getSelectorTable(),
740 PP.getBuiltinInfo(),
741 /* size_reserve = */0,
742 /*DelayInitialization=*/true);
743 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000744
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000745 bool disableValid = false;
746 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
747 disableValid = true;
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000748 Reader.reset(new ASTReader(PP, Context,
749 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000750 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000751 AllowPCHWithCompilerErrors));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000752
753 // Recover resources if we crash before exiting this method.
754 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
755 ReaderCleanup(Reader.get());
756
Douglas Gregore8bbc122011-09-02 00:18:52 +0000757 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000758 AST->ASTFileLangOpts,
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000759 AST->TargetOpts, AST->Target,
Douglas Gregord02437c2012-10-25 00:09:28 +0000760 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000761
Douglas Gregor4b29c162012-10-22 23:51:00 +0000762 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000763 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000764 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000765 break;
Mike Stump11289f42009-09-09 15:08:12 +0000766
Sebastian Redl2c499f62010-08-18 23:56:43 +0000767 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000768 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000769 case ASTReader::OutOfDate:
770 case ASTReader::VersionMismatch:
771 case ASTReader::ConfigurationMismatch:
772 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000773 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000774 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Daniel Dunbara8a50932009-12-02 08:44:16 +0000777 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
778
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000779 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000780
Sebastian Redl2c499f62010-08-18 23:56:43 +0000781 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000782 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000783 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000784 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000785 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000786
787 // Unregister the cleanup for ASTReader. It will get cleaned up
788 // by the ASTUnit cleanup.
789 ReaderCleanup.unregister();
790
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000791 Context.setExternalSource(Source);
792
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000793 // Create an AST consumer, even though it isn't used.
794 AST->Consumer.reset(new ASTConsumer);
795
Sebastian Redl2c499f62010-08-18 23:56:43 +0000796 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000797 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
798 AST->TheSema->Initialize();
799 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000800 AST->Reader = ReaderPtr;
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000801
Douglas Gregor6b930962013-05-03 22:58:43 +0000802 // Tell the diagnostic client that we have started a source file.
803 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
804
Mike Stump11289f42009-09-09 15:08:12 +0000805 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000806}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000807
808namespace {
809
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000810/// \brief Preprocessor callback class that updates a hash value with the names
811/// of all macros that have been defined by the translation unit.
812class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
813 unsigned &Hash;
814
815public:
816 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
817
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000818 virtual void MacroDefined(const Token &MacroNameTok,
819 const MacroDirective *MD) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000820 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
821 }
822};
823
824/// \brief Add the given declaration to the hash of all top-level entities.
825void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
826 if (!D)
827 return;
828
829 DeclContext *DC = D->getDeclContext();
830 if (!DC)
831 return;
832
833 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
834 return;
835
836 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000837 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
838 // For an unscoped enum include the enumerators in the hash since they
839 // enter the top-level namespace.
840 if (!EnumD->isScoped()) {
841 for (EnumDecl::enumerator_iterator EI = EnumD->enumerator_begin(),
842 EE = EnumD->enumerator_end(); EI != EE; ++EI) {
843 if ((*EI)->getIdentifier())
844 Hash = llvm::HashString((*EI)->getIdentifier()->getName(), Hash);
845 }
846 }
847 }
848
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000849 if (ND->getIdentifier())
850 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
851 else if (DeclarationName Name = ND->getDeclName()) {
852 std::string NameStr = Name.getAsString();
853 Hash = llvm::HashString(NameStr, Hash);
854 }
855 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000856 }
857
858 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
859 if (Module *Mod = ImportD->getImportedModule()) {
860 std::string ModName = Mod->getFullModuleName();
861 Hash = llvm::HashString(ModName, Hash);
862 }
863 return;
864 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000865}
866
Daniel Dunbar644dca02009-12-04 08:17:33 +0000867class TopLevelDeclTrackerConsumer : public ASTConsumer {
868 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000869 unsigned &Hash;
870
Daniel Dunbar644dca02009-12-04 08:17:33 +0000871public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000872 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
873 : Unit(_Unit), Hash(Hash) {
874 Hash = 0;
875 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000876
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000877 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000878 if (!D)
879 return;
880
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000881 // FIXME: Currently ObjC method declarations are incorrectly being
882 // reported as top-level declarations, even though their DeclContext
883 // is the containing ObjC @interface/@implementation. This is a
884 // fundamental problem in the parser right now.
885 if (isa<ObjCMethodDecl>(D))
886 return;
887
888 AddTopLevelDeclarationToHash(D, Hash);
889 Unit.addTopLevelDecl(D);
890
891 handleFileLevelDecl(D);
892 }
893
894 void handleFileLevelDecl(Decl *D) {
895 Unit.addFileLevelDecl(D);
896 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
897 for (NamespaceDecl::decl_iterator
898 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
899 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000900 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000901 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000902
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000903 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000904 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
905 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000906 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000907 }
908
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000909 // We're not interested in "interesting" decls.
910 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000911
912 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
913 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
914 handleTopLevelDecl(*it);
915 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000916
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000917 virtual ASTMutationListener *GetASTMutationListener() {
918 return Unit.getASTMutationListener();
919 }
920
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000921 virtual ASTDeserializationListener *GetASTDeserializationListener() {
922 return Unit.getDeserializationListener();
923 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000924};
925
926class TopLevelDeclTrackerAction : public ASTFrontendAction {
927public:
928 ASTUnit &Unit;
929
Daniel Dunbar764c0822009-12-01 09:51:01 +0000930 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000931 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000932 CI.getPreprocessor().addPPCallbacks(
933 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
934 return new TopLevelDeclTrackerConsumer(Unit,
935 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000936 }
937
938public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000939 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
940
Daniel Dunbar764c0822009-12-01 09:51:01 +0000941 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000942 virtual TranslationUnitKind getTranslationUnitKind() {
943 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000944 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000945};
946
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000947class PrecompilePreambleAction : public ASTFrontendAction {
948 ASTUnit &Unit;
949 bool HasEmittedPreamblePCH;
950
951public:
952 explicit PrecompilePreambleAction(ASTUnit &Unit)
953 : Unit(Unit), HasEmittedPreamblePCH(false) {}
954
955 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
956 StringRef InFile);
957 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
958 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
959 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
960
961 virtual bool hasCodeCompletionSupport() const { return false; }
962 virtual bool hasASTFileSupport() const { return false; }
963 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
964};
965
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000966class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000967 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000968 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000969 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000970 PrecompilePreambleAction *Action;
971
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000972public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000973 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
974 const Preprocessor &PP, StringRef isysroot,
975 raw_ostream *Out)
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000976 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000977 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000978 Hash = 0;
979 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000980
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000981 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000982 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
983 Decl *D = *it;
984 // FIXME: Currently ObjC method declarations are incorrectly being
985 // reported as top-level declarations, even though their DeclContext
986 // is the containing ObjC @interface/@implementation. This is a
987 // fundamental problem in the parser right now.
988 if (isa<ObjCMethodDecl>(D))
989 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000990 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000991 TopLevelDecls.push_back(D);
992 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000993 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000994 }
995
996 virtual void HandleTranslationUnit(ASTContext &Ctx) {
997 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000998 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000999 // Translate the top-level declarations we captured during
1000 // parsing into declaration IDs in the precompiled
1001 // preamble. This will allow us to deserialize those top-level
1002 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00001003 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
1004 Decl *D = TopLevelDecls[I];
1005 // Invalid top-level decls may not have been serialized.
1006 if (D->isInvalidDecl())
1007 continue;
1008 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
1009 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001010
1011 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001012 }
1013 }
1014};
1015
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001016}
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001017
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001018ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1019 StringRef InFile) {
1020 std::string Sysroot;
1021 std::string OutputFile;
1022 raw_ostream *OS = 0;
1023 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1024 OutputFile, OS))
1025 return 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001026
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001027 if (!CI.getFrontendOpts().RelocatablePCH)
1028 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001029
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001030 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1031 Unit.getCurrentTopLevelHashValue()));
1032 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1033 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +00001034}
1035
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001036static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1037 return StoredDiag.getLocation().isValid();
1038}
1039
1040static void
1041checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001042 // Get rid of stored diagnostics except the ones from the driver which do not
1043 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001044 StoredDiags.erase(
1045 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1046 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001047}
1048
1049static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1050 StoredDiagnostics,
1051 SourceManager &SM) {
1052 // The stored diagnostic has the old source manager in it; update
1053 // the locations to refer into the new source manager. Since we've
1054 // been careful to make sure that the source manager's state
1055 // before and after are identical, so that we can reuse the source
1056 // location itself.
1057 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1058 if (StoredDiagnostics[I].getLocation().isValid()) {
1059 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1060 StoredDiagnostics[I].setLocation(Loc);
1061 }
1062 }
1063}
1064
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001065/// Parse the source file into a translation unit using the given compiler
1066/// invocation, replacing the current translation unit.
1067///
1068/// \returns True if a failure occurred that causes the ASTUnit not to
1069/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001070bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001071 delete SavedMainFileBuffer;
1072 SavedMainFileBuffer = 0;
1073
Ted Kremenek5e14d392011-03-21 18:40:17 +00001074 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001075 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001076 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001077 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001078
Daniel Dunbar764c0822009-12-01 09:51:01 +00001079 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001080 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001081
1082 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001083 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1084 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001085
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001086 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001087 CCInvocation(new CompilerInvocation(*Invocation));
1088
1089 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001090 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001091
Douglas Gregor8e984da2010-08-04 16:47:14 +00001092 // Set up diagnostics, capturing any diagnostics that would
1093 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001094 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001095
Daniel Dunbar764c0822009-12-01 09:51:01 +00001096 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001097 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001098 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001100 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001101 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001102 }
1103
Daniel Dunbar764c0822009-12-01 09:51:01 +00001104 // Inform the target of the language options.
1105 //
1106 // FIXME: We shouldn't need to do this, the target should be immutable once
1107 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001108 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001109
Ted Kremenek84de4a12011-03-21 18:40:07 +00001110 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001111 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001112 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001113 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001114 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001115 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001116
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001117 // Configure the various subsystems.
1118 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001119 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001120 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001121 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001122 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1123 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001124 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001125 Ctx = 0;
1126 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001127 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001128
1129 // Clear out old caches and data.
1130 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001131 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001132 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001133
Douglas Gregor7b02b582010-08-20 00:02:33 +00001134 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001135 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001136 TopLevelDeclsInPreamble.clear();
1137 }
1138
Daniel Dunbar764c0822009-12-01 09:51:01 +00001139 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001140 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001141
Daniel Dunbar764c0822009-12-01 09:51:01 +00001142 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001143 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001144
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001145 // If the main file has been overridden due to the use of a preamble,
1146 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001147 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001148 if (OverrideMainBuffer) {
1149 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1150 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1151 PreprocessorOpts.PrecompiledPreambleBytes.second
1152 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001153 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001154 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001155
Douglas Gregord9a30af2010-08-02 20:51:39 +00001156 // The stored diagnostic has the old source manager in it; update
1157 // the locations to refer into the new source manager. Since we've
1158 // been careful to make sure that the source manager's state
1159 // before and after are identical, so that we can reuse the source
1160 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001161 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001162
1163 // Keep track of the override buffer;
1164 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001165 }
1166
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001167 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001168 new TopLevelDeclTrackerAction(*this));
1169
1170 // Recover resources if we crash before exiting this method.
1171 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1172 ActCleanup(Act.get());
1173
Douglas Gregor32fbe312012-01-20 16:28:04 +00001174 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001175 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001176
1177 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001178 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001179 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1180 getSourceManager(), PreambleDiagnostics,
1181 StoredDiagnostics);
1182 }
1183
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001184 if (!Act->Execute())
1185 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001186
1187 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001188
Daniel Dunbar644dca02009-12-04 08:17:33 +00001189 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001190
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001191 FailedParseDiagnostics.clear();
1192
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001193 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001194
Daniel Dunbar764c0822009-12-01 09:51:01 +00001195error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001196 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001197 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001198 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001199 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001200 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001201
1202 // Keep the ownership of the data in the ASTUnit because the client may
1203 // want to see the diagnostics.
1204 transferASTDataFromCompilerInstance(*Clang);
1205 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001206 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001207 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001208 return true;
1209}
1210
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001211/// \brief Simple function to retrieve a path for a preamble precompiled header.
1212static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001213 // FIXME: This is a hack so that we can override the preamble file during
1214 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001215 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001216 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1217 if (TmpFile)
1218 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001219
1220 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001221 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001222
1223 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001224}
1225
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001226/// \brief Compute the preamble for the main file, providing the source buffer
1227/// that corresponds to the main file along with a pair (bytes, start-of-line)
1228/// that describes the preamble.
1229std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001230ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1231 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001232 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001233 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001234 CreatedBuffer = false;
1235
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236 // Try to determine if the main file has been remapped, either from the
1237 // command line (to another file) or directly through the compiler invocation
1238 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001239 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001240 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001241 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001242 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001243 // Check whether there is a file-file remapping of the main file
1244 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001245 M = PreprocessorOpts.remapped_file_begin(),
1246 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001247 M != E;
1248 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001249 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001250 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001251 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001252 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001253 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001254 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001255 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001256 CreatedBuffer = false;
1257 }
1258
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001259 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001260 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001261 return std::make_pair((llvm::MemoryBuffer*)0,
1262 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001264 }
1265 }
1266 }
1267
1268 // Check whether there is a file-buffer remapping. It supercedes the
1269 // file-file remapping.
1270 for (PreprocessorOptions::remapped_file_buffer_iterator
1271 M = PreprocessorOpts.remapped_file_buffer_begin(),
1272 E = PreprocessorOpts.remapped_file_buffer_end();
1273 M != E;
1274 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001275 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001276 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001277 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001278 if (MainFileID == MID) {
1279 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001280 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001281 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001282 CreatedBuffer = false;
1283 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001284
Douglas Gregor4dde7492010-07-23 23:58:40 +00001285 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001286 }
1287 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001288 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001289 }
1290
1291 // If the main source file was not remapped, load it now.
1292 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001293 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001294 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001295 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001296
1297 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001298 }
1299
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001300 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001301 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001302 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001303}
1304
Douglas Gregor6481ef12010-07-24 00:38:13 +00001305static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001306 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001307 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001308 llvm::MemoryBuffer *Result
1309 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1310 memcpy(const_cast<char*>(Result->getBufferStart()),
1311 Old->getBufferStart(), Old->getBufferSize());
1312 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001313 ' ', NewSize - Old->getBufferSize() - 1);
1314 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001315
Douglas Gregor6481ef12010-07-24 00:38:13 +00001316 return Result;
1317}
1318
Dmitri Gribenko47652522013-12-20 00:16:25 +00001319ASTUnit::PreambleFileHash
1320ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1321 PreambleFileHash Result;
1322 Result.Size = Size;
1323 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001324 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001325 return Result;
1326}
1327
1328ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1329 const llvm::MemoryBuffer *Buffer) {
1330 PreambleFileHash Result;
1331 Result.Size = Buffer->getBufferSize();
1332 Result.ModTime = 0;
1333
1334 llvm::MD5 MD5Ctx;
1335 MD5Ctx.update(Buffer->getBuffer().data());
1336 MD5Ctx.final(Result.MD5);
1337
1338 return Result;
1339}
1340
1341namespace clang {
1342bool operator==(const ASTUnit::PreambleFileHash &LHS,
1343 const ASTUnit::PreambleFileHash &RHS) {
1344 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001345 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001346}
1347} // namespace clang
1348
Douglas Gregor4dde7492010-07-23 23:58:40 +00001349/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1350/// the source file.
1351///
1352/// This routine will compute the preamble of the main source file. If a
1353/// non-trivial preamble is found, it will precompile that preamble into a
1354/// precompiled header so that the precompiled preamble can be used to reduce
1355/// reparsing time. If a precompiled preamble has already been constructed,
1356/// this routine will determine if it is still valid and, if so, avoid
1357/// rebuilding the precompiled preamble.
1358///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001359/// \param AllowRebuild When true (the default), this routine is
1360/// allowed to rebuild the precompiled preamble if it is found to be
1361/// out-of-date.
1362///
1363/// \param MaxLines When non-zero, the maximum number of lines that
1364/// can occur within the preamble.
1365///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001366/// \returns If the precompiled preamble can be used, returns a newly-allocated
1367/// buffer that should be used in place of the main file when doing so.
1368/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001369llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001370 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001371 bool AllowRebuild,
1372 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001373
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001374 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001375 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1376 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001377 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001378 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001379
1380 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001381 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001382 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001383
Douglas Gregor925296b2011-07-19 16:10:42 +00001384 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001385 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001386 if (CreatedPreambleBuffer)
1387 OwnedPreambleBuffer.reset(NewPreamble.first);
1388
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001389 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001390 // We couldn't find a preamble in the main source. Clear out the current
1391 // preamble, if we have one. It's obviously no good any more.
1392 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001393 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001394
1395 // The next time we actually see a preamble, precompile it.
1396 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001397 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001398 }
1399
1400 if (!Preamble.empty()) {
1401 // We've previously computed a preamble. Check whether we have the same
1402 // preamble now that we did before, and that there's enough space in
1403 // the main-file buffer within the precompiled preamble to fit the
1404 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001405 if (Preamble.size() == NewPreamble.second.first &&
1406 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001407 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001408 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001409 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001410 // The preamble has not changed. We may be able to re-use the precompiled
1411 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001412
Douglas Gregor0e119552010-07-31 00:40:00 +00001413 // Check that none of the files used by the preamble have changed.
1414 bool AnyFileChanged = false;
1415
1416 // First, make a record of those files that have been overridden via
1417 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001418 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregor0e119552010-07-31 00:40:00 +00001419 for (PreprocessorOptions::remapped_file_iterator
1420 R = PreprocessorOpts.remapped_file_begin(),
1421 REnd = PreprocessorOpts.remapped_file_end();
1422 !AnyFileChanged && R != REnd;
1423 ++R) {
Ben Langmuir090610d32014-02-19 00:10:30 +00001424 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001425 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001426 // If we can't stat the file we're remapping to, assume that something
1427 // horrible happened.
1428 AnyFileChanged = true;
1429 break;
1430 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001431
Dmitri Gribenko47652522013-12-20 00:16:25 +00001432 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001433 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001434 }
1435 for (PreprocessorOptions::remapped_file_buffer_iterator
1436 R = PreprocessorOpts.remapped_file_buffer_begin(),
1437 REnd = PreprocessorOpts.remapped_file_buffer_end();
1438 !AnyFileChanged && R != REnd;
1439 ++R) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001440 OverriddenFiles[R->first] =
1441 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001442 }
1443
1444 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001445 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001446 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1447 !AnyFileChanged && F != FEnd;
1448 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001449 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001450 = OverriddenFiles.find(F->first());
1451 if (Overridden != OverriddenFiles.end()) {
1452 // This file was remapped; check whether the newly-mapped file
1453 // matches up with the previous mapping.
1454 if (Overridden->second != F->second)
1455 AnyFileChanged = true;
1456 continue;
1457 }
1458
1459 // The file was not remapped; check whether it has changed on disk.
Ben Langmuir090610d32014-02-19 00:10:30 +00001460 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001461 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001462 // If we can't stat the file, assume that something horrible happened.
1463 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001464 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001465 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001466 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001467 AnyFileChanged = true;
1468 }
1469
1470 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001471 // Okay! We can re-use the precompiled preamble.
1472
1473 // Set the state of the diagnostic object to mimic its state
1474 // after parsing the preamble.
1475 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001476 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001477 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001478 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001479
1480 // Create a version of the main file buffer that is padded to
1481 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001482 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001483 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001484 FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001485 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001486 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001487
1488 // If we aren't allowed to rebuild the precompiled preamble, just
1489 // return now.
1490 if (!AllowRebuild)
1491 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001492
Douglas Gregor4dde7492010-07-23 23:58:40 +00001493 // We can't reuse the previously-computed preamble. Build a new one.
1494 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001495 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001496 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001497 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001498 } else if (!AllowRebuild) {
1499 // We aren't allowed to rebuild the precompiled preamble; just
1500 // return now.
1501 return 0;
1502 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001503
1504 // If the preamble rebuild counter > 1, it's because we previously
1505 // failed to build a preamble and we're not yet ready to try
1506 // again. Decrement the counter and return a failure.
1507 if (PreambleRebuildCounter > 1) {
1508 --PreambleRebuildCounter;
1509 return 0;
1510 }
1511
Douglas Gregore10f0e52010-09-11 17:56:52 +00001512 // Create a temporary file for the precompiled preamble. In rare
1513 // circumstances, this can fail.
1514 std::string PreamblePCHPath = GetPreamblePCHPath();
1515 if (PreamblePCHPath.empty()) {
1516 // Try again next time.
1517 PreambleRebuildCounter = 1;
1518 return 0;
1519 }
1520
Douglas Gregor4dde7492010-07-23 23:58:40 +00001521 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001522 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001523 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001524
1525 // Create a new buffer that stores the preamble. The buffer also contains
1526 // extra space for the original contents of the file (which will be present
1527 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001528 // grows.
1529 PreambleReservedSize = NewPreamble.first->getBufferSize();
1530 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001531 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001532 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001533 PreambleReservedSize *= 2;
1534
Douglas Gregord9a30af2010-08-02 20:51:39 +00001535 // Save the preamble text for later; we'll need to compare against it for
1536 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001537 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001538 Preamble.assign(FileMgr->getFile(MainFilename),
1539 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001540 NewPreamble.first->getBufferStart()
1541 + NewPreamble.second.first);
1542 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1543
Douglas Gregora0734c52010-08-19 01:33:06 +00001544 delete PreambleBuffer;
1545 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001546 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001547 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001548 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001549 NewPreamble.first->getBufferStart(), Preamble.size());
1550 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001551 ' ', PreambleReservedSize - Preamble.size() - 1);
1552 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001553
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001555 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1556 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1557
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001558 // Tell the compiler invocation to generate a temporary precompiled header.
1559 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001560 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001561 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001562 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1563 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001564
1565 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001566 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001567
1568 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001569 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1570 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001571
Douglas Gregor3cc15812011-07-01 18:22:13 +00001572 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001573 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001574
Douglas Gregor8e984da2010-08-04 16:47:14 +00001575 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001576 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001577
1578 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001579 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001580 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001581 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001582 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001583 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001584 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001585 PreprocessorOpts.eraseRemappedFile(
1586 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001587 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001588 }
1589
1590 // Inform the target of the language options.
1591 //
1592 // FIXME: We shouldn't need to do this, the target should be immutable once
1593 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001594 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001595
Ted Kremenek84de4a12011-03-21 18:40:07 +00001596 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001597 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001598 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001599 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001600 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001601 "IR inputs not support here!");
1602
1603 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001604 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001605 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001606 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001607 TopLevelDecls.clear();
1608 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001609
1610 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001611 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001612
1613 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001614 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001615 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001616
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001617 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001618 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001619 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001620 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001621 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001622 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001623 PreprocessorOpts.eraseRemappedFile(
1624 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001625 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001626 }
1627
1628 Act->Execute();
1629 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001630
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001631 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001632 // The preamble PCH failed (e.g. there was a module loading fatal error),
1633 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001634 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001635 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001636 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001637 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001638 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001639 PreprocessorOpts.eraseRemappedFile(
1640 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001641 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001642 }
1643
Douglas Gregor925296b2011-07-19 16:10:42 +00001644 // Transfer any diagnostics generated when parsing the preamble into the set
1645 // of preamble diagnostics.
1646 PreambleDiagnostics.clear();
1647 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001648 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001649 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001650
Douglas Gregor4dde7492010-07-23 23:58:40 +00001651 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001652 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001653 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001654
1655 // Keep track of all of the files that the source manager knows about,
1656 // so we can verify whether they have changed or not.
1657 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001658 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001659 const llvm::MemoryBuffer *MainFileBuffer
1660 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1661 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1662 FEnd = SourceMgr.fileinfo_end();
1663 F != FEnd;
1664 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001665 const FileEntry *File = F->second->OrigEntry;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001666 if (!File)
Douglas Gregor0e119552010-07-31 00:40:00 +00001667 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001668 const llvm::MemoryBuffer *Buffer = F->second->getRawBuffer();
1669 if (Buffer == MainFileBuffer)
1670 continue;
1671
1672 if (time_t ModTime = File->getModificationTime()) {
1673 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1674 F->second->getSize(), ModTime);
1675 } else {
1676 assert(F->second->getSize() == Buffer->getBufferSize());
1677 FilesInPreamble[File->getName()] =
1678 PreambleFileHash::createForMemoryBuffer(Buffer);
1679 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001680 }
1681
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001682 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001683 PreprocessorOpts.eraseRemappedFile(
1684 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001685
1686 // If the hash of top-level entities differs from the hash of the top-level
1687 // entities the last time we rebuilt the preamble, clear out the completion
1688 // cache.
1689 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1690 CompletionCacheTopLevelHashValue = 0;
1691 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1692 }
1693
Douglas Gregor6481ef12010-07-24 00:38:13 +00001694 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001695 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001696 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001697}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001698
Douglas Gregore9db88f2010-08-03 19:06:41 +00001699void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1700 std::vector<Decl *> Resolved;
1701 Resolved.reserve(TopLevelDeclsInPreamble.size());
1702 ExternalASTSource &Source = *getASTContext().getExternalSource();
1703 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1704 // Resolve the declaration ID to an actual declaration, possibly
1705 // deserializing the declaration in the process.
1706 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1707 if (D)
1708 Resolved.push_back(D);
1709 }
1710 TopLevelDeclsInPreamble.clear();
1711 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1712}
1713
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001714void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1715 // Steal the created target, context, and preprocessor.
1716 TheSema.reset(CI.takeSema());
1717 Consumer.reset(CI.takeASTConsumer());
1718 Ctx = &CI.getASTContext();
1719 PP = &CI.getPreprocessor();
1720 CI.setSourceManager(0);
1721 CI.setFileManager(0);
1722 Target = &CI.getTarget();
1723 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001724 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001725}
1726
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001727StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001728 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1729 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1730 if (Input.isFile())
1731 return Input.getFile();
1732 else
1733 return Input.getBuffer()->getBufferIdentifier();
1734 }
1735
1736 if (SourceMgr) {
1737 if (const FileEntry *
1738 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1739 return FE->getName();
1740 }
1741
1742 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001743}
1744
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001745StringRef ASTUnit::getASTFileName() const {
1746 if (!isMainFileAST())
1747 return StringRef();
1748
1749 serialization::ModuleFile &
1750 Mod = Reader->getModuleManager().getPrimaryModule();
1751 return Mod.FileName;
1752}
1753
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001754ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001755 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001756 bool CaptureDiagnostics,
1757 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001758 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001759 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001760 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001761 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001762 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001763 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001764 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001765 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1766 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1767 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001768
1769 return AST.take();
1770}
1771
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001772ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001773 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001774 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001775 ASTUnit *Unit,
1776 bool Persistent,
1777 StringRef ResourceFilesPath,
1778 bool OnlyLocalDecls,
1779 bool CaptureDiagnostics,
1780 bool PrecompilePreamble,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001781 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001782 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001783 bool UserFilesAreVolatile,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001784 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001785 assert(CI && "A CompilerInvocation is required");
1786
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001787 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001788 ASTUnit *AST = Unit;
1789 if (!AST) {
1790 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001791 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001792 AST = OwnAST.get();
1793 }
1794
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001795 if (!ResourceFilesPath.empty()) {
1796 // Override the resources path.
1797 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1798 }
1799 AST->OnlyLocalDecls = OnlyLocalDecls;
1800 AST->CaptureDiagnostics = CaptureDiagnostics;
1801 if (PrecompilePreamble)
1802 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001803 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001804 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001805 AST->IncludeBriefCommentsInCodeCompletion
1806 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001807
1808 // Recover resources if we crash before exiting this method.
1809 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001810 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001811 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1812 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001813 DiagCleanup(Diags.getPtr());
1814
1815 // We'll manage file buffers ourselves.
1816 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1817 CI->getFrontendOpts().DisableFree = false;
1818 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1819
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001820 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001821 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001822
1823 // Recover resources if we crash before exiting this method.
1824 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1825 CICleanup(Clang.get());
1826
1827 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001828 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001829
1830 // Set up diagnostics, capturing any diagnostics that would
1831 // otherwise be dropped.
1832 Clang->setDiagnostics(&AST->getDiagnostics());
1833
1834 // Create the target instance.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001835 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001836 &Clang->getTargetOpts()));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001837 if (!Clang->hasTarget())
1838 return 0;
1839
1840 // Inform the target of the language options.
1841 //
1842 // FIXME: We shouldn't need to do this, the target should be immutable once
1843 // created. This complexity should be lifted elsewhere.
1844 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1845
1846 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1847 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001848 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001849 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001850 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001851 "IR inputs not supported here!");
1852
1853 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001854 AST->TheSema.reset();
1855 AST->Ctx = 0;
1856 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001857 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001858
1859 // Create a file manager object to provide access to and cache the filesystem.
1860 Clang->setFileManager(&AST->getFileManager());
1861
1862 // Create the source manager.
1863 Clang->setSourceManager(&AST->getSourceManager());
1864
1865 ASTFrontendAction *Act = Action;
1866
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001867 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001868 if (!Act) {
1869 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1870 Act = TrackerAct.get();
1871 }
1872
1873 // Recover resources if we crash before exiting this method.
1874 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1875 ActCleanup(TrackerAct.get());
1876
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001877 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1878 AST->transferASTDataFromCompilerInstance(*Clang);
1879 if (OwnAST && ErrAST)
1880 ErrAST->swap(OwnAST);
1881
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001882 return 0;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001883 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001884
1885 if (Persistent && !TrackerAct) {
1886 Clang->getPreprocessor().addPPCallbacks(
1887 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1888 std::vector<ASTConsumer*> Consumers;
1889 if (Clang->hasASTConsumer())
1890 Consumers.push_back(Clang->takeASTConsumer());
1891 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1892 AST->getCurrentTopLevelHashValue()));
1893 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1894 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001895 if (!Act->Execute()) {
1896 AST->transferASTDataFromCompilerInstance(*Clang);
1897 if (OwnAST && ErrAST)
1898 ErrAST->swap(OwnAST);
1899
1900 return 0;
1901 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001902
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001903 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001904 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001905
1906 Act->EndSourceFile();
1907
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001908 if (OwnAST)
1909 return OwnAST.take();
1910 else
1911 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001912}
1913
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001914bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1915 if (!Invocation)
1916 return true;
1917
1918 // We'll manage file buffers ourselves.
1919 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1920 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001921 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001922
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001923 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001924 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001925 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001926 OverrideMainBuffer
1927 = getMainBufferWithPrecompiledPreamble(*Invocation);
1928 }
1929
Douglas Gregor16896c42010-10-28 15:44:59 +00001930 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001931 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001932
Ted Kremenek022a4902011-03-22 01:15:24 +00001933 // Recover resources if we crash before exiting this method.
1934 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1935 MemBufferCleanup(OverrideMainBuffer);
1936
Douglas Gregor16896c42010-10-28 15:44:59 +00001937 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001938}
1939
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001940ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001941 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001942 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001943 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001944 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001945 TranslationUnitKind TUKind,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001946 bool CacheCodeCompletionResults,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001947 bool IncludeBriefCommentsInCodeCompletion,
1948 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001949 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001950 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001951 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001952 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001953 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001954 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001955 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001956 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001957 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001958 AST->IncludeBriefCommentsInCodeCompletion
1959 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001960 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001961 AST->FileSystemOpts = CI->getFileSystemOpts();
1962 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001963 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001964
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001965 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001966 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1967 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001968 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1969 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001970 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001971
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001972 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001973}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001974
1975ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1976 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001977 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001978 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001979 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001980 bool CaptureDiagnostics,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001981 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001982 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001983 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001984 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001985 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001986 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001987 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6e922512012-04-12 10:11:59 +00001988 bool SkipFunctionBodies,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001989 bool UserFilesAreVolatile,
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001990 bool ForSerialization,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001991 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001992 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001993 // No diagnostics engine was provided, so create our own diagnostics object
1994 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00001995 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00001996 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001997
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001998 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001999
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002000 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002001
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002002 {
Douglas Gregor925296b2011-07-19 16:10:42 +00002003
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002004 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002005 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00002006
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00002007 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002008 llvm::makeArrayRef(ArgBegin, ArgEnd),
2009 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00002010 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00002011 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002012 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002013
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002014 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002015 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002016 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2017 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002018 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002019 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2020 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2021 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002022
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002023 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002024 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002025
Erik Verbruggen6e922512012-04-12 10:11:59 +00002026 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2027
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002028 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002029 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002030 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002031 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002032 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00002033 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002034 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00002035 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002036 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002037 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002038 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002039 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002040 AST->IncludeBriefCommentsInCodeCompletion
2041 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002042 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002043 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002044 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002045 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002046 if (ForSerialization)
2047 AST->WriterData.reset(new ASTWriterData());
Ted Kremenek25047602011-11-17 23:01:17 +00002048 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002049
2050 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002051 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2052 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002053
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002054 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2055 // Some error occurred, if caller wants to examine diagnostics, pass it the
2056 // ASTUnit.
2057 if (ErrAST) {
2058 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2059 ErrAST->swap(AST);
2060 }
2061 return 0;
2062 }
2063
2064 return AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002065}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002066
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002067bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002068 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002069 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002070
2071 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002072
Douglas Gregor16896c42010-10-28 15:44:59 +00002073 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002074 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002075
Douglas Gregor0e119552010-07-31 00:40:00 +00002076 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002077 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2078 for (PreprocessorOptions::remapped_file_buffer_iterator
2079 R = PPOpts.remapped_file_buffer_begin(),
2080 REnd = PPOpts.remapped_file_buffer_end();
2081 R != REnd;
2082 ++R) {
2083 delete R->second;
2084 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002085 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002086 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002087 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2088 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002089 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002090
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002091 // If we have a preamble file lying around, or if we might try to
2092 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00002093 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002094 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002095 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002096
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002097 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002098 getDiagnostics().Reset();
2099 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002100 if (OverrideMainBuffer)
2101 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002102
Douglas Gregor4dde7492010-07-23 23:58:40 +00002103 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002104 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002105
2106 // If we're caching global code-completion results, and the top-level
2107 // declarations have changed, clear out the code-completion cache.
2108 if (!Result && ShouldCacheCodeCompletionResults &&
2109 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2110 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002111
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002112 // We now need to clear out the completion info related to this translation
2113 // unit; it'll be recreated if necessary.
2114 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002115
Douglas Gregor4dde7492010-07-23 23:58:40 +00002116 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002117}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002118
Douglas Gregorb14904c2010-08-13 22:48:40 +00002119//----------------------------------------------------------------------------//
2120// Code completion
2121//----------------------------------------------------------------------------//
2122
2123namespace {
2124 /// \brief Code completion consumer that combines the cached code-completion
2125 /// results from an ASTUnit with the code-completion results provided to it,
2126 /// then passes the result on to
2127 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002128 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002129 ASTUnit &AST;
2130 CodeCompleteConsumer &Next;
2131
2132 public:
2133 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002134 const CodeCompleteOptions &CodeCompleteOpts)
2135 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2136 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002137 {
2138 // Compute the set of contexts in which we will look when we don't have
2139 // any information about the specific context.
2140 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002141 = (1LL << CodeCompletionContext::CCC_TopLevel)
2142 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2143 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2144 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2145 | (1LL << CodeCompletionContext::CCC_Statement)
2146 | (1LL << CodeCompletionContext::CCC_Expression)
2147 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2148 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2149 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2150 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2151 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2152 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2153 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002154
David Blaikiebbafb8a2012-03-11 07:00:24 +00002155 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002156 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2157 | (1LL << CodeCompletionContext::CCC_UnionTag)
2158 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002159 }
2160
2161 virtual void ProcessCodeCompleteResults(Sema &S,
2162 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002163 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002164 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002165
2166 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2167 OverloadCandidate *Candidates,
2168 unsigned NumCandidates) {
2169 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2170 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002171
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002172 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002173 return Next.getAllocator();
2174 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002175
2176 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2177 return Next.getCodeCompletionTUInfo();
2178 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002179 };
2180}
Douglas Gregord46cf182010-08-16 20:01:48 +00002181
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002182/// \brief Helper function that computes which global names are hidden by the
2183/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002184static void CalculateHiddenNames(const CodeCompletionContext &Context,
2185 CodeCompletionResult *Results,
2186 unsigned NumResults,
2187 ASTContext &Ctx,
2188 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002189 bool OnlyTagNames = false;
2190 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002191 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002192 case CodeCompletionContext::CCC_TopLevel:
2193 case CodeCompletionContext::CCC_ObjCInterface:
2194 case CodeCompletionContext::CCC_ObjCImplementation:
2195 case CodeCompletionContext::CCC_ObjCIvarList:
2196 case CodeCompletionContext::CCC_ClassStructUnion:
2197 case CodeCompletionContext::CCC_Statement:
2198 case CodeCompletionContext::CCC_Expression:
2199 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002200 case CodeCompletionContext::CCC_DotMemberAccess:
2201 case CodeCompletionContext::CCC_ArrowMemberAccess:
2202 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002203 case CodeCompletionContext::CCC_Namespace:
2204 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002205 case CodeCompletionContext::CCC_Name:
2206 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002207 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002208 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002209 break;
2210
2211 case CodeCompletionContext::CCC_EnumTag:
2212 case CodeCompletionContext::CCC_UnionTag:
2213 case CodeCompletionContext::CCC_ClassOrStructTag:
2214 OnlyTagNames = true;
2215 break;
2216
2217 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002218 case CodeCompletionContext::CCC_MacroName:
2219 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002220 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002221 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002222 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002223 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002224 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002225 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002226 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002227 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2228 case CodeCompletionContext::CCC_ObjCClassMessage:
2229 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002230 // We're looking for nothing, or we're looking for names that cannot
2231 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002232 return;
2233 }
2234
John McCall276321a2010-08-25 06:19:51 +00002235 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002236 for (unsigned I = 0; I != NumResults; ++I) {
2237 if (Results[I].Kind != Result::RK_Declaration)
2238 continue;
2239
2240 unsigned IDNS
2241 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2242
2243 bool Hiding = false;
2244 if (OnlyTagNames)
2245 Hiding = (IDNS & Decl::IDNS_Tag);
2246 else {
2247 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002248 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2249 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002250 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002251 HiddenIDNS |= Decl::IDNS_Tag;
2252 Hiding = (IDNS & HiddenIDNS);
2253 }
2254
2255 if (!Hiding)
2256 continue;
2257
2258 DeclarationName Name = Results[I].Declaration->getDeclName();
2259 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2260 HiddenNames.insert(Identifier->getName());
2261 else
2262 HiddenNames.insert(Name.getAsString());
2263 }
2264}
2265
2266
Douglas Gregord46cf182010-08-16 20:01:48 +00002267void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2268 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002269 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002270 unsigned NumResults) {
2271 // Merge the results we were given with the results we cached.
2272 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002273 uint64_t InContexts =
2274 Context.getKind() == CodeCompletionContext::CCC_Recovery
2275 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002276 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002277 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002278 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002279 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002280 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002281 C = AST.cached_completion_begin(),
2282 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002283 C != CEnd; ++C) {
2284 // If the context we are in matches any of the contexts we are
2285 // interested in, we'll add this result.
2286 if ((C->ShowInContexts & InContexts) == 0)
2287 continue;
2288
2289 // If we haven't added any results previously, do so now.
2290 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002291 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2292 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002293 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2294 AddedResult = true;
2295 }
2296
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002297 // Determine whether this global completion result is hidden by a local
2298 // completion result. If so, skip it.
2299 if (C->Kind != CXCursor_MacroDefinition &&
2300 HiddenNames.count(C->Completion->getTypedText()))
2301 continue;
2302
Douglas Gregord46cf182010-08-16 20:01:48 +00002303 // Adjust priority based on similar type classes.
2304 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002305 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002306 if (!Context.getPreferredType().isNull()) {
2307 if (C->Kind == CXCursor_MacroDefinition) {
2308 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002310 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002311 } else if (C->Type) {
2312 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002313 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002314 Context.getPreferredType().getUnqualifiedType());
2315 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2316 if (ExpectedSTC == C->TypeClass) {
2317 // We know this type is similar; check for an exact match.
2318 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002319 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002320 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002321 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002322 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2323 Priority /= CCF_ExactTypeMatch;
2324 else
2325 Priority /= CCF_SimilarTypeMatch;
2326 }
2327 }
2328 }
2329
Douglas Gregor12785102010-08-24 20:21:13 +00002330 // Adjust the completion string, if required.
2331 if (C->Kind == CXCursor_MacroDefinition &&
2332 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2333 // Create a new code-completion string that just contains the
2334 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002335 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2336 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002337 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002338 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002339 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002340 }
2341
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002342 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002343 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002344 }
2345
2346 // If we did not add any cached completion results, just forward the
2347 // results we were given to the next consumer.
2348 if (!AddedResult) {
2349 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2350 return;
2351 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002352
Douglas Gregord46cf182010-08-16 20:01:48 +00002353 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2354 AllResults.size());
2355}
2356
2357
2358
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002359void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002360 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002361 bool IncludeMacros,
2362 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002363 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002364 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002365 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002366 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002367 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2368 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002369 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002370 return;
2371
Douglas Gregor16896c42010-10-28 15:44:59 +00002372 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002373 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002374 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002375
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002376 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002377 CCInvocation(new CompilerInvocation(*Invocation));
2378
2379 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002380 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002381 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002382
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002383 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2384 CachedCompletionResults.empty();
2385 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2386 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2387 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2388
2389 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2390
Douglas Gregor8e984da2010-08-04 16:47:14 +00002391 FrontendOpts.CodeCompletionAt.FileName = File;
2392 FrontendOpts.CodeCompletionAt.Line = Line;
2393 FrontendOpts.CodeCompletionAt.Column = Column;
2394
2395 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002396 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002397
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002398 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002399
2400 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002401 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2402 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002403
Ted Kremenek5e14d392011-03-21 18:40:17 +00002404 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002405 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002406
2407 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002408 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002409 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002410 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002411 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002412 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002413
2414 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002415 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00002416 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002417 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002418 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002419 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002420 }
2421
2422 // Inform the target of the language options.
2423 //
2424 // FIXME: We shouldn't need to do this, the target should be immutable once
2425 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002426 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002427
Ted Kremenek84de4a12011-03-21 18:40:07 +00002428 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002429 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002430 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002431 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002432 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002433 "IR inputs not support here!");
2434
2435
2436 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002437 Clang->setFileManager(&FileMgr);
2438 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002439
2440 // Remap files.
2441 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002442 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002443 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002444 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2445 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002446 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002447 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002448
Douglas Gregorb14904c2010-08-13 22:48:40 +00002449 // Use the code completion consumer we were given, but adding any cached
2450 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002451 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002452 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002453 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002454
Douglas Gregor028d3e42010-08-09 20:45:32 +00002455 // If we have a precompiled preamble, try to use it. We only allow
2456 // the use of the precompiled preamble if we're if the completion
2457 // point is within the main file, after the end of the precompiled
2458 // preamble.
2459 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002460 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002461 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002462 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002463
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002464 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002465 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002466 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002467 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002468 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002469 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002470 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002471 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002472 }
2473 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002474 }
2475
2476 // If the main file has been overridden due to the use of a preamble,
2477 // make that override happen and introduce the preamble.
2478 if (OverrideMainBuffer) {
2479 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2480 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2481 PreprocessorOpts.PrecompiledPreambleBytes.second
2482 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002483 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002484 PreprocessorOpts.DisablePCHValidation = true;
2485
Douglas Gregorb97b6662010-08-20 00:59:43 +00002486 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002487 } else {
2488 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2489 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002490 }
2491
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002492 // Disable the preprocessing record if modules are not enabled.
2493 if (!Clang->getLangOpts().Modules)
2494 PreprocessorOpts.DetailedRecord = false;
Douglas Gregor998caea2011-05-06 16:33:08 +00002495
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002496 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002497 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002498 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002499 Act->Execute();
2500 Act->EndSourceFile();
2501 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002502}
Douglas Gregore9386682010-08-13 05:36:37 +00002503
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002504bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002505 if (HadModuleLoaderFatalFailure)
2506 return true;
2507
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002508 // Write to a temporary file and later rename it to the actual file, to avoid
2509 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002510 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002511 TempPath = File;
2512 TempPath += "-%%%%%%%%";
2513 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002514 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002515 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002516
Douglas Gregore9386682010-08-13 05:36:37 +00002517 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2518 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002519 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002520
2521 serialize(Out);
2522 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002523 if (Out.has_error()) {
2524 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002525 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002526 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002527
Rafael Espindola65e025c2011-12-25 01:18:52 +00002528 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002529 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002530 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002531 }
2532
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002533 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002534}
2535
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002536static bool serializeUnit(ASTWriter &Writer,
2537 SmallVectorImpl<char> &Buffer,
2538 Sema &S,
2539 bool hasErrors,
2540 raw_ostream &OS) {
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00002541 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002542
2543 // Write the generated bitstream to "Out".
2544 if (!Buffer.empty())
2545 OS.write(Buffer.data(), Buffer.size());
2546
2547 return false;
2548}
2549
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002550bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002551 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002552
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002553 if (WriterData)
2554 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2555 getSema(), hasErrors, OS);
2556
Daniel Dunbar9a963862012-02-29 20:31:23 +00002557 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002558 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002559 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002560 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002561}
Douglas Gregor925296b2011-07-19 16:10:42 +00002562
2563typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2564
2565static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2566 unsigned Raw = L.getRawEncoding();
2567 const unsigned MacroBit = 1U << 31;
2568 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2569 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2570}
2571
2572void ASTUnit::TranslateStoredDiagnostics(
2573 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002574 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002575 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002576 const SmallVectorImpl<StoredDiagnostic> &Diags,
2577 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002578 // The stored diagnostic has the old source manager in it; update
2579 // the locations to refer into the new source manager. We also need to remap
2580 // all the locations to the new view. This includes the diag location, any
2581 // associated source ranges, and the source ranges of associated fix-its.
2582 // FIXME: There should be a cleaner way to do this.
2583
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002584 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002585 Result.reserve(Diags.size());
2586 assert(MMan && "Don't have a module manager");
Douglas Gregorde3ef502011-11-30 23:21:26 +00002587 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002588 assert(Mod && "Don't have preamble module");
2589 SLocRemap &Remap = Mod->SLocRemap;
2590 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2591 // Rebuild the StoredDiagnostic.
2592 const StoredDiagnostic &SD = Diags[I];
2593 SourceLocation L = SD.getLocation();
2594 TranslateSLoc(L, Remap);
2595 FullSourceLoc Loc(L, SrcMgr);
2596
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002597 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002598 Ranges.reserve(SD.range_size());
2599 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2600 E = SD.range_end();
2601 I != E; ++I) {
2602 SourceLocation BL = I->getBegin();
2603 TranslateSLoc(BL, Remap);
2604 SourceLocation EL = I->getEnd();
2605 TranslateSLoc(EL, Remap);
2606 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2607 }
2608
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002609 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002610 FixIts.reserve(SD.fixit_size());
2611 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2612 E = SD.fixit_end();
2613 I != E; ++I) {
2614 FixIts.push_back(FixItHint());
2615 FixItHint &FH = FixIts.back();
2616 FH.CodeToInsert = I->CodeToInsert;
2617 SourceLocation BL = I->RemoveRange.getBegin();
2618 TranslateSLoc(BL, Remap);
2619 SourceLocation EL = I->RemoveRange.getEnd();
2620 TranslateSLoc(EL, Remap);
2621 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2622 I->RemoveRange.isTokenRange());
2623 }
2624
2625 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2626 SD.getMessage(), Loc, Ranges, FixIts));
2627 }
2628 Result.swap(Out);
2629}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002630
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002631void ASTUnit::addFileLevelDecl(Decl *D) {
2632 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002633
2634 // We only care about local declarations.
2635 if (D->isFromASTFile())
2636 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002637
2638 SourceManager &SM = *SourceMgr;
2639 SourceLocation Loc = D->getLocation();
2640 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2641 return;
2642
2643 // We only keep track of the file-level declarations of each file.
2644 if (!D->getLexicalDeclContext()->isFileContext())
2645 return;
2646
2647 SourceLocation FileLoc = SM.getFileLoc(Loc);
2648 assert(SM.isLocalSourceLocation(FileLoc));
2649 FileID FID;
2650 unsigned Offset;
2651 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2652 if (FID.isInvalid())
2653 return;
2654
2655 LocDeclsTy *&Decls = FileDecls[FID];
2656 if (!Decls)
2657 Decls = new LocDeclsTy();
2658
2659 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2660
2661 if (Decls->empty() || Decls->back().first <= Offset) {
2662 Decls->push_back(LocDecl);
2663 return;
2664 }
2665
Benjamin Kramer45025c02013-08-24 13:22:59 +00002666 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2667 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002668
2669 Decls->insert(I, LocDecl);
2670}
2671
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002672void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2673 SmallVectorImpl<Decl *> &Decls) {
2674 if (File.isInvalid())
2675 return;
2676
2677 if (SourceMgr->isLoadedFileID(File)) {
2678 assert(Ctx->getExternalSource() && "No external source!");
2679 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2680 Decls);
2681 }
2682
2683 FileDeclsTy::iterator I = FileDecls.find(File);
2684 if (I == FileDecls.end())
2685 return;
2686
2687 LocDeclsTy &LocDecls = *I->second;
2688 if (LocDecls.empty())
2689 return;
2690
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002691 LocDeclsTy::iterator BeginIt =
2692 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002693 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002694 if (BeginIt != LocDecls.begin())
2695 --BeginIt;
2696
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002697 // If we are pointing at a top-level decl inside an objc container, we need
2698 // to backtrack until we find it otherwise we will fail to report that the
2699 // region overlaps with an objc container.
2700 while (BeginIt != LocDecls.begin() &&
2701 BeginIt->second->isTopLevelDeclInObjCContainer())
2702 --BeginIt;
2703
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002704 LocDeclsTy::iterator EndIt = std::upper_bound(
2705 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002706 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002707 if (EndIt != LocDecls.end())
2708 ++EndIt;
2709
2710 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2711 Decls.push_back(DIt->second);
2712}
2713
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002714SourceLocation ASTUnit::getLocation(const FileEntry *File,
2715 unsigned Line, unsigned Col) const {
2716 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002717 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002718 return SM.getMacroArgExpandedLocation(Loc);
2719}
2720
2721SourceLocation ASTUnit::getLocation(const FileEntry *File,
2722 unsigned Offset) const {
2723 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002724 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002725 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2726}
2727
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002728/// \brief If \arg Loc is a loaded location from the preamble, returns
2729/// the corresponding local location of the main file, otherwise it returns
2730/// \arg Loc.
2731SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2732 FileID PreambleID;
2733 if (SourceMgr)
2734 PreambleID = SourceMgr->getPreambleFileID();
2735
2736 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2737 return Loc;
2738
2739 unsigned Offs;
2740 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2741 SourceLocation FileLoc
2742 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2743 return FileLoc.getLocWithOffset(Offs);
2744 }
2745
2746 return Loc;
2747}
2748
2749/// \brief If \arg Loc is a local location of the main file but inside the
2750/// preamble chunk, returns the corresponding loaded location from the
2751/// preamble, otherwise it returns \arg Loc.
2752SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2753 FileID PreambleID;
2754 if (SourceMgr)
2755 PreambleID = SourceMgr->getPreambleFileID();
2756
2757 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2758 return Loc;
2759
2760 unsigned Offs;
2761 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2762 Offs < Preamble.size()) {
2763 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2764 return FileLoc.getLocWithOffset(Offs);
2765 }
2766
2767 return Loc;
2768}
2769
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002770bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2771 FileID FID;
2772 if (SourceMgr)
2773 FID = SourceMgr->getPreambleFileID();
2774
2775 if (Loc.isInvalid() || FID.isInvalid())
2776 return false;
2777
2778 return SourceMgr->isInFileID(Loc, FID);
2779}
2780
2781bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2782 FileID FID;
2783 if (SourceMgr)
2784 FID = SourceMgr->getMainFileID();
2785
2786 if (Loc.isInvalid() || FID.isInvalid())
2787 return false;
2788
2789 return SourceMgr->isInFileID(Loc, FID);
2790}
2791
2792SourceLocation ASTUnit::getEndOfPreambleFileID() {
2793 FileID FID;
2794 if (SourceMgr)
2795 FID = SourceMgr->getPreambleFileID();
2796
2797 if (FID.isInvalid())
2798 return SourceLocation();
2799
2800 return SourceMgr->getLocForEndOfFile(FID);
2801}
2802
2803SourceLocation ASTUnit::getStartOfMainFileID() {
2804 FileID FID;
2805 if (SourceMgr)
2806 FID = SourceMgr->getMainFileID();
2807
2808 if (FID.isInvalid())
2809 return SourceLocation();
2810
2811 return SourceMgr->getLocForStartOfFile(FID);
2812}
2813
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002814std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2815ASTUnit::getLocalPreprocessingEntities() const {
2816 if (isMainFileAST()) {
2817 serialization::ModuleFile &
2818 Mod = Reader->getModuleManager().getPrimaryModule();
2819 return Reader->getModulePreprocessedEntities(Mod);
2820 }
2821
2822 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2823 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2824
2825 return std::make_pair(PreprocessingRecord::iterator(),
2826 PreprocessingRecord::iterator());
2827}
2828
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002829bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002830 if (isMainFileAST()) {
2831 serialization::ModuleFile &
2832 Mod = Reader->getModuleManager().getPrimaryModule();
2833 ASTReader::ModuleDeclIterator MDI, MDE;
2834 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2835 for (; MDI != MDE; ++MDI) {
2836 if (!Fn(context, *MDI))
2837 return false;
2838 }
2839
2840 return true;
2841 }
2842
2843 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2844 TLEnd = top_level_end();
2845 TL != TLEnd; ++TL) {
2846 if (!Fn(context, *TL))
2847 return false;
2848 }
2849
2850 return true;
2851}
2852
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002853namespace {
2854struct PCHLocatorInfo {
2855 serialization::ModuleFile *Mod;
2856 PCHLocatorInfo() : Mod(0) {}
2857};
2858}
2859
2860static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2861 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2862 switch (M.Kind) {
2863 case serialization::MK_Module:
2864 return true; // skip dependencies.
2865 case serialization::MK_PCH:
2866 Info.Mod = &M;
2867 return true; // found it.
2868 case serialization::MK_Preamble:
2869 return false; // look in dependencies.
2870 case serialization::MK_MainFile:
2871 return false; // look in dependencies.
2872 }
2873
2874 return true;
2875}
2876
2877const FileEntry *ASTUnit::getPCHFile() {
2878 if (!Reader)
2879 return 0;
2880
2881 PCHLocatorInfo Info;
2882 Reader->getModuleManager().visit(PCHLocator, &Info);
2883 if (Info.Mod)
2884 return Info.Mod->File;
2885
2886 return 0;
2887}
2888
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002889bool ASTUnit::isModuleFile() {
2890 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2891}
2892
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002893void ASTUnit::PreambleData::countLines() const {
2894 NumLines = 0;
2895 if (empty())
2896 return;
2897
2898 for (std::vector<char>::const_iterator
2899 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2900 if (*I == '\n')
2901 ++NumLines;
2902 }
2903 if (Buffer.back() != '\n')
2904 ++NumLines;
2905}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002906
2907#ifndef NDEBUG
2908ASTUnit::ConcurrencyState::ConcurrencyState() {
2909 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2910}
2911
2912ASTUnit::ConcurrencyState::~ConcurrencyState() {
2913 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2914}
2915
2916void ASTUnit::ConcurrencyState::start() {
2917 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2918 assert(acquired && "Concurrent access to ASTUnit!");
2919}
2920
2921void ASTUnit::ConcurrencyState::finish() {
2922 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2923}
2924
2925#else // NDEBUG
2926
Alp Tokerb159c132013-11-22 07:49:39 +00002927ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002928ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2929void ASTUnit::ConcurrencyState::start() {}
2930void ASTUnit::ConcurrencyState::finish() {}
2931
2932#endif