blob: 93429cba8870f566c692d064357ef08ea911d4e6 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
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() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000194 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000195}
196
Ted Kremenek06b4f912011-10-27 17:55:18 +0000197void ASTUnit::CleanTemporaryFiles() {
198 getOnDiskData(this).CleanTemporaryFiles();
199}
200
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000201void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000202 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000203}
204
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000205/// \brief After failing to build a precompiled preamble (due to
206/// errors in the source that occurs in the preamble), the number of
207/// reparses during which we'll skip even trying to precompile the
208/// preamble.
209const unsigned DefaultPreambleRebuildInterval = 5;
210
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000211/// \brief Tracks the number of ASTUnit objects that are currently active.
212///
213/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000214static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000215
Douglas Gregord03e8232010-04-05 21:10:19 +0000216ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000217 : Reader(0), HadModuleLoaderFatalFailure(false),
218 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis85b4a372011-11-29 18:18:33 +0000224 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000232 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Reid Klecknerc50b4bf2014-02-03 22:20:24 +0000233 fprintf(stderr, "+++ %d translation units\n", (int)ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000234 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000235}
Douglas Gregord03e8232010-04-05 21:10:19 +0000236
Daniel Dunbar764c0822009-12-01 09:51:01 +0000237ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000238 // If we loaded from an AST file, balance out the BeginSourceFile call.
239 if (MainFileIsAST && getDiagnostics().getClient()) {
240 getDiagnostics().getClient()->EndSourceFile();
241 }
242
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000243 clearFileLevelDecls();
244
Ted Kremenek06b4f912011-10-27 17:55:18 +0000245 // Clean up the temporary files and the preamble file.
246 removeOnDiskEntry(this);
247
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000248 // Free the buffers associated with remapped files. We are required to
249 // perform this operation here because we explicitly request that the
250 // compiler instance *not* free these buffers for each invocation of the
251 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000252 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000253 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
254 for (PreprocessorOptions::remapped_file_buffer_iterator
255 FB = PPOpts.remapped_file_buffer_begin(),
256 FBEnd = PPOpts.remapped_file_buffer_end();
257 FB != FBEnd;
258 ++FB)
259 delete FB->second;
260 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000261
262 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000263 delete PreambleBuffer;
264
Douglas Gregor16896c42010-10-28 15:44:59 +0000265 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000266
267 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000268 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Reid Klecknerc50b4bf2014-02-03 22:20:24 +0000269 fprintf(stderr, "--- %d translation units\n", (int)ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000270 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000271}
272
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000273void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
274
Douglas Gregor39982192010-08-15 06:18:01 +0000275/// \brief Determine the set of code-completion contexts in which this
276/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000277static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000278 const LangOptions &LangOpts,
279 bool &IsNestedNameSpecifier) {
280 IsNestedNameSpecifier = false;
281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 if (isa<UsingShadowDecl>(ND))
283 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
284 if (!ND)
285 return 0;
286
Richard Smith697cc9e2012-08-14 03:13:00 +0000287 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000288 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
289 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
290 // Types can appear in these contexts.
291 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
293 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
294 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
295 | (1LL << CodeCompletionContext::CCC_Statement)
296 | (1LL << CodeCompletionContext::CCC_Type)
297 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // In C++, types can appear in expressions contexts (for functional casts).
300 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
303 // In Objective-C, message sends can send interfaces. In Objective-C++,
304 // all types are available due to functional casts.
305 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000307
308 // In Objective-C, you can only be a subclass of another Objective-C class
309 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000311
312 // Deal with tag names.
313 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000315
Douglas Gregor59cab552010-08-16 23:05:20 +0000316 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000317 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000318 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000319 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000320 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000321 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000322 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000323 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000324
Douglas Gregor39982192010-08-15 06:18:01 +0000325 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000326 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000327 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000328 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000329 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
330 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
332 | (1LL << CodeCompletionContext::CCC_Expression)
333 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
334 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000335 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000337 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000338 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000339 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000340 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000341
342 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000343 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000344 }
345
346 return Contexts;
347}
348
Douglas Gregorb14904c2010-08-13 22:48:40 +0000349void ASTUnit::CacheCodeCompletionResults() {
350 if (!TheSema)
351 return;
352
Douglas Gregor16896c42010-10-28 15:44:59 +0000353 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000354 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000355
356 // Clear out the previous results.
357 ClearCachedCompletionResults();
358
359 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000360 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000361 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000362 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000363 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000364 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000365 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000366
367 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000368 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
369
Douglas Gregorb14904c2010-08-13 22:48:40 +0000370 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
371 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000372 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000373 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000374 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000375 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000376 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000377 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000378 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000379 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000380 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000381 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000382 CachedResult.Priority = Results[I].Priority;
383 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000384 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000385
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000386 // Keep track of the type of this completion in an ASTContext-agnostic
387 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000388 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000389 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000390 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000391 CachedResult.Type = 0;
392 } else {
393 CanQualType CanUsageType
394 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
395 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
396
397 // Determine whether we have already seen this type. If so, we save
398 // ourselves the work of formatting the type string by using the
399 // temporary, CanQualType-based hash table to find the associated value.
400 unsigned &TypeValue = CompletionTypes[CanUsageType];
401 if (TypeValue == 0) {
402 TypeValue = CompletionTypes.size();
403 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
404 = TypeValue;
405 }
406
407 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000408 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000409
Douglas Gregor39982192010-08-15 06:18:01 +0000410 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000411
412 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000413 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000414 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
415 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000416 uint64_t NNSContexts
417 = (1LL << CodeCompletionContext::CCC_TopLevel)
418 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
419 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
420 | (1LL << CodeCompletionContext::CCC_Statement)
421 | (1LL << CodeCompletionContext::CCC_Expression)
422 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
423 | (1LL << CodeCompletionContext::CCC_EnumTag)
424 | (1LL << CodeCompletionContext::CCC_UnionTag)
425 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
426 | (1LL << CodeCompletionContext::CCC_Type)
427 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
428 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000429
430 if (isa<NamespaceDecl>(Results[I].Declaration) ||
431 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000432 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000433
434 if (unsigned RemainingContexts
435 = NNSContexts & ~CachedResult.ShowInContexts) {
436 // If there any contexts where this completion can be a
437 // nested-name-specifier but isn't already an option, create a
438 // nested-name-specifier completion.
439 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000440 CachedResult.Completion
441 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000442 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000443 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000444 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000445 CachedResult.ShowInContexts = RemainingContexts;
446 CachedResult.Priority = CCP_NestedNameSpecifier;
447 CachedResult.TypeClass = STC_Void;
448 CachedResult.Type = 0;
449 CachedCompletionResults.push_back(CachedResult);
450 }
451 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000452 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000453 }
454
Douglas Gregorb14904c2010-08-13 22:48:40 +0000455 case Result::RK_Keyword:
456 case Result::RK_Pattern:
457 // Ignore keywords and patterns; we don't care, since they are so
458 // easily regenerated.
459 break;
460
461 case Result::RK_Macro: {
462 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000463 CachedResult.Completion
464 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000465 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000466 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000467 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000468 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000469 = (1LL << CodeCompletionContext::CCC_TopLevel)
470 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
471 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
472 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
473 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
474 | (1LL << CodeCompletionContext::CCC_Statement)
475 | (1LL << CodeCompletionContext::CCC_Expression)
476 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
477 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
478 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
479 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
480 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000481
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482 CachedResult.Priority = Results[I].Priority;
483 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000484 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000485 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000486 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000487 CachedCompletionResults.push_back(CachedResult);
488 break;
489 }
490 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000491 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000492
493 // Save the current top-level hash value.
494 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000495}
496
497void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000498 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000499 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000500 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000501}
502
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000503namespace {
504
Sebastian Redl2c499f62010-08-18 23:56:43 +0000505/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000507class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000508 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000509 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000510 LangOptions &LangOpt;
Douglas Gregorcb177f12012-10-16 23:40:58 +0000511 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000512 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregore8bbc122011-09-02 00:18:52 +0000515 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000517 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregorcb177f12012-10-16 23:40:58 +0000518 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000519 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 unsigned &Counter)
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000521 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000522 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000523 Counter(Counter),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000524 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000526 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000527 bool Complain) {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000528 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000529 return false;
530
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000531 LangOpt = LangOpts;
532 InitializedLanguage = true;
533
534 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000535 return false;
536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000538 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000539 bool Complain) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000540 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000541 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000542 return false;
543
Douglas Gregorcb177f12012-10-16 23:40:58 +0000544 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregorf8715de2012-11-16 04:24:59 +0000545 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
546 &*this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000547
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000548 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000549 return false;
550 }
Mike Stump11289f42009-09-09 15:08:12 +0000551
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +0000552 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553 Counter = Value;
554 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000555
556private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000557 void updated() {
558 if (!Target || !InitializedLanguage)
559 return;
560
561 // Inform the target of the language options.
562 //
563 // FIXME: We shouldn't need to do this, the target should be immutable once
564 // created. This complexity should be lifted elsewhere.
565 Target->setForcedLangOptions(LangOpt);
566
567 // Initialize the preprocessor.
568 PP.Initialize(*Target);
569
570 // Initialize the ASTContext
571 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000572
573 // We didn't have access to the comment options when the ASTContext was
574 // constructed, so register them now.
575 Context.getCommentCommandTraits().registerCommentOptions(
576 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000577 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000578};
579
Douglas Gregor6b930962013-05-03 22:58:43 +0000580 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000581class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000582 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000583 SourceManager *SourceMgr;
584
Douglas Gregor33cdd812010-02-18 18:08:43 +0000585public:
David Blaikief18d91a2011-09-26 00:01:39 +0000586 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000587 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor6b930962013-05-03 22:58:43 +0000588 : StoredDiags(StoredDiags), SourceMgr(0) { }
589
590 virtual void BeginSourceFile(const LangOptions &LangOpts,
591 const Preprocessor *PP = 0) {
592 if (PP)
593 SourceMgr = &PP->getSourceManager();
594 }
595
David Blaikie9c902b52011-09-25 23:23:43 +0000596 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000597 const Diagnostic &Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000598};
599
600/// \brief RAII object that optionally captures diagnostics, if
601/// there is no diagnostic client to capture them already.
602class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000603 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000604 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000605 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000606
607public:
David Blaikie9c902b52011-09-25 23:23:43 +0000608 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000609 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000610 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000611 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000612 if (RequestCapture || Diags.getClient() == 0) {
613 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000614 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000615 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000616 }
617
618 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000619 if (Diags.getClient() == &Client) {
620 Diags.takeClient();
621 Diags.setClient(PreviousClient);
622 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000623 }
624};
625
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000626} // anonymous namespace
627
David Blaikief18d91a2011-09-26 00:01:39 +0000628void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000629 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000630 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000631 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000632
Douglas Gregor6b930962013-05-03 22:58:43 +0000633 // Only record the diagnostic if it's part of the source manager we know
634 // about. This effectively drops diagnostics from modules we're building.
635 // FIXME: In the long run, ee don't want to drop source managers from modules.
636 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
637 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000638}
639
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000640ASTMutationListener *ASTUnit::getASTMutationListener() {
641 if (WriterData)
642 return &WriterData->Writer;
643 return 0;
644}
645
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000646ASTDeserializationListener *ASTUnit::getDeserializationListener() {
647 if (WriterData)
648 return &WriterData->Writer;
649 return 0;
650}
651
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000652llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000653 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000654 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000655 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000656}
657
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000658/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000659void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000660 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000661 ASTUnit &AST, bool CaptureDiagnostics) {
662 if (!Diags.getPtr()) {
663 // No diagnostics engine was provided, so create our own diagnostics object
664 // with the default options.
David Blaikiee2eefae2011-09-25 23:39:51 +0000665 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000666 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000667 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000668 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000669 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000670 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000671 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000672 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000673 }
674}
675
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000676ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000677 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000678 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000679 bool OnlyLocalDecls,
Dmitri Gribenko2febd212014-02-07 15:00:22 +0000680 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000681 bool CaptureDiagnostics,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000682 bool AllowPCHWithCompilerErrors,
683 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000684 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000685
686 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000687 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
688 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000689 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
690 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000691 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000692
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000693 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000694
Douglas Gregor16bef852009-10-16 20:01:17 +0000695 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000696 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000697 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000698 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000699 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000700 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000701 AST->getFileManager(),
702 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000703 AST->HSOpts = new HeaderSearchOptions();
704
705 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000706 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000707 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000708 AST->ASTFileLangOpts,
709 /*Target=*/0));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000710
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000711 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000712
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000713 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
714 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000715
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000716 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000717
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000718 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 unsigned Counter;
720
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000721 AST->PP = new Preprocessor(PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +0000722 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor83297df2011-09-01 23:39:15 +0000723 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
724 *AST,
725 /*IILookup=*/0,
726 /*OwnsHeaderSearch=*/false,
727 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 Preprocessor &PP = *AST->PP;
729
730 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
731 AST->getSourceManager(),
732 /*Target=*/0,
733 PP.getIdentifierTable(),
734 PP.getSelectorTable(),
735 PP.getBuiltinInfo(),
736 /* size_reserve = */0,
737 /*DelayInitialization=*/true);
738 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000739
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000740 bool disableValid = false;
741 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
742 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000743 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000744 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000745 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000746 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000747
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000748 AST->Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000749 AST->ASTFileLangOpts,
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000750 AST->TargetOpts, AST->Target,
Douglas Gregord02437c2012-10-25 00:09:28 +0000751 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000752
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000753 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000754 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000755 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000756 break;
Mike Stump11289f42009-09-09 15:08:12 +0000757
Sebastian Redl2c499f62010-08-18 23:56:43 +0000758 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000759 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000760 case ASTReader::OutOfDate:
761 case ASTReader::VersionMismatch:
762 case ASTReader::ConfigurationMismatch:
763 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000764 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000765 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000768 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000769
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000770 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Sebastian Redl2c499f62010-08-18 23:56:43 +0000772 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000773 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000774 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000775 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000776
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000777 // Create an AST consumer, even though it isn't used.
778 AST->Consumer.reset(new ASTConsumer);
779
Sebastian Redl2c499f62010-08-18 23:56:43 +0000780 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000781 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
782 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000783 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000784
Douglas Gregor6b930962013-05-03 22:58:43 +0000785 // Tell the diagnostic client that we have started a source file.
786 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
787
Mike Stump11289f42009-09-09 15:08:12 +0000788 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000789}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000790
791namespace {
792
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000793/// \brief Preprocessor callback class that updates a hash value with the names
794/// of all macros that have been defined by the translation unit.
795class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
796 unsigned &Hash;
797
798public:
799 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
800
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000801 virtual void MacroDefined(const Token &MacroNameTok,
802 const MacroDirective *MD) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000803 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
804 }
805};
806
807/// \brief Add the given declaration to the hash of all top-level entities.
808void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
809 if (!D)
810 return;
811
812 DeclContext *DC = D->getDeclContext();
813 if (!DC)
814 return;
815
816 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
817 return;
818
819 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000820 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
821 // For an unscoped enum include the enumerators in the hash since they
822 // enter the top-level namespace.
823 if (!EnumD->isScoped()) {
824 for (EnumDecl::enumerator_iterator EI = EnumD->enumerator_begin(),
825 EE = EnumD->enumerator_end(); EI != EE; ++EI) {
826 if ((*EI)->getIdentifier())
827 Hash = llvm::HashString((*EI)->getIdentifier()->getName(), Hash);
828 }
829 }
830 }
831
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000832 if (ND->getIdentifier())
833 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
834 else if (DeclarationName Name = ND->getDeclName()) {
835 std::string NameStr = Name.getAsString();
836 Hash = llvm::HashString(NameStr, Hash);
837 }
838 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000839 }
840
841 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
842 if (Module *Mod = ImportD->getImportedModule()) {
843 std::string ModName = Mod->getFullModuleName();
844 Hash = llvm::HashString(ModName, Hash);
845 }
846 return;
847 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848}
849
Daniel Dunbar644dca02009-12-04 08:17:33 +0000850class TopLevelDeclTrackerConsumer : public ASTConsumer {
851 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852 unsigned &Hash;
853
Daniel Dunbar644dca02009-12-04 08:17:33 +0000854public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000855 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
856 : Unit(_Unit), Hash(Hash) {
857 Hash = 0;
858 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000859
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000860 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000861 if (!D)
862 return;
863
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000864 // FIXME: Currently ObjC method declarations are incorrectly being
865 // reported as top-level declarations, even though their DeclContext
866 // is the containing ObjC @interface/@implementation. This is a
867 // fundamental problem in the parser right now.
868 if (isa<ObjCMethodDecl>(D))
869 return;
870
871 AddTopLevelDeclarationToHash(D, Hash);
872 Unit.addTopLevelDecl(D);
873
874 handleFileLevelDecl(D);
875 }
876
877 void handleFileLevelDecl(Decl *D) {
878 Unit.addFileLevelDecl(D);
879 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
880 for (NamespaceDecl::decl_iterator
881 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
882 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000883 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000884 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000885
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000886 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000887 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
888 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000889 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000890 }
891
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000892 // We're not interested in "interesting" decls.
893 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000894
895 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
896 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
897 handleTopLevelDecl(*it);
898 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000899
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000900 virtual ASTMutationListener *GetASTMutationListener() {
901 return Unit.getASTMutationListener();
902 }
903
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000904 virtual ASTDeserializationListener *GetASTDeserializationListener() {
905 return Unit.getDeserializationListener();
906 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000907};
908
909class TopLevelDeclTrackerAction : public ASTFrontendAction {
910public:
911 ASTUnit &Unit;
912
Daniel Dunbar764c0822009-12-01 09:51:01 +0000913 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000914 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000915 CI.getPreprocessor().addPPCallbacks(
916 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
917 return new TopLevelDeclTrackerConsumer(Unit,
918 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000919 }
920
921public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000922 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
923
Daniel Dunbar764c0822009-12-01 09:51:01 +0000924 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000925 virtual TranslationUnitKind getTranslationUnitKind() {
926 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000927 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000928};
929
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000930class PrecompilePreambleAction : public ASTFrontendAction {
931 ASTUnit &Unit;
932 bool HasEmittedPreamblePCH;
933
934public:
935 explicit PrecompilePreambleAction(ASTUnit &Unit)
936 : Unit(Unit), HasEmittedPreamblePCH(false) {}
937
938 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
939 StringRef InFile);
940 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
941 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
942 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
943
944 virtual bool hasCodeCompletionSupport() const { return false; }
945 virtual bool hasASTFileSupport() const { return false; }
946 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
947};
948
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000949class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000950 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000951 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000952 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000953 PrecompilePreambleAction *Action;
954
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000955public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000956 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
957 const Preprocessor &PP, StringRef isysroot,
958 raw_ostream *Out)
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000959 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000960 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000961 Hash = 0;
962 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000963
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000964 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000965 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
966 Decl *D = *it;
967 // FIXME: Currently ObjC method declarations are incorrectly being
968 // reported as top-level declarations, even though their DeclContext
969 // is the containing ObjC @interface/@implementation. This is a
970 // fundamental problem in the parser right now.
971 if (isa<ObjCMethodDecl>(D))
972 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000973 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000974 TopLevelDecls.push_back(D);
975 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000976 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000977 }
978
979 virtual void HandleTranslationUnit(ASTContext &Ctx) {
980 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000981 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000982 // Translate the top-level declarations we captured during
983 // parsing into declaration IDs in the precompiled
984 // preamble. This will allow us to deserialize those top-level
985 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000986 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
987 Decl *D = TopLevelDecls[I];
988 // Invalid top-level decls may not have been serialized.
989 if (D->isInvalidDecl())
990 continue;
991 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
992 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000993
994 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000995 }
996 }
997};
998
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000999}
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001000
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001001ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1002 StringRef InFile) {
1003 std::string Sysroot;
1004 std::string OutputFile;
1005 raw_ostream *OS = 0;
1006 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1007 OutputFile, OS))
1008 return 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001009
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001010 if (!CI.getFrontendOpts().RelocatablePCH)
1011 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001012
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001013 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1014 Unit.getCurrentTopLevelHashValue()));
1015 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1016 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +00001017}
1018
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001019static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1020 return StoredDiag.getLocation().isValid();
1021}
1022
1023static void
1024checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001025 // Get rid of stored diagnostics except the ones from the driver which do not
1026 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001027 StoredDiags.erase(
1028 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1029 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001030}
1031
1032static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1033 StoredDiagnostics,
1034 SourceManager &SM) {
1035 // The stored diagnostic has the old source manager in it; update
1036 // the locations to refer into the new source manager. Since we've
1037 // been careful to make sure that the source manager's state
1038 // before and after are identical, so that we can reuse the source
1039 // location itself.
1040 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1041 if (StoredDiagnostics[I].getLocation().isValid()) {
1042 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1043 StoredDiagnostics[I].setLocation(Loc);
1044 }
1045 }
1046}
1047
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001048/// Parse the source file into a translation unit using the given compiler
1049/// invocation, replacing the current translation unit.
1050///
1051/// \returns True if a failure occurred that causes the ASTUnit not to
1052/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001053bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001054 delete SavedMainFileBuffer;
1055 SavedMainFileBuffer = 0;
1056
Ted Kremenek5e14d392011-03-21 18:40:17 +00001057 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001058 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001059 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001060 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001061
Daniel Dunbar764c0822009-12-01 09:51:01 +00001062 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001063 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001064
1065 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001066 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1067 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001068
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001069 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001070 CCInvocation(new CompilerInvocation(*Invocation));
1071
1072 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001073 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001074
Douglas Gregor8e984da2010-08-04 16:47:14 +00001075 // Set up diagnostics, capturing any diagnostics that would
1076 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001077 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001078
Daniel Dunbar764c0822009-12-01 09:51:01 +00001079 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001080 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001081 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001082 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001083 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001084 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001085 }
1086
Daniel Dunbar764c0822009-12-01 09:51:01 +00001087 // Inform the target of the language options.
1088 //
1089 // FIXME: We shouldn't need to do this, the target should be immutable once
1090 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001091 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001092
Ted Kremenek84de4a12011-03-21 18:40:07 +00001093 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001094 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001095 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001096 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001097 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001098 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001099
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001100 // Configure the various subsystems.
1101 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001102 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001104 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001105 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1106 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001107 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001108 Ctx = 0;
1109 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001110 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001111
1112 // Clear out old caches and data.
1113 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001114 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001115 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001116
Douglas Gregor7b02b582010-08-20 00:02:33 +00001117 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001118 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001119 TopLevelDeclsInPreamble.clear();
1120 }
1121
Daniel Dunbar764c0822009-12-01 09:51:01 +00001122 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001123 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001124
Daniel Dunbar764c0822009-12-01 09:51:01 +00001125 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001126 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001127
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001128 // If the main file has been overridden due to the use of a preamble,
1129 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001130 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001131 if (OverrideMainBuffer) {
1132 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1133 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1134 PreprocessorOpts.PrecompiledPreambleBytes.second
1135 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001136 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001137 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001138
Douglas Gregord9a30af2010-08-02 20:51:39 +00001139 // The stored diagnostic has the old source manager in it; update
1140 // the locations to refer into the new source manager. Since we've
1141 // been careful to make sure that the source manager's state
1142 // before and after are identical, so that we can reuse the source
1143 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001144 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001145
1146 // Keep track of the override buffer;
1147 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001148 }
1149
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001150 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001151 new TopLevelDeclTrackerAction(*this));
1152
1153 // Recover resources if we crash before exiting this method.
1154 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1155 ActCleanup(Act.get());
1156
Douglas Gregor32fbe312012-01-20 16:28:04 +00001157 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001158 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001159
1160 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001161 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001162 TranslateStoredDiagnostics(Clang->getModuleManager().getPtr(), ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00001163 getSourceManager(), PreambleDiagnostics,
1164 StoredDiagnostics);
1165 }
1166
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001167 if (!Act->Execute())
1168 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001169
1170 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001171
Daniel Dunbar644dca02009-12-04 08:17:33 +00001172 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001173
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001174 FailedParseDiagnostics.clear();
1175
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001176 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001177
Daniel Dunbar764c0822009-12-01 09:51:01 +00001178error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001179 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001180 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001181 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001182 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001183 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001184
1185 // Keep the ownership of the data in the ASTUnit because the client may
1186 // want to see the diagnostics.
1187 transferASTDataFromCompilerInstance(*Clang);
1188 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001189 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001190 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001191 return true;
1192}
1193
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001194/// \brief Simple function to retrieve a path for a preamble precompiled header.
1195static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001196 // FIXME: This is a hack so that we can override the preamble file during
1197 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001198 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001199 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1200 if (TmpFile)
1201 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001202
1203 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001204 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001205
1206 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207}
1208
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001209/// \brief Compute the preamble for the main file, providing the source buffer
1210/// that corresponds to the main file along with a pair (bytes, start-of-line)
1211/// that describes the preamble.
1212std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001213ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1214 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001215 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001216 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001217 CreatedBuffer = false;
1218
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219 // Try to determine if the main file has been remapped, either from the
1220 // command line (to another file) or directly through the compiler invocation
1221 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001222 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001223 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001224 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001225 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001226 // Check whether there is a file-file remapping of the main file
1227 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001228 M = PreprocessorOpts.remapped_file_begin(),
1229 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001230 M != E;
1231 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001232 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001233 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001234 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001235 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001237 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001239 CreatedBuffer = false;
1240 }
1241
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001242 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001243 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001244 return std::make_pair((llvm::MemoryBuffer*)0,
1245 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001246 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001247 }
1248 }
1249 }
1250
1251 // Check whether there is a file-buffer remapping. It supercedes the
1252 // file-file remapping.
1253 for (PreprocessorOptions::remapped_file_buffer_iterator
1254 M = PreprocessorOpts.remapped_file_buffer_begin(),
1255 E = PreprocessorOpts.remapped_file_buffer_end();
1256 M != E;
1257 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001258 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001259 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001260 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001261 if (MainFileID == MID) {
1262 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001264 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001265 CreatedBuffer = false;
1266 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001267
Douglas Gregor4dde7492010-07-23 23:58:40 +00001268 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001269 }
1270 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001271 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001272 }
1273
1274 // If the main source file was not remapped, load it now.
1275 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001276 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001277 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001278 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001279
1280 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001281 }
1282
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001283 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001284 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001285 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001286}
1287
Douglas Gregor6481ef12010-07-24 00:38:13 +00001288static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001289 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001290 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001291 llvm::MemoryBuffer *Result
1292 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1293 memcpy(const_cast<char*>(Result->getBufferStart()),
1294 Old->getBufferStart(), Old->getBufferSize());
1295 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001296 ' ', NewSize - Old->getBufferSize() - 1);
1297 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001298
Douglas Gregor6481ef12010-07-24 00:38:13 +00001299 return Result;
1300}
1301
Dmitri Gribenko47652522013-12-20 00:16:25 +00001302ASTUnit::PreambleFileHash
1303ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1304 PreambleFileHash Result;
1305 Result.Size = Size;
1306 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001307 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001308 return Result;
1309}
1310
1311ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1312 const llvm::MemoryBuffer *Buffer) {
1313 PreambleFileHash Result;
1314 Result.Size = Buffer->getBufferSize();
1315 Result.ModTime = 0;
1316
1317 llvm::MD5 MD5Ctx;
1318 MD5Ctx.update(Buffer->getBuffer().data());
1319 MD5Ctx.final(Result.MD5);
1320
1321 return Result;
1322}
1323
1324namespace clang {
1325bool operator==(const ASTUnit::PreambleFileHash &LHS,
1326 const ASTUnit::PreambleFileHash &RHS) {
1327 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001328 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001329}
1330} // namespace clang
1331
Douglas Gregor4dde7492010-07-23 23:58:40 +00001332/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1333/// the source file.
1334///
1335/// This routine will compute the preamble of the main source file. If a
1336/// non-trivial preamble is found, it will precompile that preamble into a
1337/// precompiled header so that the precompiled preamble can be used to reduce
1338/// reparsing time. If a precompiled preamble has already been constructed,
1339/// this routine will determine if it is still valid and, if so, avoid
1340/// rebuilding the precompiled preamble.
1341///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001342/// \param AllowRebuild When true (the default), this routine is
1343/// allowed to rebuild the precompiled preamble if it is found to be
1344/// out-of-date.
1345///
1346/// \param MaxLines When non-zero, the maximum number of lines that
1347/// can occur within the preamble.
1348///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001349/// \returns If the precompiled preamble can be used, returns a newly-allocated
1350/// buffer that should be used in place of the main file when doing so.
1351/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001352llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001353 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001354 bool AllowRebuild,
1355 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001356
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001357 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001358 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1359 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001360 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001361 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001362
1363 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001364 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001365 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001366
Douglas Gregor925296b2011-07-19 16:10:42 +00001367 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001368 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001369 if (CreatedPreambleBuffer)
1370 OwnedPreambleBuffer.reset(NewPreamble.first);
1371
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001372 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001373 // We couldn't find a preamble in the main source. Clear out the current
1374 // preamble, if we have one. It's obviously no good any more.
1375 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001376 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001377
1378 // The next time we actually see a preamble, precompile it.
1379 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001380 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001381 }
1382
1383 if (!Preamble.empty()) {
1384 // We've previously computed a preamble. Check whether we have the same
1385 // preamble now that we did before, and that there's enough space in
1386 // the main-file buffer within the precompiled preamble to fit the
1387 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001388 if (Preamble.size() == NewPreamble.second.first &&
1389 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001390 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001391 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001392 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001393 // The preamble has not changed. We may be able to re-use the precompiled
1394 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001395
Douglas Gregor0e119552010-07-31 00:40:00 +00001396 // Check that none of the files used by the preamble have changed.
1397 bool AnyFileChanged = false;
1398
1399 // First, make a record of those files that have been overridden via
1400 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001401 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregor0e119552010-07-31 00:40:00 +00001402 for (PreprocessorOptions::remapped_file_iterator
1403 R = PreprocessorOpts.remapped_file_begin(),
1404 REnd = PreprocessorOpts.remapped_file_end();
1405 !AnyFileChanged && R != REnd;
1406 ++R) {
Ben Langmuirc8130a72014-02-20 21:59:23 +00001407 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001408 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001409 // If we can't stat the file we're remapping to, assume that something
1410 // horrible happened.
1411 AnyFileChanged = true;
1412 break;
1413 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001414
Dmitri Gribenko47652522013-12-20 00:16:25 +00001415 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001416 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001417 }
1418 for (PreprocessorOptions::remapped_file_buffer_iterator
1419 R = PreprocessorOpts.remapped_file_buffer_begin(),
1420 REnd = PreprocessorOpts.remapped_file_buffer_end();
1421 !AnyFileChanged && R != REnd;
1422 ++R) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001423 OverriddenFiles[R->first] =
1424 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001425 }
1426
1427 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001428 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001429 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1430 !AnyFileChanged && F != FEnd;
1431 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001432 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001433 = OverriddenFiles.find(F->first());
1434 if (Overridden != OverriddenFiles.end()) {
1435 // This file was remapped; check whether the newly-mapped file
1436 // matches up with the previous mapping.
1437 if (Overridden->second != F->second)
1438 AnyFileChanged = true;
1439 continue;
1440 }
1441
1442 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001443 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001444 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001445 // If we can't stat the file, assume that something horrible happened.
1446 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001447 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001448 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001449 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001450 AnyFileChanged = true;
1451 }
1452
1453 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001454 // Okay! We can re-use the precompiled preamble.
1455
1456 // Set the state of the diagnostic object to mimic its state
1457 // after parsing the preamble.
1458 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001459 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001460 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001461 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001462
1463 // Create a version of the main file buffer that is padded to
1464 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001465 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001466 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001467 FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001468 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001469 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001470
1471 // If we aren't allowed to rebuild the precompiled preamble, just
1472 // return now.
1473 if (!AllowRebuild)
1474 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001475
Douglas Gregor4dde7492010-07-23 23:58:40 +00001476 // We can't reuse the previously-computed preamble. Build a new one.
1477 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001478 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001479 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001480 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001481 } else if (!AllowRebuild) {
1482 // We aren't allowed to rebuild the precompiled preamble; just
1483 // return now.
1484 return 0;
1485 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001486
1487 // If the preamble rebuild counter > 1, it's because we previously
1488 // failed to build a preamble and we're not yet ready to try
1489 // again. Decrement the counter and return a failure.
1490 if (PreambleRebuildCounter > 1) {
1491 --PreambleRebuildCounter;
1492 return 0;
1493 }
1494
Douglas Gregore10f0e52010-09-11 17:56:52 +00001495 // Create a temporary file for the precompiled preamble. In rare
1496 // circumstances, this can fail.
1497 std::string PreamblePCHPath = GetPreamblePCHPath();
1498 if (PreamblePCHPath.empty()) {
1499 // Try again next time.
1500 PreambleRebuildCounter = 1;
1501 return 0;
1502 }
1503
Douglas Gregor4dde7492010-07-23 23:58:40 +00001504 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001505 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001506 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001507
1508 // Create a new buffer that stores the preamble. The buffer also contains
1509 // extra space for the original contents of the file (which will be present
1510 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001511 // grows.
1512 PreambleReservedSize = NewPreamble.first->getBufferSize();
1513 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001514 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001515 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001516 PreambleReservedSize *= 2;
1517
Douglas Gregord9a30af2010-08-02 20:51:39 +00001518 // Save the preamble text for later; we'll need to compare against it for
1519 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001520 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001521 Preamble.assign(FileMgr->getFile(MainFilename),
1522 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001523 NewPreamble.first->getBufferStart()
1524 + NewPreamble.second.first);
1525 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1526
Douglas Gregora0734c52010-08-19 01:33:06 +00001527 delete PreambleBuffer;
1528 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001529 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001530 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001531 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001532 NewPreamble.first->getBufferStart(), Preamble.size());
1533 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001534 ' ', PreambleReservedSize - Preamble.size() - 1);
1535 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001536
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001537 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001538 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1539 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1540
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001541 // Tell the compiler invocation to generate a temporary precompiled header.
1542 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001543 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001544 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001545 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1546 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001547
1548 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001549 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001550
1551 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001552 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1553 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001554
Douglas Gregor3cc15812011-07-01 18:22:13 +00001555 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001556 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001557
Douglas Gregor8e984da2010-08-04 16:47:14 +00001558 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001559 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001560
1561 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001562 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001563 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001564 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001565 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001566 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001567 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001568 PreprocessorOpts.eraseRemappedFile(
1569 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001570 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001571 }
1572
1573 // Inform the target of the language options.
1574 //
1575 // FIXME: We shouldn't need to do this, the target should be immutable once
1576 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001577 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001578
Ted Kremenek84de4a12011-03-21 18:40:07 +00001579 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001580 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001581 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001582 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001583 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001584 "IR inputs not support here!");
1585
1586 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001587 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001588 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001589 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001590 TopLevelDecls.clear();
1591 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001592
1593 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001594 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001595
1596 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001597 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001598 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001599
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001600 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001601 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001602 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001603 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001604 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001605 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001606 PreprocessorOpts.eraseRemappedFile(
1607 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001608 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001609 }
1610
1611 Act->Execute();
1612 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001613
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001614 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001615 // The preamble PCH failed (e.g. there was a module loading fatal error),
1616 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001617 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001618 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001619 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001620 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001621 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001622 PreprocessorOpts.eraseRemappedFile(
1623 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001624 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001625 }
1626
Douglas Gregor925296b2011-07-19 16:10:42 +00001627 // Transfer any diagnostics generated when parsing the preamble into the set
1628 // of preamble diagnostics.
1629 PreambleDiagnostics.clear();
1630 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001631 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001632 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001633
Douglas Gregor4dde7492010-07-23 23:58:40 +00001634 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001635 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001636 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001637
1638 // Keep track of all of the files that the source manager knows about,
1639 // so we can verify whether they have changed or not.
1640 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001641 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001642 const llvm::MemoryBuffer *MainFileBuffer
1643 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1644 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1645 FEnd = SourceMgr.fileinfo_end();
1646 F != FEnd;
1647 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001648 const FileEntry *File = F->second->OrigEntry;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001649 if (!File)
Douglas Gregor0e119552010-07-31 00:40:00 +00001650 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001651 const llvm::MemoryBuffer *Buffer = F->second->getRawBuffer();
1652 if (Buffer == MainFileBuffer)
1653 continue;
1654
1655 if (time_t ModTime = File->getModificationTime()) {
1656 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1657 F->second->getSize(), ModTime);
1658 } else {
1659 assert(F->second->getSize() == Buffer->getBufferSize());
1660 FilesInPreamble[File->getName()] =
1661 PreambleFileHash::createForMemoryBuffer(Buffer);
1662 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001663 }
1664
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001665 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001666 PreprocessorOpts.eraseRemappedFile(
1667 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001668
1669 // If the hash of top-level entities differs from the hash of the top-level
1670 // entities the last time we rebuilt the preamble, clear out the completion
1671 // cache.
1672 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1673 CompletionCacheTopLevelHashValue = 0;
1674 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1675 }
1676
Douglas Gregor6481ef12010-07-24 00:38:13 +00001677 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001678 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001679 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001680}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001681
Douglas Gregore9db88f2010-08-03 19:06:41 +00001682void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1683 std::vector<Decl *> Resolved;
1684 Resolved.reserve(TopLevelDeclsInPreamble.size());
1685 ExternalASTSource &Source = *getASTContext().getExternalSource();
1686 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1687 // Resolve the declaration ID to an actual declaration, possibly
1688 // deserializing the declaration in the process.
1689 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1690 if (D)
1691 Resolved.push_back(D);
1692 }
1693 TopLevelDeclsInPreamble.clear();
1694 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1695}
1696
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001697void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1698 // Steal the created target, context, and preprocessor.
1699 TheSema.reset(CI.takeSema());
1700 Consumer.reset(CI.takeASTConsumer());
1701 Ctx = &CI.getASTContext();
1702 PP = &CI.getPreprocessor();
1703 CI.setSourceManager(0);
1704 CI.setFileManager(0);
1705 Target = &CI.getTarget();
1706 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001707 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001708}
1709
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001710StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001711 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1712 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1713 if (Input.isFile())
1714 return Input.getFile();
1715 else
1716 return Input.getBuffer()->getBufferIdentifier();
1717 }
1718
1719 if (SourceMgr) {
1720 if (const FileEntry *
1721 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1722 return FE->getName();
1723 }
1724
1725 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001726}
1727
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001728StringRef ASTUnit::getASTFileName() const {
1729 if (!isMainFileAST())
1730 return StringRef();
1731
1732 serialization::ModuleFile &
1733 Mod = Reader->getModuleManager().getPrimaryModule();
1734 return Mod.FileName;
1735}
1736
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001737ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001738 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001739 bool CaptureDiagnostics,
1740 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001741 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001742 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001743 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001744 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001745 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001746 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001747 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001748 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1749 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1750 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001751
1752 return AST.take();
1753}
1754
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001755ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001756 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001757 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001758 ASTUnit *Unit,
1759 bool Persistent,
1760 StringRef ResourceFilesPath,
1761 bool OnlyLocalDecls,
1762 bool CaptureDiagnostics,
1763 bool PrecompilePreamble,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001764 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001765 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001766 bool UserFilesAreVolatile,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001767 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001768 assert(CI && "A CompilerInvocation is required");
1769
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001770 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001771 ASTUnit *AST = Unit;
1772 if (!AST) {
1773 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001774 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001775 AST = OwnAST.get();
1776 }
1777
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001778 if (!ResourceFilesPath.empty()) {
1779 // Override the resources path.
1780 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1781 }
1782 AST->OnlyLocalDecls = OnlyLocalDecls;
1783 AST->CaptureDiagnostics = CaptureDiagnostics;
1784 if (PrecompilePreamble)
1785 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001786 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001787 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001788 AST->IncludeBriefCommentsInCodeCompletion
1789 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001790
1791 // Recover resources if we crash before exiting this method.
1792 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001793 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001794 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1795 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001796 DiagCleanup(Diags.getPtr());
1797
1798 // We'll manage file buffers ourselves.
1799 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1800 CI->getFrontendOpts().DisableFree = false;
1801 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1802
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001803 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001804 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001805
1806 // Recover resources if we crash before exiting this method.
1807 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1808 CICleanup(Clang.get());
1809
1810 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001811 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001812
1813 // Set up diagnostics, capturing any diagnostics that would
1814 // otherwise be dropped.
1815 Clang->setDiagnostics(&AST->getDiagnostics());
1816
1817 // Create the target instance.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001818 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001819 &Clang->getTargetOpts()));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001820 if (!Clang->hasTarget())
1821 return 0;
1822
1823 // Inform the target of the language options.
1824 //
1825 // FIXME: We shouldn't need to do this, the target should be immutable once
1826 // created. This complexity should be lifted elsewhere.
1827 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1828
1829 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1830 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001831 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001832 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001833 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001834 "IR inputs not supported here!");
1835
1836 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001837 AST->TheSema.reset();
1838 AST->Ctx = 0;
1839 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001840 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001841
1842 // Create a file manager object to provide access to and cache the filesystem.
1843 Clang->setFileManager(&AST->getFileManager());
1844
1845 // Create the source manager.
1846 Clang->setSourceManager(&AST->getSourceManager());
1847
1848 ASTFrontendAction *Act = Action;
1849
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001850 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001851 if (!Act) {
1852 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1853 Act = TrackerAct.get();
1854 }
1855
1856 // Recover resources if we crash before exiting this method.
1857 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1858 ActCleanup(TrackerAct.get());
1859
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001860 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1861 AST->transferASTDataFromCompilerInstance(*Clang);
1862 if (OwnAST && ErrAST)
1863 ErrAST->swap(OwnAST);
1864
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001865 return 0;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001866 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001867
1868 if (Persistent && !TrackerAct) {
1869 Clang->getPreprocessor().addPPCallbacks(
1870 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1871 std::vector<ASTConsumer*> Consumers;
1872 if (Clang->hasASTConsumer())
1873 Consumers.push_back(Clang->takeASTConsumer());
1874 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1875 AST->getCurrentTopLevelHashValue()));
1876 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1877 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001878 if (!Act->Execute()) {
1879 AST->transferASTDataFromCompilerInstance(*Clang);
1880 if (OwnAST && ErrAST)
1881 ErrAST->swap(OwnAST);
1882
1883 return 0;
1884 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001885
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001886 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001887 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001888
1889 Act->EndSourceFile();
1890
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001891 if (OwnAST)
1892 return OwnAST.take();
1893 else
1894 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001895}
1896
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001897bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1898 if (!Invocation)
1899 return true;
1900
1901 // We'll manage file buffers ourselves.
1902 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1903 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001904 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001905
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001906 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001907 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001908 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001909 OverrideMainBuffer
1910 = getMainBufferWithPrecompiledPreamble(*Invocation);
1911 }
1912
Douglas Gregor16896c42010-10-28 15:44:59 +00001913 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001914 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001915
Ted Kremenek022a4902011-03-22 01:15:24 +00001916 // Recover resources if we crash before exiting this method.
1917 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1918 MemBufferCleanup(OverrideMainBuffer);
1919
Douglas Gregor16896c42010-10-28 15:44:59 +00001920 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001921}
1922
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001923ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001924 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001925 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001926 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001927 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001928 TranslationUnitKind TUKind,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001929 bool CacheCodeCompletionResults,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001930 bool IncludeBriefCommentsInCodeCompletion,
1931 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001932 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001933 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001934 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001935 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001936 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001937 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001938 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001939 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001940 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001941 AST->IncludeBriefCommentsInCodeCompletion
1942 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001943 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001944 AST->FileSystemOpts = CI->getFileSystemOpts();
1945 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001946 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001947
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001948 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001949 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1950 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001951 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1952 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001953 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001954
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001955 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001956}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001957
1958ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1959 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001960 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001961 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001962 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001963 bool CaptureDiagnostics,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001964 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001965 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001966 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001967 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001968 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001969 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001970 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6e922512012-04-12 10:11:59 +00001971 bool SkipFunctionBodies,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001972 bool UserFilesAreVolatile,
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001973 bool ForSerialization,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001974 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001975 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001976 // No diagnostics engine was provided, so create our own diagnostics object
1977 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00001978 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00001979 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001980
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001981 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001982
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001983 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001984
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001985 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001986
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001987 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001988 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001989
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001990 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001991 llvm::makeArrayRef(ArgBegin, ArgEnd),
1992 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001993 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001994 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001995 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001996
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001997 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001998 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001999 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2000 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002001 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002002 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2003 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2004 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002005
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002006 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002007 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002008
Erik Verbruggen6e922512012-04-12 10:11:59 +00002009 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2010
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002011 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002012 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002013 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002014 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002015 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00002016 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002017 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00002018 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002019 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002020 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002021 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002022 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002023 AST->IncludeBriefCommentsInCodeCompletion
2024 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002025 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002026 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002027 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002028 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002029 if (ForSerialization)
2030 AST->WriterData.reset(new ASTWriterData());
Ted Kremenek25047602011-11-17 23:01:17 +00002031 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002032
2033 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002034 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2035 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002036
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002037 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2038 // Some error occurred, if caller wants to examine diagnostics, pass it the
2039 // ASTUnit.
2040 if (ErrAST) {
2041 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2042 ErrAST->swap(AST);
2043 }
2044 return 0;
2045 }
2046
2047 return AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002048}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002049
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002050bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002051 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002052 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002053
2054 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002055
Douglas Gregor16896c42010-10-28 15:44:59 +00002056 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002057 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002058
Douglas Gregor0e119552010-07-31 00:40:00 +00002059 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002060 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2061 for (PreprocessorOptions::remapped_file_buffer_iterator
2062 R = PPOpts.remapped_file_buffer_begin(),
2063 REnd = PPOpts.remapped_file_buffer_end();
2064 R != REnd;
2065 ++R) {
2066 delete R->second;
2067 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002068 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002069 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002070 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2071 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002072 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002073
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002074 // If we have a preamble file lying around, or if we might try to
2075 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00002076 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002077 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002078 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002079
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002080 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002081 getDiagnostics().Reset();
2082 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002083 if (OverrideMainBuffer)
2084 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002085
Douglas Gregor4dde7492010-07-23 23:58:40 +00002086 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002087 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002088
2089 // If we're caching global code-completion results, and the top-level
2090 // declarations have changed, clear out the code-completion cache.
2091 if (!Result && ShouldCacheCodeCompletionResults &&
2092 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2093 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002094
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002095 // We now need to clear out the completion info related to this translation
2096 // unit; it'll be recreated if necessary.
2097 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002098
Douglas Gregor4dde7492010-07-23 23:58:40 +00002099 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002100}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002101
Douglas Gregorb14904c2010-08-13 22:48:40 +00002102//----------------------------------------------------------------------------//
2103// Code completion
2104//----------------------------------------------------------------------------//
2105
2106namespace {
2107 /// \brief Code completion consumer that combines the cached code-completion
2108 /// results from an ASTUnit with the code-completion results provided to it,
2109 /// then passes the result on to
2110 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002111 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002112 ASTUnit &AST;
2113 CodeCompleteConsumer &Next;
2114
2115 public:
2116 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002117 const CodeCompleteOptions &CodeCompleteOpts)
2118 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2119 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002120 {
2121 // Compute the set of contexts in which we will look when we don't have
2122 // any information about the specific context.
2123 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002124 = (1LL << CodeCompletionContext::CCC_TopLevel)
2125 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2126 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2127 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2128 | (1LL << CodeCompletionContext::CCC_Statement)
2129 | (1LL << CodeCompletionContext::CCC_Expression)
2130 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2131 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2132 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2133 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2134 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2135 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2136 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002137
David Blaikiebbafb8a2012-03-11 07:00:24 +00002138 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002139 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2140 | (1LL << CodeCompletionContext::CCC_UnionTag)
2141 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002142 }
2143
2144 virtual void ProcessCodeCompleteResults(Sema &S,
2145 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002146 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002147 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002148
2149 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2150 OverloadCandidate *Candidates,
2151 unsigned NumCandidates) {
2152 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2153 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002154
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002155 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002156 return Next.getAllocator();
2157 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002158
2159 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2160 return Next.getCodeCompletionTUInfo();
2161 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002162 };
2163}
Douglas Gregord46cf182010-08-16 20:01:48 +00002164
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002165/// \brief Helper function that computes which global names are hidden by the
2166/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002167static void CalculateHiddenNames(const CodeCompletionContext &Context,
2168 CodeCompletionResult *Results,
2169 unsigned NumResults,
2170 ASTContext &Ctx,
2171 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002172 bool OnlyTagNames = false;
2173 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002174 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002175 case CodeCompletionContext::CCC_TopLevel:
2176 case CodeCompletionContext::CCC_ObjCInterface:
2177 case CodeCompletionContext::CCC_ObjCImplementation:
2178 case CodeCompletionContext::CCC_ObjCIvarList:
2179 case CodeCompletionContext::CCC_ClassStructUnion:
2180 case CodeCompletionContext::CCC_Statement:
2181 case CodeCompletionContext::CCC_Expression:
2182 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002183 case CodeCompletionContext::CCC_DotMemberAccess:
2184 case CodeCompletionContext::CCC_ArrowMemberAccess:
2185 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002186 case CodeCompletionContext::CCC_Namespace:
2187 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002188 case CodeCompletionContext::CCC_Name:
2189 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002190 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002191 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002192 break;
2193
2194 case CodeCompletionContext::CCC_EnumTag:
2195 case CodeCompletionContext::CCC_UnionTag:
2196 case CodeCompletionContext::CCC_ClassOrStructTag:
2197 OnlyTagNames = true;
2198 break;
2199
2200 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002201 case CodeCompletionContext::CCC_MacroName:
2202 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002203 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002204 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002205 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002206 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002207 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002208 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002209 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002210 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2211 case CodeCompletionContext::CCC_ObjCClassMessage:
2212 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002213 // We're looking for nothing, or we're looking for names that cannot
2214 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002215 return;
2216 }
2217
John McCall276321a2010-08-25 06:19:51 +00002218 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002219 for (unsigned I = 0; I != NumResults; ++I) {
2220 if (Results[I].Kind != Result::RK_Declaration)
2221 continue;
2222
2223 unsigned IDNS
2224 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2225
2226 bool Hiding = false;
2227 if (OnlyTagNames)
2228 Hiding = (IDNS & Decl::IDNS_Tag);
2229 else {
2230 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002231 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2232 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002233 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002234 HiddenIDNS |= Decl::IDNS_Tag;
2235 Hiding = (IDNS & HiddenIDNS);
2236 }
2237
2238 if (!Hiding)
2239 continue;
2240
2241 DeclarationName Name = Results[I].Declaration->getDeclName();
2242 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2243 HiddenNames.insert(Identifier->getName());
2244 else
2245 HiddenNames.insert(Name.getAsString());
2246 }
2247}
2248
2249
Douglas Gregord46cf182010-08-16 20:01:48 +00002250void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2251 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002252 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002253 unsigned NumResults) {
2254 // Merge the results we were given with the results we cached.
2255 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002256 uint64_t InContexts =
2257 Context.getKind() == CodeCompletionContext::CCC_Recovery
2258 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002259 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002260 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002261 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002262 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002263 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002264 C = AST.cached_completion_begin(),
2265 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002266 C != CEnd; ++C) {
2267 // If the context we are in matches any of the contexts we are
2268 // interested in, we'll add this result.
2269 if ((C->ShowInContexts & InContexts) == 0)
2270 continue;
2271
2272 // If we haven't added any results previously, do so now.
2273 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002274 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2275 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002276 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2277 AddedResult = true;
2278 }
2279
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002280 // Determine whether this global completion result is hidden by a local
2281 // completion result. If so, skip it.
2282 if (C->Kind != CXCursor_MacroDefinition &&
2283 HiddenNames.count(C->Completion->getTypedText()))
2284 continue;
2285
Douglas Gregord46cf182010-08-16 20:01:48 +00002286 // Adjust priority based on similar type classes.
2287 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002288 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002289 if (!Context.getPreferredType().isNull()) {
2290 if (C->Kind == CXCursor_MacroDefinition) {
2291 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002292 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002293 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002294 } else if (C->Type) {
2295 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002296 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002297 Context.getPreferredType().getUnqualifiedType());
2298 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2299 if (ExpectedSTC == C->TypeClass) {
2300 // We know this type is similar; check for an exact match.
2301 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002302 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002303 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002304 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002305 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2306 Priority /= CCF_ExactTypeMatch;
2307 else
2308 Priority /= CCF_SimilarTypeMatch;
2309 }
2310 }
2311 }
2312
Douglas Gregor12785102010-08-24 20:21:13 +00002313 // Adjust the completion string, if required.
2314 if (C->Kind == CXCursor_MacroDefinition &&
2315 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2316 // Create a new code-completion string that just contains the
2317 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002318 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2319 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002320 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002321 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002322 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002323 }
2324
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002325 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002326 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002327 }
2328
2329 // If we did not add any cached completion results, just forward the
2330 // results we were given to the next consumer.
2331 if (!AddedResult) {
2332 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2333 return;
2334 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002335
Douglas Gregord46cf182010-08-16 20:01:48 +00002336 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2337 AllResults.size());
2338}
2339
2340
2341
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002342void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002343 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002344 bool IncludeMacros,
2345 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002346 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002347 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002348 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002349 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002350 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2351 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002352 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002353 return;
2354
Douglas Gregor16896c42010-10-28 15:44:59 +00002355 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002356 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002357 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002358
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002359 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002360 CCInvocation(new CompilerInvocation(*Invocation));
2361
2362 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002363 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002364 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002365
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002366 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2367 CachedCompletionResults.empty();
2368 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2369 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2370 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2371
2372 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2373
Douglas Gregor8e984da2010-08-04 16:47:14 +00002374 FrontendOpts.CodeCompletionAt.FileName = File;
2375 FrontendOpts.CodeCompletionAt.Line = Line;
2376 FrontendOpts.CodeCompletionAt.Column = Column;
2377
2378 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002379 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002380
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002381 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002382
2383 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002384 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2385 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002386
Ted Kremenek5e14d392011-03-21 18:40:17 +00002387 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002388 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002389
2390 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002391 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002392 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002393 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002394 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002395 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002396
2397 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002398 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00002399 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002400 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002401 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002402 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002403 }
2404
2405 // Inform the target of the language options.
2406 //
2407 // FIXME: We shouldn't need to do this, the target should be immutable once
2408 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002409 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002410
Ted Kremenek84de4a12011-03-21 18:40:07 +00002411 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002412 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002413 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002414 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002415 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002416 "IR inputs not support here!");
2417
2418
2419 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002420 Clang->setFileManager(&FileMgr);
2421 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002422
2423 // Remap files.
2424 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002425 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002426 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002427 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2428 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002429 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002430 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002431
Douglas Gregorb14904c2010-08-13 22:48:40 +00002432 // Use the code completion consumer we were given, but adding any cached
2433 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002434 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002435 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002436 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002437
Douglas Gregor028d3e42010-08-09 20:45:32 +00002438 // If we have a precompiled preamble, try to use it. We only allow
2439 // the use of the precompiled preamble if we're if the completion
2440 // point is within the main file, after the end of the precompiled
2441 // preamble.
2442 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002443 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002444 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002445 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002446
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002447 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002448 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002449 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002450 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002451 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002452 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002453 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002454 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002455 }
2456 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002457 }
2458
2459 // If the main file has been overridden due to the use of a preamble,
2460 // make that override happen and introduce the preamble.
2461 if (OverrideMainBuffer) {
2462 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2463 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2464 PreprocessorOpts.PrecompiledPreambleBytes.second
2465 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002466 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002467 PreprocessorOpts.DisablePCHValidation = true;
2468
Douglas Gregorb97b6662010-08-20 00:59:43 +00002469 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002470 } else {
2471 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2472 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002473 }
2474
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002475 // Disable the preprocessing record if modules are not enabled.
2476 if (!Clang->getLangOpts().Modules)
2477 PreprocessorOpts.DetailedRecord = false;
Douglas Gregor998caea2011-05-06 16:33:08 +00002478
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002479 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002480 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002481 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002482 Act->Execute();
2483 Act->EndSourceFile();
2484 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002485}
Douglas Gregore9386682010-08-13 05:36:37 +00002486
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002487bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002488 if (HadModuleLoaderFatalFailure)
2489 return true;
2490
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002491 // Write to a temporary file and later rename it to the actual file, to avoid
2492 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002493 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002494 TempPath = File;
2495 TempPath += "-%%%%%%%%";
2496 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002497 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002498 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002499
Douglas Gregore9386682010-08-13 05:36:37 +00002500 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2501 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002502 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002503
2504 serialize(Out);
2505 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002506 if (Out.has_error()) {
2507 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002508 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002509 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002510
Rafael Espindola65e025c2011-12-25 01:18:52 +00002511 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002512 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002513 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002514 }
2515
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002516 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002517}
2518
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002519static bool serializeUnit(ASTWriter &Writer,
2520 SmallVectorImpl<char> &Buffer,
2521 Sema &S,
2522 bool hasErrors,
2523 raw_ostream &OS) {
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00002524 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002525
2526 // Write the generated bitstream to "Out".
2527 if (!Buffer.empty())
2528 OS.write(Buffer.data(), Buffer.size());
2529
2530 return false;
2531}
2532
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002533bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002534 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002535
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002536 if (WriterData)
2537 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2538 getSema(), hasErrors, OS);
2539
Daniel Dunbar9a963862012-02-29 20:31:23 +00002540 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002541 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002542 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002543 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002544}
Douglas Gregor925296b2011-07-19 16:10:42 +00002545
2546typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2547
2548static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2549 unsigned Raw = L.getRawEncoding();
2550 const unsigned MacroBit = 1U << 31;
2551 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2552 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2553}
2554
2555void ASTUnit::TranslateStoredDiagnostics(
2556 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002557 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002558 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002559 const SmallVectorImpl<StoredDiagnostic> &Diags,
2560 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002561 // The stored diagnostic has the old source manager in it; update
2562 // the locations to refer into the new source manager. We also need to remap
2563 // all the locations to the new view. This includes the diag location, any
2564 // associated source ranges, and the source ranges of associated fix-its.
2565 // FIXME: There should be a cleaner way to do this.
2566
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002567 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002568 Result.reserve(Diags.size());
2569 assert(MMan && "Don't have a module manager");
Douglas Gregorde3ef502011-11-30 23:21:26 +00002570 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002571 assert(Mod && "Don't have preamble module");
2572 SLocRemap &Remap = Mod->SLocRemap;
2573 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2574 // Rebuild the StoredDiagnostic.
2575 const StoredDiagnostic &SD = Diags[I];
2576 SourceLocation L = SD.getLocation();
2577 TranslateSLoc(L, Remap);
2578 FullSourceLoc Loc(L, SrcMgr);
2579
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002580 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002581 Ranges.reserve(SD.range_size());
2582 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2583 E = SD.range_end();
2584 I != E; ++I) {
2585 SourceLocation BL = I->getBegin();
2586 TranslateSLoc(BL, Remap);
2587 SourceLocation EL = I->getEnd();
2588 TranslateSLoc(EL, Remap);
2589 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2590 }
2591
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002592 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002593 FixIts.reserve(SD.fixit_size());
2594 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2595 E = SD.fixit_end();
2596 I != E; ++I) {
2597 FixIts.push_back(FixItHint());
2598 FixItHint &FH = FixIts.back();
2599 FH.CodeToInsert = I->CodeToInsert;
2600 SourceLocation BL = I->RemoveRange.getBegin();
2601 TranslateSLoc(BL, Remap);
2602 SourceLocation EL = I->RemoveRange.getEnd();
2603 TranslateSLoc(EL, Remap);
2604 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2605 I->RemoveRange.isTokenRange());
2606 }
2607
2608 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2609 SD.getMessage(), Loc, Ranges, FixIts));
2610 }
2611 Result.swap(Out);
2612}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002613
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002614void ASTUnit::addFileLevelDecl(Decl *D) {
2615 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002616
2617 // We only care about local declarations.
2618 if (D->isFromASTFile())
2619 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002620
2621 SourceManager &SM = *SourceMgr;
2622 SourceLocation Loc = D->getLocation();
2623 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2624 return;
2625
2626 // We only keep track of the file-level declarations of each file.
2627 if (!D->getLexicalDeclContext()->isFileContext())
2628 return;
2629
2630 SourceLocation FileLoc = SM.getFileLoc(Loc);
2631 assert(SM.isLocalSourceLocation(FileLoc));
2632 FileID FID;
2633 unsigned Offset;
2634 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2635 if (FID.isInvalid())
2636 return;
2637
2638 LocDeclsTy *&Decls = FileDecls[FID];
2639 if (!Decls)
2640 Decls = new LocDeclsTy();
2641
2642 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2643
2644 if (Decls->empty() || Decls->back().first <= Offset) {
2645 Decls->push_back(LocDecl);
2646 return;
2647 }
2648
Benjamin Kramer45025c02013-08-24 13:22:59 +00002649 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2650 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002651
2652 Decls->insert(I, LocDecl);
2653}
2654
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002655void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2656 SmallVectorImpl<Decl *> &Decls) {
2657 if (File.isInvalid())
2658 return;
2659
2660 if (SourceMgr->isLoadedFileID(File)) {
2661 assert(Ctx->getExternalSource() && "No external source!");
2662 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2663 Decls);
2664 }
2665
2666 FileDeclsTy::iterator I = FileDecls.find(File);
2667 if (I == FileDecls.end())
2668 return;
2669
2670 LocDeclsTy &LocDecls = *I->second;
2671 if (LocDecls.empty())
2672 return;
2673
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002674 LocDeclsTy::iterator BeginIt =
2675 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002676 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002677 if (BeginIt != LocDecls.begin())
2678 --BeginIt;
2679
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002680 // If we are pointing at a top-level decl inside an objc container, we need
2681 // to backtrack until we find it otherwise we will fail to report that the
2682 // region overlaps with an objc container.
2683 while (BeginIt != LocDecls.begin() &&
2684 BeginIt->second->isTopLevelDeclInObjCContainer())
2685 --BeginIt;
2686
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002687 LocDeclsTy::iterator EndIt = std::upper_bound(
2688 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002689 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002690 if (EndIt != LocDecls.end())
2691 ++EndIt;
2692
2693 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2694 Decls.push_back(DIt->second);
2695}
2696
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002697SourceLocation ASTUnit::getLocation(const FileEntry *File,
2698 unsigned Line, unsigned Col) const {
2699 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002700 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002701 return SM.getMacroArgExpandedLocation(Loc);
2702}
2703
2704SourceLocation ASTUnit::getLocation(const FileEntry *File,
2705 unsigned Offset) const {
2706 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002707 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002708 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2709}
2710
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002711/// \brief If \arg Loc is a loaded location from the preamble, returns
2712/// the corresponding local location of the main file, otherwise it returns
2713/// \arg Loc.
2714SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2715 FileID PreambleID;
2716 if (SourceMgr)
2717 PreambleID = SourceMgr->getPreambleFileID();
2718
2719 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2720 return Loc;
2721
2722 unsigned Offs;
2723 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2724 SourceLocation FileLoc
2725 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2726 return FileLoc.getLocWithOffset(Offs);
2727 }
2728
2729 return Loc;
2730}
2731
2732/// \brief If \arg Loc is a local location of the main file but inside the
2733/// preamble chunk, returns the corresponding loaded location from the
2734/// preamble, otherwise it returns \arg Loc.
2735SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2736 FileID PreambleID;
2737 if (SourceMgr)
2738 PreambleID = SourceMgr->getPreambleFileID();
2739
2740 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2741 return Loc;
2742
2743 unsigned Offs;
2744 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2745 Offs < Preamble.size()) {
2746 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2747 return FileLoc.getLocWithOffset(Offs);
2748 }
2749
2750 return Loc;
2751}
2752
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002753bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2754 FileID FID;
2755 if (SourceMgr)
2756 FID = SourceMgr->getPreambleFileID();
2757
2758 if (Loc.isInvalid() || FID.isInvalid())
2759 return false;
2760
2761 return SourceMgr->isInFileID(Loc, FID);
2762}
2763
2764bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2765 FileID FID;
2766 if (SourceMgr)
2767 FID = SourceMgr->getMainFileID();
2768
2769 if (Loc.isInvalid() || FID.isInvalid())
2770 return false;
2771
2772 return SourceMgr->isInFileID(Loc, FID);
2773}
2774
2775SourceLocation ASTUnit::getEndOfPreambleFileID() {
2776 FileID FID;
2777 if (SourceMgr)
2778 FID = SourceMgr->getPreambleFileID();
2779
2780 if (FID.isInvalid())
2781 return SourceLocation();
2782
2783 return SourceMgr->getLocForEndOfFile(FID);
2784}
2785
2786SourceLocation ASTUnit::getStartOfMainFileID() {
2787 FileID FID;
2788 if (SourceMgr)
2789 FID = SourceMgr->getMainFileID();
2790
2791 if (FID.isInvalid())
2792 return SourceLocation();
2793
2794 return SourceMgr->getLocForStartOfFile(FID);
2795}
2796
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002797std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2798ASTUnit::getLocalPreprocessingEntities() const {
2799 if (isMainFileAST()) {
2800 serialization::ModuleFile &
2801 Mod = Reader->getModuleManager().getPrimaryModule();
2802 return Reader->getModulePreprocessedEntities(Mod);
2803 }
2804
2805 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2806 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2807
2808 return std::make_pair(PreprocessingRecord::iterator(),
2809 PreprocessingRecord::iterator());
2810}
2811
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002812bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002813 if (isMainFileAST()) {
2814 serialization::ModuleFile &
2815 Mod = Reader->getModuleManager().getPrimaryModule();
2816 ASTReader::ModuleDeclIterator MDI, MDE;
2817 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2818 for (; MDI != MDE; ++MDI) {
2819 if (!Fn(context, *MDI))
2820 return false;
2821 }
2822
2823 return true;
2824 }
2825
2826 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2827 TLEnd = top_level_end();
2828 TL != TLEnd; ++TL) {
2829 if (!Fn(context, *TL))
2830 return false;
2831 }
2832
2833 return true;
2834}
2835
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002836namespace {
2837struct PCHLocatorInfo {
2838 serialization::ModuleFile *Mod;
2839 PCHLocatorInfo() : Mod(0) {}
2840};
2841}
2842
2843static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2844 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2845 switch (M.Kind) {
2846 case serialization::MK_Module:
2847 return true; // skip dependencies.
2848 case serialization::MK_PCH:
2849 Info.Mod = &M;
2850 return true; // found it.
2851 case serialization::MK_Preamble:
2852 return false; // look in dependencies.
2853 case serialization::MK_MainFile:
2854 return false; // look in dependencies.
2855 }
2856
2857 return true;
2858}
2859
2860const FileEntry *ASTUnit::getPCHFile() {
2861 if (!Reader)
2862 return 0;
2863
2864 PCHLocatorInfo Info;
2865 Reader->getModuleManager().visit(PCHLocator, &Info);
2866 if (Info.Mod)
2867 return Info.Mod->File;
2868
2869 return 0;
2870}
2871
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002872bool ASTUnit::isModuleFile() {
2873 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2874}
2875
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002876void ASTUnit::PreambleData::countLines() const {
2877 NumLines = 0;
2878 if (empty())
2879 return;
2880
2881 for (std::vector<char>::const_iterator
2882 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2883 if (*I == '\n')
2884 ++NumLines;
2885 }
2886 if (Buffer.back() != '\n')
2887 ++NumLines;
2888}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002889
2890#ifndef NDEBUG
2891ASTUnit::ConcurrencyState::ConcurrencyState() {
2892 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2893}
2894
2895ASTUnit::ConcurrencyState::~ConcurrencyState() {
2896 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2897}
2898
2899void ASTUnit::ConcurrencyState::start() {
2900 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2901 assert(acquired && "Concurrent access to ASTUnit!");
2902}
2903
2904void ASTUnit::ConcurrencyState::finish() {
2905 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2906}
2907
2908#else // NDEBUG
2909
Alp Tokerb159c132013-11-22 07:49:39 +00002910ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002911ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2912void ASTUnit::ConcurrencyState::start() {}
2913void ASTUnit::ConcurrencyState::finish() {}
2914
2915#endif