blob: ace3e9c6aada4d435fc7c2e930fb568ef7990afd [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000047#include <atomic>
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
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.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000214static std::atomic<unsigned> 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) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING"))
232 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000233}
Douglas Gregord03e8232010-04-05 21:10:19 +0000234
Daniel Dunbar764c0822009-12-01 09:51:01 +0000235ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000236 // If we loaded from an AST file, balance out the BeginSourceFile call.
237 if (MainFileIsAST && getDiagnostics().getClient()) {
238 getDiagnostics().getClient()->EndSourceFile();
239 }
240
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000241 clearFileLevelDecls();
242
Ted Kremenek06b4f912011-10-27 17:55:18 +0000243 // Clean up the temporary files and the preamble file.
244 removeOnDiskEntry(this);
245
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000246 // Free the buffers associated with remapped files. We are required to
247 // perform this operation here because we explicitly request that the
248 // compiler instance *not* free these buffers for each invocation of the
249 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000250 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000251 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
252 for (PreprocessorOptions::remapped_file_buffer_iterator
253 FB = PPOpts.remapped_file_buffer_begin(),
254 FBEnd = PPOpts.remapped_file_buffer_end();
255 FB != FBEnd;
256 ++FB)
257 delete FB->second;
258 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000259
260 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000261 delete PreambleBuffer;
262
Douglas Gregor16896c42010-10-28 15:44:59 +0000263 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000264
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000265 if (getenv("LIBCLANG_OBJTRACKING"))
266 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000267}
268
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000269void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
270
Douglas Gregor39982192010-08-15 06:18:01 +0000271/// \brief Determine the set of code-completion contexts in which this
272/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000273static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000274 const LangOptions &LangOpts,
275 bool &IsNestedNameSpecifier) {
276 IsNestedNameSpecifier = false;
277
Douglas Gregor39982192010-08-15 06:18:01 +0000278 if (isa<UsingShadowDecl>(ND))
279 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
280 if (!ND)
281 return 0;
282
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000284 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
285 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
286 // Types can appear in these contexts.
287 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
289 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
290 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
291 | (1LL << CodeCompletionContext::CCC_Statement)
292 | (1LL << CodeCompletionContext::CCC_Type)
293 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000294
295 // In C++, types can appear in expressions contexts (for functional casts).
296 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // In Objective-C, message sends can send interfaces. In Objective-C++,
300 // all types are available due to functional casts.
301 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000303
304 // In Objective-C, you can only be a subclass of another Objective-C class
305 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000307
308 // Deal with tag names.
309 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000311
Douglas Gregor59cab552010-08-16 23:05:20 +0000312 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000313 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000315 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000316 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000318 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000319 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000320
Douglas Gregor39982192010-08-15 06:18:01 +0000321 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000322 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000323 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000324 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000325 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
326 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
328 | (1LL << CodeCompletionContext::CCC_Expression)
329 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
330 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000331 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000333 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000335 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000337
338 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000339 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000340 }
341
342 return Contexts;
343}
344
Douglas Gregorb14904c2010-08-13 22:48:40 +0000345void ASTUnit::CacheCodeCompletionResults() {
346 if (!TheSema)
347 return;
348
Douglas Gregor16896c42010-10-28 15:44:59 +0000349 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000350 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000351
352 // Clear out the previous results.
353 ClearCachedCompletionResults();
354
355 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000356 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000357 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000358 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000359 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000360 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000361 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000362
363 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000364 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
365
Douglas Gregorb14904c2010-08-13 22:48:40 +0000366 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
367 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000368 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000369 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000370 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000371 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000372 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000373 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000374 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000375 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000376 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000377 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000378 CachedResult.Priority = Results[I].Priority;
379 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000380 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000381
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000382 // Keep track of the type of this completion in an ASTContext-agnostic
383 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000384 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000385 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000386 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000387 CachedResult.Type = 0;
388 } else {
389 CanQualType CanUsageType
390 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
391 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
392
393 // Determine whether we have already seen this type. If so, we save
394 // ourselves the work of formatting the type string by using the
395 // temporary, CanQualType-based hash table to find the associated value.
396 unsigned &TypeValue = CompletionTypes[CanUsageType];
397 if (TypeValue == 0) {
398 TypeValue = CompletionTypes.size();
399 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
400 = TypeValue;
401 }
402
403 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000404 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000405
Douglas Gregor39982192010-08-15 06:18:01 +0000406 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000407
408 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000410 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
411 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000412 uint64_t NNSContexts
413 = (1LL << CodeCompletionContext::CCC_TopLevel)
414 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
415 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
416 | (1LL << CodeCompletionContext::CCC_Statement)
417 | (1LL << CodeCompletionContext::CCC_Expression)
418 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
419 | (1LL << CodeCompletionContext::CCC_EnumTag)
420 | (1LL << CodeCompletionContext::CCC_UnionTag)
421 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
422 | (1LL << CodeCompletionContext::CCC_Type)
423 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
424 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000425
426 if (isa<NamespaceDecl>(Results[I].Declaration) ||
427 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000428 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000429
430 if (unsigned RemainingContexts
431 = NNSContexts & ~CachedResult.ShowInContexts) {
432 // If there any contexts where this completion can be a
433 // nested-name-specifier but isn't already an option, create a
434 // nested-name-specifier completion.
435 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000436 CachedResult.Completion
437 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000438 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000439 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000440 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000441 CachedResult.ShowInContexts = RemainingContexts;
442 CachedResult.Priority = CCP_NestedNameSpecifier;
443 CachedResult.TypeClass = STC_Void;
444 CachedResult.Type = 0;
445 CachedCompletionResults.push_back(CachedResult);
446 }
447 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000448 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000449 }
450
Douglas Gregorb14904c2010-08-13 22:48:40 +0000451 case Result::RK_Keyword:
452 case Result::RK_Pattern:
453 // Ignore keywords and patterns; we don't care, since they are so
454 // easily regenerated.
455 break;
456
457 case Result::RK_Macro: {
458 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000459 CachedResult.Completion
460 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000461 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000462 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000463 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000464 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000465 = (1LL << CodeCompletionContext::CCC_TopLevel)
466 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
467 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
468 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
469 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
470 | (1LL << CodeCompletionContext::CCC_Statement)
471 | (1LL << CodeCompletionContext::CCC_Expression)
472 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
473 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
474 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
475 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
476 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000477
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478 CachedResult.Priority = Results[I].Priority;
479 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000480 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000481 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000482 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000483 CachedCompletionResults.push_back(CachedResult);
484 break;
485 }
486 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000487 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000488
489 // Save the current top-level hash value.
490 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000491}
492
493void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000494 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000495 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000496 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000497}
498
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499namespace {
500
Sebastian Redl2c499f62010-08-18 23:56:43 +0000501/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000502/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000503class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000504 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000505 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506 LangOptions &LangOpt;
Douglas Gregorcb177f12012-10-16 23:40:58 +0000507 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000509 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregore8bbc122011-09-02 00:18:52 +0000511 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000512public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000513 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregorcb177f12012-10-16 23:40:58 +0000514 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 unsigned &Counter)
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000517 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000518 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000519 Counter(Counter),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000520 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000522 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000523 bool Complain) {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000524 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000525 return false;
526
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000527 LangOpt = LangOpts;
528 InitializedLanguage = true;
529
530 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000531 return false;
532 }
Mike Stump11289f42009-09-09 15:08:12 +0000533
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000534 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000535 bool Complain) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000536 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000537 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000538 return false;
539
Douglas Gregorcb177f12012-10-16 23:40:58 +0000540 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregorf8715de2012-11-16 04:24:59 +0000541 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
542 &*this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000543
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000544 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000545 return false;
546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +0000548 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000549 Counter = Value;
550 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000551
552private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000553 void updated() {
554 if (!Target || !InitializedLanguage)
555 return;
556
557 // Inform the target of the language options.
558 //
559 // FIXME: We shouldn't need to do this, the target should be immutable once
560 // created. This complexity should be lifted elsewhere.
561 Target->setForcedLangOptions(LangOpt);
562
563 // Initialize the preprocessor.
564 PP.Initialize(*Target);
565
566 // Initialize the ASTContext
567 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000568
569 // We didn't have access to the comment options when the ASTContext was
570 // constructed, so register them now.
571 Context.getCommentCommandTraits().registerCommentOptions(
572 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000573 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000574};
575
Douglas Gregor6b930962013-05-03 22:58:43 +0000576 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000577class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000578 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000579 SourceManager *SourceMgr;
580
Douglas Gregor33cdd812010-02-18 18:08:43 +0000581public:
David Blaikief18d91a2011-09-26 00:01:39 +0000582 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor6b930962013-05-03 22:58:43 +0000584 : StoredDiags(StoredDiags), SourceMgr(0) { }
585
586 virtual void BeginSourceFile(const LangOptions &LangOpts,
587 const Preprocessor *PP = 0) {
588 if (PP)
589 SourceMgr = &PP->getSourceManager();
590 }
591
David Blaikie9c902b52011-09-25 23:23:43 +0000592 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000593 const Diagnostic &Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000594};
595
596/// \brief RAII object that optionally captures diagnostics, if
597/// there is no diagnostic client to capture them already.
598class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000599 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000600 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000601 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000602
603public:
David Blaikie9c902b52011-09-25 23:23:43 +0000604 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000605 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000606 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000607 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000608 if (RequestCapture || Diags.getClient() == 0) {
609 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000610 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000611 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000612 }
613
614 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000615 if (Diags.getClient() == &Client) {
616 Diags.takeClient();
617 Diags.setClient(PreviousClient);
618 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000619 }
620};
621
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000622} // anonymous namespace
623
David Blaikief18d91a2011-09-26 00:01:39 +0000624void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000625 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000626 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000627 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000628
Douglas Gregor6b930962013-05-03 22:58:43 +0000629 // Only record the diagnostic if it's part of the source manager we know
630 // about. This effectively drops diagnostics from modules we're building.
631 // FIXME: In the long run, ee don't want to drop source managers from modules.
632 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
633 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000634}
635
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000636ASTMutationListener *ASTUnit::getASTMutationListener() {
637 if (WriterData)
638 return &WriterData->Writer;
639 return 0;
640}
641
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000642ASTDeserializationListener *ASTUnit::getDeserializationListener() {
643 if (WriterData)
644 return &WriterData->Writer;
645 return 0;
646}
647
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000648llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000649 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000650 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000651 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000652}
653
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000654/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000655void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000656 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000657 ASTUnit &AST, bool CaptureDiagnostics) {
658 if (!Diags.getPtr()) {
659 // No diagnostics engine was provided, so create our own diagnostics object
660 // with the default options.
David Blaikiee2eefae2011-09-25 23:39:51 +0000661 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000662 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000663 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000664 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000665 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000666 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000667 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000668 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000669 }
670}
671
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000672ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000673 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000674 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000675 bool OnlyLocalDecls,
Dmitri Gribenko2febd212014-02-07 15:00:22 +0000676 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000677 bool CaptureDiagnostics,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000678 bool AllowPCHWithCompilerErrors,
679 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000680 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000681
682 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000683 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
684 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000685 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
686 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000687 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000688
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000689 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000690
Douglas Gregor16bef852009-10-16 20:01:17 +0000691 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000692 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000693 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000694 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000695 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000696 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000697 AST->getFileManager(),
698 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000699 AST->HSOpts = new HeaderSearchOptions();
700
701 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000702 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000703 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000704 AST->ASTFileLangOpts,
705 /*Target=*/0));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000706
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000707 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000708
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000709 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
710 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000711
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000712 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000713
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000714 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000715 unsigned Counter;
716
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000717 AST->PP = new Preprocessor(PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +0000718 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor83297df2011-09-01 23:39:15 +0000719 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
720 *AST,
721 /*IILookup=*/0,
722 /*OwnsHeaderSearch=*/false,
723 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000724 Preprocessor &PP = *AST->PP;
725
726 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
727 AST->getSourceManager(),
728 /*Target=*/0,
729 PP.getIdentifierTable(),
730 PP.getSelectorTable(),
731 PP.getBuiltinInfo(),
732 /* size_reserve = */0,
733 /*DelayInitialization=*/true);
734 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000735
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000736 bool disableValid = false;
737 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
738 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000739 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000740 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000741 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000742 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000743
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000744 AST->Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000745 AST->ASTFileLangOpts,
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000746 AST->TargetOpts, AST->Target,
Douglas Gregord02437c2012-10-25 00:09:28 +0000747 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000748
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000749 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000750 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000751 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000752 break;
Mike Stump11289f42009-09-09 15:08:12 +0000753
Sebastian Redl2c499f62010-08-18 23:56:43 +0000754 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000755 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000756 case ASTReader::OutOfDate:
757 case ASTReader::VersionMismatch:
758 case ASTReader::ConfigurationMismatch:
759 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000760 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000761 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000762 }
Mike Stump11289f42009-09-09 15:08:12 +0000763
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000764 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000765
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000766 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Sebastian Redl2c499f62010-08-18 23:56:43 +0000768 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000769 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000770 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000771 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000772
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000773 // Create an AST consumer, even though it isn't used.
774 AST->Consumer.reset(new ASTConsumer);
775
Sebastian Redl2c499f62010-08-18 23:56:43 +0000776 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000777 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
778 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000779 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000780
Douglas Gregor6b930962013-05-03 22:58:43 +0000781 // Tell the diagnostic client that we have started a source file.
782 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
783
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000784 return AST.release();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000785}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000786
787namespace {
788
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000789/// \brief Preprocessor callback class that updates a hash value with the names
790/// of all macros that have been defined by the translation unit.
791class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
792 unsigned &Hash;
793
794public:
795 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
796
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000797 virtual void MacroDefined(const Token &MacroNameTok,
798 const MacroDirective *MD) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000799 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
800 }
801};
802
803/// \brief Add the given declaration to the hash of all top-level entities.
804void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
805 if (!D)
806 return;
807
808 DeclContext *DC = D->getDeclContext();
809 if (!DC)
810 return;
811
812 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
813 return;
814
815 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000816 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
817 // For an unscoped enum include the enumerators in the hash since they
818 // enter the top-level namespace.
819 if (!EnumD->isScoped()) {
820 for (EnumDecl::enumerator_iterator EI = EnumD->enumerator_begin(),
821 EE = EnumD->enumerator_end(); EI != EE; ++EI) {
822 if ((*EI)->getIdentifier())
823 Hash = llvm::HashString((*EI)->getIdentifier()->getName(), Hash);
824 }
825 }
826 }
827
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000828 if (ND->getIdentifier())
829 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
830 else if (DeclarationName Name = ND->getDeclName()) {
831 std::string NameStr = Name.getAsString();
832 Hash = llvm::HashString(NameStr, Hash);
833 }
834 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000835 }
836
837 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
838 if (Module *Mod = ImportD->getImportedModule()) {
839 std::string ModName = Mod->getFullModuleName();
840 Hash = llvm::HashString(ModName, Hash);
841 }
842 return;
843 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000844}
845
Daniel Dunbar644dca02009-12-04 08:17:33 +0000846class TopLevelDeclTrackerConsumer : public ASTConsumer {
847 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848 unsigned &Hash;
849
Daniel Dunbar644dca02009-12-04 08:17:33 +0000850public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000851 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
852 : Unit(_Unit), Hash(Hash) {
853 Hash = 0;
854 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000855
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000856 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000857 if (!D)
858 return;
859
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000860 // FIXME: Currently ObjC method declarations are incorrectly being
861 // reported as top-level declarations, even though their DeclContext
862 // is the containing ObjC @interface/@implementation. This is a
863 // fundamental problem in the parser right now.
864 if (isa<ObjCMethodDecl>(D))
865 return;
866
867 AddTopLevelDeclarationToHash(D, Hash);
868 Unit.addTopLevelDecl(D);
869
870 handleFileLevelDecl(D);
871 }
872
873 void handleFileLevelDecl(Decl *D) {
874 Unit.addFileLevelDecl(D);
875 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
876 for (NamespaceDecl::decl_iterator
877 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
878 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000879 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000880 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000881
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000882 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000883 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
884 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000885 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000886 }
887
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000888 // We're not interested in "interesting" decls.
889 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000890
891 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
892 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
893 handleTopLevelDecl(*it);
894 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000895
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000896 virtual ASTMutationListener *GetASTMutationListener() {
897 return Unit.getASTMutationListener();
898 }
899
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000900 virtual ASTDeserializationListener *GetASTDeserializationListener() {
901 return Unit.getDeserializationListener();
902 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000903};
904
905class TopLevelDeclTrackerAction : public ASTFrontendAction {
906public:
907 ASTUnit &Unit;
908
Daniel Dunbar764c0822009-12-01 09:51:01 +0000909 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000910 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000911 CI.getPreprocessor().addPPCallbacks(
912 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
913 return new TopLevelDeclTrackerConsumer(Unit,
914 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000915 }
916
917public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000918 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
919
Daniel Dunbar764c0822009-12-01 09:51:01 +0000920 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000921 virtual TranslationUnitKind getTranslationUnitKind() {
922 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000923 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000924};
925
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000926class PrecompilePreambleAction : public ASTFrontendAction {
927 ASTUnit &Unit;
928 bool HasEmittedPreamblePCH;
929
930public:
931 explicit PrecompilePreambleAction(ASTUnit &Unit)
932 : Unit(Unit), HasEmittedPreamblePCH(false) {}
933
934 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
935 StringRef InFile);
936 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
937 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
938 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
939
940 virtual bool hasCodeCompletionSupport() const { return false; }
941 virtual bool hasASTFileSupport() const { return false; }
942 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
943};
944
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000945class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000946 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000947 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000948 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000949 PrecompilePreambleAction *Action;
950
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000951public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000952 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
953 const Preprocessor &PP, StringRef isysroot,
954 raw_ostream *Out)
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000955 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000956 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000957 Hash = 0;
958 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000959
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000960 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000961 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
962 Decl *D = *it;
963 // FIXME: Currently ObjC method declarations are incorrectly being
964 // reported as top-level declarations, even though their DeclContext
965 // is the containing ObjC @interface/@implementation. This is a
966 // fundamental problem in the parser right now.
967 if (isa<ObjCMethodDecl>(D))
968 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000969 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000970 TopLevelDecls.push_back(D);
971 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000972 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000973 }
974
975 virtual void HandleTranslationUnit(ASTContext &Ctx) {
976 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000977 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000978 // Translate the top-level declarations we captured during
979 // parsing into declaration IDs in the precompiled
980 // preamble. This will allow us to deserialize those top-level
981 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000982 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
983 Decl *D = TopLevelDecls[I];
984 // Invalid top-level decls may not have been serialized.
985 if (D->isInvalidDecl())
986 continue;
987 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
988 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000989
990 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000991 }
992 }
993};
994
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000995}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000996
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000997ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
998 StringRef InFile) {
999 std::string Sysroot;
1000 std::string OutputFile;
1001 raw_ostream *OS = 0;
1002 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1003 OutputFile, OS))
1004 return 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001005
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001006 if (!CI.getFrontendOpts().RelocatablePCH)
1007 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001008
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001009 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1010 Unit.getCurrentTopLevelHashValue()));
1011 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1012 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +00001013}
1014
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001015static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1016 return StoredDiag.getLocation().isValid();
1017}
1018
1019static void
1020checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001021 // Get rid of stored diagnostics except the ones from the driver which do not
1022 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001023 StoredDiags.erase(
1024 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1025 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001026}
1027
1028static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1029 StoredDiagnostics,
1030 SourceManager &SM) {
1031 // The stored diagnostic has the old source manager in it; update
1032 // the locations to refer into the new source manager. Since we've
1033 // been careful to make sure that the source manager's state
1034 // before and after are identical, so that we can reuse the source
1035 // location itself.
1036 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1037 if (StoredDiagnostics[I].getLocation().isValid()) {
1038 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1039 StoredDiagnostics[I].setLocation(Loc);
1040 }
1041 }
1042}
1043
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001044/// Parse the source file into a translation unit using the given compiler
1045/// invocation, replacing the current translation unit.
1046///
1047/// \returns True if a failure occurred that causes the ASTUnit not to
1048/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001049bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001050 delete SavedMainFileBuffer;
1051 SavedMainFileBuffer = 0;
1052
Ted Kremenek5e14d392011-03-21 18:40:17 +00001053 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001054 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001055 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001056 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001057
Daniel Dunbar764c0822009-12-01 09:51:01 +00001058 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001059 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001060
1061 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001062 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1063 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001064
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001065 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001066 CCInvocation(new CompilerInvocation(*Invocation));
1067
1068 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001069 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070
Douglas Gregor8e984da2010-08-04 16:47:14 +00001071 // Set up diagnostics, capturing any diagnostics that would
1072 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001073 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001074
Daniel Dunbar764c0822009-12-01 09:51:01 +00001075 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001076 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001077 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001078 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001079 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001080 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001081 }
1082
Daniel Dunbar764c0822009-12-01 09:51:01 +00001083 // Inform the target of the language options.
1084 //
1085 // FIXME: We shouldn't need to do this, the target should be immutable once
1086 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001087 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001088
Ted Kremenek84de4a12011-03-21 18:40:07 +00001089 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001090 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001091 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001092 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001093 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001094 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001095
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001096 // Configure the various subsystems.
1097 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001098 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001100 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001101 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1102 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001103 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001104 Ctx = 0;
1105 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001106 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001107
1108 // Clear out old caches and data.
1109 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001110 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001111 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001112
Douglas Gregor7b02b582010-08-20 00:02:33 +00001113 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001114 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001115 TopLevelDeclsInPreamble.clear();
1116 }
1117
Daniel Dunbar764c0822009-12-01 09:51:01 +00001118 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001119 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001120
Daniel Dunbar764c0822009-12-01 09:51:01 +00001121 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001122 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001123
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001124 // If the main file has been overridden due to the use of a preamble,
1125 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001126 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001127 if (OverrideMainBuffer) {
1128 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1129 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1130 PreprocessorOpts.PrecompiledPreambleBytes.second
1131 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001132 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001133 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001134
Douglas Gregord9a30af2010-08-02 20:51:39 +00001135 // The stored diagnostic has the old source manager in it; update
1136 // the locations to refer into the new source manager. Since we've
1137 // been careful to make sure that the source manager's state
1138 // before and after are identical, so that we can reuse the source
1139 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001140 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001141
1142 // Keep track of the override buffer;
1143 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001144 }
1145
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001146 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001147 new TopLevelDeclTrackerAction(*this));
1148
1149 // Recover resources if we crash before exiting this method.
1150 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1151 ActCleanup(Act.get());
1152
Douglas Gregor32fbe312012-01-20 16:28:04 +00001153 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001154 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001155
1156 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001157 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001158 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1159 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001160 }
1161
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001162 if (!Act->Execute())
1163 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001164
1165 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001166
Daniel Dunbar644dca02009-12-04 08:17:33 +00001167 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001168
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001169 FailedParseDiagnostics.clear();
1170
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001171 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001172
Daniel Dunbar764c0822009-12-01 09:51:01 +00001173error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001174 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001175 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001176 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001177 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001178 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001179
1180 // Keep the ownership of the data in the ASTUnit because the client may
1181 // want to see the diagnostics.
1182 transferASTDataFromCompilerInstance(*Clang);
1183 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001184 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001185 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001186 return true;
1187}
1188
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189/// \brief Simple function to retrieve a path for a preamble precompiled header.
1190static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001191 // FIXME: This is a hack so that we can override the preamble file during
1192 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001193 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001194 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1195 if (TmpFile)
1196 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001197
1198 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001199 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001200
1201 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001202}
1203
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001204/// \brief Compute the preamble for the main file, providing the source buffer
1205/// that corresponds to the main file along with a pair (bytes, start-of-line)
1206/// that describes the preamble.
1207std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001208ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1209 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001211 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001212 CreatedBuffer = false;
1213
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001214 // Try to determine if the main file has been remapped, either from the
1215 // command line (to another file) or directly through the compiler invocation
1216 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001217 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001218 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001219 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001220 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001221 // Check whether there is a file-file remapping of the main file
1222 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001223 M = PreprocessorOpts.remapped_file_begin(),
1224 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001225 M != E;
1226 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001227 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001228 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001229 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001230 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001231 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001232 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001233 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001234 CreatedBuffer = false;
1235 }
1236
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001237 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001239 return std::make_pair((llvm::MemoryBuffer*)0,
1240 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001241 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001242 }
1243 }
1244 }
1245
1246 // Check whether there is a file-buffer remapping. It supercedes the
1247 // file-file remapping.
1248 for (PreprocessorOptions::remapped_file_buffer_iterator
1249 M = PreprocessorOpts.remapped_file_buffer_begin(),
1250 E = PreprocessorOpts.remapped_file_buffer_end();
1251 M != E;
1252 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001253 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001254 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001255 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001256 if (MainFileID == MID) {
1257 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001258 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001259 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001260 CreatedBuffer = false;
1261 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001262
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001264 }
1265 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001266 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001267 }
1268
1269 // If the main source file was not remapped, load it now.
1270 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001271 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001272 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001273 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001274
1275 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001276 }
1277
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001278 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001279 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001280 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001281}
1282
Douglas Gregor6481ef12010-07-24 00:38:13 +00001283static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001284 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001285 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001286 llvm::MemoryBuffer *Result
1287 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1288 memcpy(const_cast<char*>(Result->getBufferStart()),
1289 Old->getBufferStart(), Old->getBufferSize());
1290 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001291 ' ', NewSize - Old->getBufferSize() - 1);
1292 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001293
Douglas Gregor6481ef12010-07-24 00:38:13 +00001294 return Result;
1295}
1296
Dmitri Gribenko47652522013-12-20 00:16:25 +00001297ASTUnit::PreambleFileHash
1298ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1299 PreambleFileHash Result;
1300 Result.Size = Size;
1301 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001302 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001303 return Result;
1304}
1305
1306ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1307 const llvm::MemoryBuffer *Buffer) {
1308 PreambleFileHash Result;
1309 Result.Size = Buffer->getBufferSize();
1310 Result.ModTime = 0;
1311
1312 llvm::MD5 MD5Ctx;
1313 MD5Ctx.update(Buffer->getBuffer().data());
1314 MD5Ctx.final(Result.MD5);
1315
1316 return Result;
1317}
1318
1319namespace clang {
1320bool operator==(const ASTUnit::PreambleFileHash &LHS,
1321 const ASTUnit::PreambleFileHash &RHS) {
1322 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001323 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001324}
1325} // namespace clang
1326
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001327static std::pair<unsigned, unsigned>
1328makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1329 const LangOptions &LangOpts) {
1330 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1331 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1332 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1333 return std::make_pair(Offset, EndOffset);
1334}
1335
1336static void makeStandaloneFixIt(const SourceManager &SM,
1337 const LangOptions &LangOpts,
1338 const FixItHint &InFix,
1339 ASTUnit::StandaloneFixIt &OutFix) {
1340 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1341 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1342 LangOpts);
1343 OutFix.CodeToInsert = InFix.CodeToInsert;
1344 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1345}
1346
1347static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1348 const StoredDiagnostic &InDiag,
1349 ASTUnit::StandaloneDiagnostic &OutDiag) {
1350 OutDiag.ID = InDiag.getID();
1351 OutDiag.Level = InDiag.getLevel();
1352 OutDiag.Message = InDiag.getMessage();
1353 OutDiag.LocOffset = 0;
1354 if (InDiag.getLocation().isInvalid())
1355 return;
1356 const SourceManager &SM = InDiag.getLocation().getManager();
1357 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1358 OutDiag.Filename = SM.getFilename(FileLoc);
1359 if (OutDiag.Filename.empty())
1360 return;
1361 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1362 for (StoredDiagnostic::range_iterator
1363 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1364 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1365 }
1366 for (StoredDiagnostic::fixit_iterator
1367 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1368 ASTUnit::StandaloneFixIt Fix;
1369 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1370 OutDiag.FixIts.push_back(Fix);
1371 }
1372}
1373
Douglas Gregor4dde7492010-07-23 23:58:40 +00001374/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1375/// the source file.
1376///
1377/// This routine will compute the preamble of the main source file. If a
1378/// non-trivial preamble is found, it will precompile that preamble into a
1379/// precompiled header so that the precompiled preamble can be used to reduce
1380/// reparsing time. If a precompiled preamble has already been constructed,
1381/// this routine will determine if it is still valid and, if so, avoid
1382/// rebuilding the precompiled preamble.
1383///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001384/// \param AllowRebuild When true (the default), this routine is
1385/// allowed to rebuild the precompiled preamble if it is found to be
1386/// out-of-date.
1387///
1388/// \param MaxLines When non-zero, the maximum number of lines that
1389/// can occur within the preamble.
1390///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001391/// \returns If the precompiled preamble can be used, returns a newly-allocated
1392/// buffer that should be used in place of the main file when doing so.
1393/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001394llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001395 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001396 bool AllowRebuild,
1397 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001398
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001399 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001400 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1401 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001402 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001403 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001404
1405 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001406 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001407 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001408
Douglas Gregor925296b2011-07-19 16:10:42 +00001409 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001410 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001411 if (CreatedPreambleBuffer)
1412 OwnedPreambleBuffer.reset(NewPreamble.first);
1413
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001414 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001415 // We couldn't find a preamble in the main source. Clear out the current
1416 // preamble, if we have one. It's obviously no good any more.
1417 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001418 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001419
1420 // The next time we actually see a preamble, precompile it.
1421 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001422 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001423 }
1424
1425 if (!Preamble.empty()) {
1426 // We've previously computed a preamble. Check whether we have the same
1427 // preamble now that we did before, and that there's enough space in
1428 // the main-file buffer within the precompiled preamble to fit the
1429 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001430 if (Preamble.size() == NewPreamble.second.first &&
1431 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001432 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001433 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001434 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001435 // The preamble has not changed. We may be able to re-use the precompiled
1436 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001437
Douglas Gregor0e119552010-07-31 00:40:00 +00001438 // Check that none of the files used by the preamble have changed.
1439 bool AnyFileChanged = false;
1440
1441 // First, make a record of those files that have been overridden via
1442 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001443 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregor0e119552010-07-31 00:40:00 +00001444 for (PreprocessorOptions::remapped_file_iterator
1445 R = PreprocessorOpts.remapped_file_begin(),
1446 REnd = PreprocessorOpts.remapped_file_end();
1447 !AnyFileChanged && R != REnd;
1448 ++R) {
Ben Langmuirc8130a72014-02-20 21:59:23 +00001449 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001450 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001451 // If we can't stat the file we're remapping to, assume that something
1452 // horrible happened.
1453 AnyFileChanged = true;
1454 break;
1455 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001456
Dmitri Gribenko47652522013-12-20 00:16:25 +00001457 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001458 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001459 }
1460 for (PreprocessorOptions::remapped_file_buffer_iterator
1461 R = PreprocessorOpts.remapped_file_buffer_begin(),
1462 REnd = PreprocessorOpts.remapped_file_buffer_end();
1463 !AnyFileChanged && R != REnd;
1464 ++R) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001465 OverriddenFiles[R->first] =
1466 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001467 }
1468
1469 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001470 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001471 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1472 !AnyFileChanged && F != FEnd;
1473 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001474 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001475 = OverriddenFiles.find(F->first());
1476 if (Overridden != OverriddenFiles.end()) {
1477 // This file was remapped; check whether the newly-mapped file
1478 // matches up with the previous mapping.
1479 if (Overridden->second != F->second)
1480 AnyFileChanged = true;
1481 continue;
1482 }
1483
1484 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001485 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001486 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001487 // If we can't stat the file, assume that something horrible happened.
1488 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001489 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001490 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001491 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001492 AnyFileChanged = true;
1493 }
1494
1495 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001496 // Okay! We can re-use the precompiled preamble.
1497
1498 // Set the state of the diagnostic object to mimic its state
1499 // after parsing the preamble.
1500 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001501 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001502 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001503 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001504
1505 // Create a version of the main file buffer that is padded to
1506 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001507 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001508 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001509 FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001510 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001511 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001512
1513 // If we aren't allowed to rebuild the precompiled preamble, just
1514 // return now.
1515 if (!AllowRebuild)
1516 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001517
Douglas Gregor4dde7492010-07-23 23:58:40 +00001518 // We can't reuse the previously-computed preamble. Build a new one.
1519 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001520 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001521 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001522 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001523 } else if (!AllowRebuild) {
1524 // We aren't allowed to rebuild the precompiled preamble; just
1525 // return now.
1526 return 0;
1527 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001528
1529 // If the preamble rebuild counter > 1, it's because we previously
1530 // failed to build a preamble and we're not yet ready to try
1531 // again. Decrement the counter and return a failure.
1532 if (PreambleRebuildCounter > 1) {
1533 --PreambleRebuildCounter;
1534 return 0;
1535 }
1536
Douglas Gregore10f0e52010-09-11 17:56:52 +00001537 // Create a temporary file for the precompiled preamble. In rare
1538 // circumstances, this can fail.
1539 std::string PreamblePCHPath = GetPreamblePCHPath();
1540 if (PreamblePCHPath.empty()) {
1541 // Try again next time.
1542 PreambleRebuildCounter = 1;
1543 return 0;
1544 }
1545
Douglas Gregor4dde7492010-07-23 23:58:40 +00001546 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001547 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001548 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001549
1550 // Create a new buffer that stores the preamble. The buffer also contains
1551 // extra space for the original contents of the file (which will be present
1552 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001553 // grows.
1554 PreambleReservedSize = NewPreamble.first->getBufferSize();
1555 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001556 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001557 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001558 PreambleReservedSize *= 2;
1559
Douglas Gregord9a30af2010-08-02 20:51:39 +00001560 // Save the preamble text for later; we'll need to compare against it for
1561 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001562 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001563 Preamble.assign(FileMgr->getFile(MainFilename),
1564 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001565 NewPreamble.first->getBufferStart()
1566 + NewPreamble.second.first);
1567 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1568
Douglas Gregora0734c52010-08-19 01:33:06 +00001569 delete PreambleBuffer;
1570 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001571 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001572 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001573 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001574 NewPreamble.first->getBufferStart(), Preamble.size());
1575 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001576 ' ', PreambleReservedSize - Preamble.size() - 1);
1577 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001578
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001579 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001580 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1581 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1582
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001583 // Tell the compiler invocation to generate a temporary precompiled header.
1584 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001585 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001586 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001587 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1588 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001589
1590 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001591 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001592
1593 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001594 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1595 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001596
Douglas Gregor3cc15812011-07-01 18:22:13 +00001597 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001598 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001599
Douglas Gregor8e984da2010-08-04 16:47:14 +00001600 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001601 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001602
1603 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001604 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001605 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001606 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001607 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001608 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001609 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001610 PreprocessorOpts.eraseRemappedFile(
1611 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001612 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001613 }
1614
1615 // Inform the target of the language options.
1616 //
1617 // FIXME: We shouldn't need to do this, the target should be immutable once
1618 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001619 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001620
Ted Kremenek84de4a12011-03-21 18:40:07 +00001621 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001622 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001623 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001624 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001625 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001626 "IR inputs not support here!");
1627
1628 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001629 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001630 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001631 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001632 TopLevelDecls.clear();
1633 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001634 PreambleDiagnostics.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001635
1636 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001637 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001638
1639 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001640 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001641 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001642
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001643 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001644 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001645 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001646 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001647 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001648 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001649 PreprocessorOpts.eraseRemappedFile(
1650 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001651 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001652 }
1653
1654 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001655
1656 // Transfer any diagnostics generated when parsing the preamble into the set
1657 // of preamble diagnostics.
1658 for (stored_diag_iterator
1659 I = stored_diag_afterDriver_begin(),
1660 E = stored_diag_end(); I != E; ++I) {
1661 StandaloneDiagnostic Diag;
1662 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1663 PreambleDiagnostics.push_back(Diag);
1664 }
1665
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001666 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001667
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001668 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1669
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001670 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001671 // The preamble PCH failed (e.g. there was a module loading fatal error),
1672 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001673 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001674 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001675 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001676 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001677 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001678 PreprocessorOpts.eraseRemappedFile(
1679 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001680 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001681 }
1682
1683 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001684 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001685 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001686
1687 // Keep track of all of the files that the source manager knows about,
1688 // so we can verify whether they have changed or not.
1689 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001690 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001691 const llvm::MemoryBuffer *MainFileBuffer
1692 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1693 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1694 FEnd = SourceMgr.fileinfo_end();
1695 F != FEnd;
1696 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001697 const FileEntry *File = F->second->OrigEntry;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001698 if (!File)
Douglas Gregor0e119552010-07-31 00:40:00 +00001699 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001700 const llvm::MemoryBuffer *Buffer = F->second->getRawBuffer();
1701 if (Buffer == MainFileBuffer)
1702 continue;
1703
1704 if (time_t ModTime = File->getModificationTime()) {
1705 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1706 F->second->getSize(), ModTime);
1707 } else {
1708 assert(F->second->getSize() == Buffer->getBufferSize());
1709 FilesInPreamble[File->getName()] =
1710 PreambleFileHash::createForMemoryBuffer(Buffer);
1711 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001712 }
1713
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001714 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001715 PreprocessorOpts.eraseRemappedFile(
1716 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001717
1718 // If the hash of top-level entities differs from the hash of the top-level
1719 // entities the last time we rebuilt the preamble, clear out the completion
1720 // cache.
1721 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1722 CompletionCacheTopLevelHashValue = 0;
1723 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1724 }
1725
Douglas Gregor6481ef12010-07-24 00:38:13 +00001726 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001727 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001728 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001729}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001730
Douglas Gregore9db88f2010-08-03 19:06:41 +00001731void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1732 std::vector<Decl *> Resolved;
1733 Resolved.reserve(TopLevelDeclsInPreamble.size());
1734 ExternalASTSource &Source = *getASTContext().getExternalSource();
1735 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1736 // Resolve the declaration ID to an actual declaration, possibly
1737 // deserializing the declaration in the process.
1738 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1739 if (D)
1740 Resolved.push_back(D);
1741 }
1742 TopLevelDeclsInPreamble.clear();
1743 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1744}
1745
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001746void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1747 // Steal the created target, context, and preprocessor.
1748 TheSema.reset(CI.takeSema());
1749 Consumer.reset(CI.takeASTConsumer());
1750 Ctx = &CI.getASTContext();
1751 PP = &CI.getPreprocessor();
1752 CI.setSourceManager(0);
1753 CI.setFileManager(0);
1754 Target = &CI.getTarget();
1755 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001756 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001757}
1758
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001759StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001760 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1761 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1762 if (Input.isFile())
1763 return Input.getFile();
1764 else
1765 return Input.getBuffer()->getBufferIdentifier();
1766 }
1767
1768 if (SourceMgr) {
1769 if (const FileEntry *
1770 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1771 return FE->getName();
1772 }
1773
1774 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001775}
1776
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001777StringRef ASTUnit::getASTFileName() const {
1778 if (!isMainFileAST())
1779 return StringRef();
1780
1781 serialization::ModuleFile &
1782 Mod = Reader->getModuleManager().getPrimaryModule();
1783 return Mod.FileName;
1784}
1785
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001786ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001787 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001788 bool CaptureDiagnostics,
1789 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001790 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001791 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001792 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001793 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001794 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001795 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001796 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001797 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1798 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1799 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001800
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001801 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001802}
1803
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001804ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001805 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001806 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001807 ASTUnit *Unit,
1808 bool Persistent,
1809 StringRef ResourceFilesPath,
1810 bool OnlyLocalDecls,
1811 bool CaptureDiagnostics,
1812 bool PrecompilePreamble,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001813 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001814 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001815 bool UserFilesAreVolatile,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001816 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001817 assert(CI && "A CompilerInvocation is required");
1818
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001819 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001820 ASTUnit *AST = Unit;
1821 if (!AST) {
1822 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001823 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001824 AST = OwnAST.get();
1825 }
1826
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001827 if (!ResourceFilesPath.empty()) {
1828 // Override the resources path.
1829 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1830 }
1831 AST->OnlyLocalDecls = OnlyLocalDecls;
1832 AST->CaptureDiagnostics = CaptureDiagnostics;
1833 if (PrecompilePreamble)
1834 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001835 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001836 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001837 AST->IncludeBriefCommentsInCodeCompletion
1838 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001839
1840 // Recover resources if we crash before exiting this method.
1841 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001842 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001843 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1844 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001845 DiagCleanup(Diags.getPtr());
1846
1847 // We'll manage file buffers ourselves.
1848 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1849 CI->getFrontendOpts().DisableFree = false;
1850 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1851
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001852 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001853 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001854
1855 // Recover resources if we crash before exiting this method.
1856 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1857 CICleanup(Clang.get());
1858
1859 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001860 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001861
1862 // Set up diagnostics, capturing any diagnostics that would
1863 // otherwise be dropped.
1864 Clang->setDiagnostics(&AST->getDiagnostics());
1865
1866 // Create the target instance.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001867 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001868 &Clang->getTargetOpts()));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001869 if (!Clang->hasTarget())
1870 return 0;
1871
1872 // Inform the target of the language options.
1873 //
1874 // FIXME: We shouldn't need to do this, the target should be immutable once
1875 // created. This complexity should be lifted elsewhere.
1876 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1877
1878 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1879 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001880 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001881 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001882 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001883 "IR inputs not supported here!");
1884
1885 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001886 AST->TheSema.reset();
1887 AST->Ctx = 0;
1888 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001889 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001890
1891 // Create a file manager object to provide access to and cache the filesystem.
1892 Clang->setFileManager(&AST->getFileManager());
1893
1894 // Create the source manager.
1895 Clang->setSourceManager(&AST->getSourceManager());
1896
1897 ASTFrontendAction *Act = Action;
1898
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001899 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001900 if (!Act) {
1901 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1902 Act = TrackerAct.get();
1903 }
1904
1905 // Recover resources if we crash before exiting this method.
1906 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1907 ActCleanup(TrackerAct.get());
1908
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001909 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1910 AST->transferASTDataFromCompilerInstance(*Clang);
1911 if (OwnAST && ErrAST)
1912 ErrAST->swap(OwnAST);
1913
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001914 return 0;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001915 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001916
1917 if (Persistent && !TrackerAct) {
1918 Clang->getPreprocessor().addPPCallbacks(
1919 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1920 std::vector<ASTConsumer*> Consumers;
1921 if (Clang->hasASTConsumer())
1922 Consumers.push_back(Clang->takeASTConsumer());
1923 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1924 AST->getCurrentTopLevelHashValue()));
1925 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1926 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001927 if (!Act->Execute()) {
1928 AST->transferASTDataFromCompilerInstance(*Clang);
1929 if (OwnAST && ErrAST)
1930 ErrAST->swap(OwnAST);
1931
1932 return 0;
1933 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001934
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001935 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001936 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001937
1938 Act->EndSourceFile();
1939
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001940 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001941 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001942 else
1943 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001944}
1945
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001946bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1947 if (!Invocation)
1948 return true;
1949
1950 // We'll manage file buffers ourselves.
1951 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1952 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001953 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001954
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001955 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001956 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001957 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001958 OverrideMainBuffer
1959 = getMainBufferWithPrecompiledPreamble(*Invocation);
1960 }
1961
Douglas Gregor16896c42010-10-28 15:44:59 +00001962 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001963 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001964
Ted Kremenek022a4902011-03-22 01:15:24 +00001965 // Recover resources if we crash before exiting this method.
1966 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1967 MemBufferCleanup(OverrideMainBuffer);
1968
Douglas Gregor16896c42010-10-28 15:44:59 +00001969 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001970}
1971
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001972ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001973 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001974 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001975 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001976 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001977 TranslationUnitKind TUKind,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001978 bool CacheCodeCompletionResults,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001979 bool IncludeBriefCommentsInCodeCompletion,
1980 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001981 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001982 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001983 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001984 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001985 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001986 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001987 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001988 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001989 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001990 AST->IncludeBriefCommentsInCodeCompletion
1991 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001992 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001993 AST->FileSystemOpts = CI->getFileSystemOpts();
1994 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001995 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001996
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001997 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001998 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1999 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00002000 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2001 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00002002 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002003
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002004 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0
2005 : AST.release();
Daniel Dunbar764c0822009-12-01 09:51:01 +00002006}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002007
2008ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
2009 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002010 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002011 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002012 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002013 bool CaptureDiagnostics,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002014 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00002015 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00002016 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00002017 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002018 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002019 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002020 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6e922512012-04-12 10:11:59 +00002021 bool SkipFunctionBodies,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002022 bool UserFilesAreVolatile,
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002023 bool ForSerialization,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002024 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00002025 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00002026 // No diagnostics engine was provided, so create our own diagnostics object
2027 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00002028 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00002029 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002030
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002031 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002032
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002033 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002034
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002035 {
Douglas Gregor925296b2011-07-19 16:10:42 +00002036
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002037 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002038 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00002039
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00002040 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002041 llvm::makeArrayRef(ArgBegin, ArgEnd),
2042 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00002043 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00002044 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002045 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002046
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002047 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002048 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002049 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2050 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002051 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002052 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2053 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2054 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002055
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002056 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002057 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002058
Erik Verbruggen6e922512012-04-12 10:11:59 +00002059 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2060
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002061 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002062 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002063 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002064 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002065 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00002066 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002067 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00002068 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002069 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002070 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002071 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002072 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002073 AST->IncludeBriefCommentsInCodeCompletion
2074 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002075 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002076 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002077 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002078 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002079 if (ForSerialization)
2080 AST->WriterData.reset(new ASTWriterData());
Ted Kremenek25047602011-11-17 23:01:17 +00002081 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002082
2083 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002084 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2085 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002086
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002087 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2088 // Some error occurred, if caller wants to examine diagnostics, pass it the
2089 // ASTUnit.
2090 if (ErrAST) {
2091 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2092 ErrAST->swap(AST);
2093 }
2094 return 0;
2095 }
2096
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002097 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002098}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002099
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002100bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002101 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002102 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002103
2104 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002105
Douglas Gregor16896c42010-10-28 15:44:59 +00002106 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002107 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002108
Douglas Gregor0e119552010-07-31 00:40:00 +00002109 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002110 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2111 for (PreprocessorOptions::remapped_file_buffer_iterator
2112 R = PPOpts.remapped_file_buffer_begin(),
2113 REnd = PPOpts.remapped_file_buffer_end();
2114 R != REnd;
2115 ++R) {
2116 delete R->second;
2117 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002118 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002119 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002120 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2121 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002122 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002123
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002124 // If we have a preamble file lying around, or if we might try to
2125 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00002126 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002127 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002128 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002129
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002130 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002131 getDiagnostics().Reset();
2132 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002133 if (OverrideMainBuffer)
2134 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002135
Douglas Gregor4dde7492010-07-23 23:58:40 +00002136 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002137 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002138
2139 // If we're caching global code-completion results, and the top-level
2140 // declarations have changed, clear out the code-completion cache.
2141 if (!Result && ShouldCacheCodeCompletionResults &&
2142 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2143 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002144
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002145 // We now need to clear out the completion info related to this translation
2146 // unit; it'll be recreated if necessary.
2147 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002148
Douglas Gregor4dde7492010-07-23 23:58:40 +00002149 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002150}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002151
Douglas Gregorb14904c2010-08-13 22:48:40 +00002152//----------------------------------------------------------------------------//
2153// Code completion
2154//----------------------------------------------------------------------------//
2155
2156namespace {
2157 /// \brief Code completion consumer that combines the cached code-completion
2158 /// results from an ASTUnit with the code-completion results provided to it,
2159 /// then passes the result on to
2160 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002161 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002162 ASTUnit &AST;
2163 CodeCompleteConsumer &Next;
2164
2165 public:
2166 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002167 const CodeCompleteOptions &CodeCompleteOpts)
2168 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2169 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002170 {
2171 // Compute the set of contexts in which we will look when we don't have
2172 // any information about the specific context.
2173 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002174 = (1LL << CodeCompletionContext::CCC_TopLevel)
2175 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2176 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2177 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2178 | (1LL << CodeCompletionContext::CCC_Statement)
2179 | (1LL << CodeCompletionContext::CCC_Expression)
2180 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2181 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2182 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2183 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2184 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2185 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2186 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002187
David Blaikiebbafb8a2012-03-11 07:00:24 +00002188 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002189 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2190 | (1LL << CodeCompletionContext::CCC_UnionTag)
2191 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002192 }
2193
2194 virtual void ProcessCodeCompleteResults(Sema &S,
2195 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002196 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002197 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002198
2199 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2200 OverloadCandidate *Candidates,
2201 unsigned NumCandidates) {
2202 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2203 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002204
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002205 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002206 return Next.getAllocator();
2207 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002208
2209 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2210 return Next.getCodeCompletionTUInfo();
2211 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002212 };
2213}
Douglas Gregord46cf182010-08-16 20:01:48 +00002214
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002215/// \brief Helper function that computes which global names are hidden by the
2216/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002217static void CalculateHiddenNames(const CodeCompletionContext &Context,
2218 CodeCompletionResult *Results,
2219 unsigned NumResults,
2220 ASTContext &Ctx,
2221 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002222 bool OnlyTagNames = false;
2223 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002224 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002225 case CodeCompletionContext::CCC_TopLevel:
2226 case CodeCompletionContext::CCC_ObjCInterface:
2227 case CodeCompletionContext::CCC_ObjCImplementation:
2228 case CodeCompletionContext::CCC_ObjCIvarList:
2229 case CodeCompletionContext::CCC_ClassStructUnion:
2230 case CodeCompletionContext::CCC_Statement:
2231 case CodeCompletionContext::CCC_Expression:
2232 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002233 case CodeCompletionContext::CCC_DotMemberAccess:
2234 case CodeCompletionContext::CCC_ArrowMemberAccess:
2235 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002236 case CodeCompletionContext::CCC_Namespace:
2237 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002238 case CodeCompletionContext::CCC_Name:
2239 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002240 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002241 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002242 break;
2243
2244 case CodeCompletionContext::CCC_EnumTag:
2245 case CodeCompletionContext::CCC_UnionTag:
2246 case CodeCompletionContext::CCC_ClassOrStructTag:
2247 OnlyTagNames = true;
2248 break;
2249
2250 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002251 case CodeCompletionContext::CCC_MacroName:
2252 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002253 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002254 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002255 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002256 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002257 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002258 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002259 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002260 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2261 case CodeCompletionContext::CCC_ObjCClassMessage:
2262 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002263 // We're looking for nothing, or we're looking for names that cannot
2264 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002265 return;
2266 }
2267
John McCall276321a2010-08-25 06:19:51 +00002268 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002269 for (unsigned I = 0; I != NumResults; ++I) {
2270 if (Results[I].Kind != Result::RK_Declaration)
2271 continue;
2272
2273 unsigned IDNS
2274 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2275
2276 bool Hiding = false;
2277 if (OnlyTagNames)
2278 Hiding = (IDNS & Decl::IDNS_Tag);
2279 else {
2280 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002281 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2282 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002283 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002284 HiddenIDNS |= Decl::IDNS_Tag;
2285 Hiding = (IDNS & HiddenIDNS);
2286 }
2287
2288 if (!Hiding)
2289 continue;
2290
2291 DeclarationName Name = Results[I].Declaration->getDeclName();
2292 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2293 HiddenNames.insert(Identifier->getName());
2294 else
2295 HiddenNames.insert(Name.getAsString());
2296 }
2297}
2298
2299
Douglas Gregord46cf182010-08-16 20:01:48 +00002300void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2301 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002302 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002303 unsigned NumResults) {
2304 // Merge the results we were given with the results we cached.
2305 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002306 uint64_t InContexts =
2307 Context.getKind() == CodeCompletionContext::CCC_Recovery
2308 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002309 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002310 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002311 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002312 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002313 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002314 C = AST.cached_completion_begin(),
2315 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002316 C != CEnd; ++C) {
2317 // If the context we are in matches any of the contexts we are
2318 // interested in, we'll add this result.
2319 if ((C->ShowInContexts & InContexts) == 0)
2320 continue;
2321
2322 // If we haven't added any results previously, do so now.
2323 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002324 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2325 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002326 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2327 AddedResult = true;
2328 }
2329
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002330 // Determine whether this global completion result is hidden by a local
2331 // completion result. If so, skip it.
2332 if (C->Kind != CXCursor_MacroDefinition &&
2333 HiddenNames.count(C->Completion->getTypedText()))
2334 continue;
2335
Douglas Gregord46cf182010-08-16 20:01:48 +00002336 // Adjust priority based on similar type classes.
2337 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002338 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002339 if (!Context.getPreferredType().isNull()) {
2340 if (C->Kind == CXCursor_MacroDefinition) {
2341 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002342 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002343 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002344 } else if (C->Type) {
2345 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002346 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002347 Context.getPreferredType().getUnqualifiedType());
2348 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2349 if (ExpectedSTC == C->TypeClass) {
2350 // We know this type is similar; check for an exact match.
2351 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002352 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002353 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002354 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002355 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2356 Priority /= CCF_ExactTypeMatch;
2357 else
2358 Priority /= CCF_SimilarTypeMatch;
2359 }
2360 }
2361 }
2362
Douglas Gregor12785102010-08-24 20:21:13 +00002363 // Adjust the completion string, if required.
2364 if (C->Kind == CXCursor_MacroDefinition &&
2365 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2366 // Create a new code-completion string that just contains the
2367 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002368 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2369 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002370 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002371 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002372 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002373 }
2374
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002375 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002376 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002377 }
2378
2379 // If we did not add any cached completion results, just forward the
2380 // results we were given to the next consumer.
2381 if (!AddedResult) {
2382 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2383 return;
2384 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002385
Douglas Gregord46cf182010-08-16 20:01:48 +00002386 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2387 AllResults.size());
2388}
2389
2390
2391
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002392void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002393 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002394 bool IncludeMacros,
2395 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002396 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002397 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002398 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002399 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002400 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2401 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002402 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002403 return;
2404
Douglas Gregor16896c42010-10-28 15:44:59 +00002405 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002406 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002407 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002408
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002409 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002410 CCInvocation(new CompilerInvocation(*Invocation));
2411
2412 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002413 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002414 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002415
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002416 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2417 CachedCompletionResults.empty();
2418 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2419 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2420 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2421
2422 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2423
Douglas Gregor8e984da2010-08-04 16:47:14 +00002424 FrontendOpts.CodeCompletionAt.FileName = File;
2425 FrontendOpts.CodeCompletionAt.Line = Line;
2426 FrontendOpts.CodeCompletionAt.Column = Column;
2427
2428 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002429 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002430
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002431 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002432
2433 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002434 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2435 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002436
Ted Kremenek5e14d392011-03-21 18:40:17 +00002437 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002438 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002439
2440 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002441 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002442 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002443 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002444 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002445 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002446
2447 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002448 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00002449 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002450 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002451 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002452 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002453 }
2454
2455 // Inform the target of the language options.
2456 //
2457 // FIXME: We shouldn't need to do this, the target should be immutable once
2458 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002459 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002460
Ted Kremenek84de4a12011-03-21 18:40:07 +00002461 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002462 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002463 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002464 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002465 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002466 "IR inputs not support here!");
2467
2468
2469 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002470 Clang->setFileManager(&FileMgr);
2471 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002472
2473 // Remap files.
2474 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002475 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002476 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002477 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2478 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002479 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002480 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002481
Douglas Gregorb14904c2010-08-13 22:48:40 +00002482 // Use the code completion consumer we were given, but adding any cached
2483 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002484 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002485 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002486 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002487
Douglas Gregor028d3e42010-08-09 20:45:32 +00002488 // If we have a precompiled preamble, try to use it. We only allow
2489 // the use of the precompiled preamble if we're if the completion
2490 // point is within the main file, after the end of the precompiled
2491 // preamble.
2492 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002493 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002494 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002495 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002496
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002497 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002498 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002499 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002500 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002501 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002502 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002503 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002504 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002505 }
2506 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002507 }
2508
2509 // If the main file has been overridden due to the use of a preamble,
2510 // make that override happen and introduce the preamble.
2511 if (OverrideMainBuffer) {
2512 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2513 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2514 PreprocessorOpts.PrecompiledPreambleBytes.second
2515 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002516 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002517 PreprocessorOpts.DisablePCHValidation = true;
2518
Douglas Gregorb97b6662010-08-20 00:59:43 +00002519 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002520 } else {
2521 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2522 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002523 }
2524
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002525 // Disable the preprocessing record if modules are not enabled.
2526 if (!Clang->getLangOpts().Modules)
2527 PreprocessorOpts.DetailedRecord = false;
Douglas Gregor998caea2011-05-06 16:33:08 +00002528
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002529 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002530 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002531 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002532 Act->Execute();
2533 Act->EndSourceFile();
2534 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002535}
Douglas Gregore9386682010-08-13 05:36:37 +00002536
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002537bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002538 if (HadModuleLoaderFatalFailure)
2539 return true;
2540
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002541 // Write to a temporary file and later rename it to the actual file, to avoid
2542 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002543 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002544 TempPath = File;
2545 TempPath += "-%%%%%%%%";
2546 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002547 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002548 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002549
Douglas Gregore9386682010-08-13 05:36:37 +00002550 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2551 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002552 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002553
2554 serialize(Out);
2555 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002556 if (Out.has_error()) {
2557 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002558 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002559 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002560
Rafael Espindola65e025c2011-12-25 01:18:52 +00002561 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002562 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002563 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002564 }
2565
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002566 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002567}
2568
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002569static bool serializeUnit(ASTWriter &Writer,
2570 SmallVectorImpl<char> &Buffer,
2571 Sema &S,
2572 bool hasErrors,
2573 raw_ostream &OS) {
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00002574 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002575
2576 // Write the generated bitstream to "Out".
2577 if (!Buffer.empty())
2578 OS.write(Buffer.data(), Buffer.size());
2579
2580 return false;
2581}
2582
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002583bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002584 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002585
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002586 if (WriterData)
2587 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2588 getSema(), hasErrors, OS);
2589
Daniel Dunbar9a963862012-02-29 20:31:23 +00002590 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002591 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002592 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002593 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002594}
Douglas Gregor925296b2011-07-19 16:10:42 +00002595
2596typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2597
Douglas Gregor925296b2011-07-19 16:10:42 +00002598void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002599 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002600 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002601 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002602 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002603 // Map the standalone diagnostic into the new source manager. We also need to
2604 // remap all the locations to the new view. This includes the diag location,
2605 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002606 // FIXME: There should be a cleaner way to do this.
2607
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002608 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002609 Result.reserve(Diags.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00002610 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2611 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002612 const StandaloneDiagnostic &SD = Diags[I];
2613 if (SD.Filename.empty())
2614 continue;
2615 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2616 if (!FE)
2617 continue;
2618 FileID FID = SrcMgr.translateFile(FE);
2619 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2620 if (FileLoc.isInvalid())
2621 continue;
2622 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002623 FullSourceLoc Loc(L, SrcMgr);
2624
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002625 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002626 Ranges.reserve(SD.Ranges.size());
2627 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2628 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2629 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2630 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2631 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002632 }
2633
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002634 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002635 FixIts.reserve(SD.FixIts.size());
2636 for (std::vector<StandaloneFixIt>::const_iterator
2637 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregor925296b2011-07-19 16:10:42 +00002638 I != E; ++I) {
2639 FixIts.push_back(FixItHint());
2640 FixItHint &FH = FixIts.back();
2641 FH.CodeToInsert = I->CodeToInsert;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002642 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2643 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2644 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002645 }
2646
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002647 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2648 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002649 }
2650 Result.swap(Out);
2651}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002652
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002653void ASTUnit::addFileLevelDecl(Decl *D) {
2654 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002655
2656 // We only care about local declarations.
2657 if (D->isFromASTFile())
2658 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002659
2660 SourceManager &SM = *SourceMgr;
2661 SourceLocation Loc = D->getLocation();
2662 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2663 return;
2664
2665 // We only keep track of the file-level declarations of each file.
2666 if (!D->getLexicalDeclContext()->isFileContext())
2667 return;
2668
2669 SourceLocation FileLoc = SM.getFileLoc(Loc);
2670 assert(SM.isLocalSourceLocation(FileLoc));
2671 FileID FID;
2672 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002673 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002674 if (FID.isInvalid())
2675 return;
2676
2677 LocDeclsTy *&Decls = FileDecls[FID];
2678 if (!Decls)
2679 Decls = new LocDeclsTy();
2680
2681 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2682
2683 if (Decls->empty() || Decls->back().first <= Offset) {
2684 Decls->push_back(LocDecl);
2685 return;
2686 }
2687
Benjamin Kramer45025c02013-08-24 13:22:59 +00002688 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2689 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002690
2691 Decls->insert(I, LocDecl);
2692}
2693
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002694void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2695 SmallVectorImpl<Decl *> &Decls) {
2696 if (File.isInvalid())
2697 return;
2698
2699 if (SourceMgr->isLoadedFileID(File)) {
2700 assert(Ctx->getExternalSource() && "No external source!");
2701 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2702 Decls);
2703 }
2704
2705 FileDeclsTy::iterator I = FileDecls.find(File);
2706 if (I == FileDecls.end())
2707 return;
2708
2709 LocDeclsTy &LocDecls = *I->second;
2710 if (LocDecls.empty())
2711 return;
2712
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002713 LocDeclsTy::iterator BeginIt =
2714 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002715 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002716 if (BeginIt != LocDecls.begin())
2717 --BeginIt;
2718
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002719 // If we are pointing at a top-level decl inside an objc container, we need
2720 // to backtrack until we find it otherwise we will fail to report that the
2721 // region overlaps with an objc container.
2722 while (BeginIt != LocDecls.begin() &&
2723 BeginIt->second->isTopLevelDeclInObjCContainer())
2724 --BeginIt;
2725
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002726 LocDeclsTy::iterator EndIt = std::upper_bound(
2727 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002728 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002729 if (EndIt != LocDecls.end())
2730 ++EndIt;
2731
2732 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2733 Decls.push_back(DIt->second);
2734}
2735
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002736SourceLocation ASTUnit::getLocation(const FileEntry *File,
2737 unsigned Line, unsigned Col) const {
2738 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002739 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002740 return SM.getMacroArgExpandedLocation(Loc);
2741}
2742
2743SourceLocation ASTUnit::getLocation(const FileEntry *File,
2744 unsigned Offset) const {
2745 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002746 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002747 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2748}
2749
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002750/// \brief If \arg Loc is a loaded location from the preamble, returns
2751/// the corresponding local location of the main file, otherwise it returns
2752/// \arg Loc.
2753SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2754 FileID PreambleID;
2755 if (SourceMgr)
2756 PreambleID = SourceMgr->getPreambleFileID();
2757
2758 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2759 return Loc;
2760
2761 unsigned Offs;
2762 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2763 SourceLocation FileLoc
2764 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2765 return FileLoc.getLocWithOffset(Offs);
2766 }
2767
2768 return Loc;
2769}
2770
2771/// \brief If \arg Loc is a local location of the main file but inside the
2772/// preamble chunk, returns the corresponding loaded location from the
2773/// preamble, otherwise it returns \arg Loc.
2774SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2775 FileID PreambleID;
2776 if (SourceMgr)
2777 PreambleID = SourceMgr->getPreambleFileID();
2778
2779 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2780 return Loc;
2781
2782 unsigned Offs;
2783 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2784 Offs < Preamble.size()) {
2785 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2786 return FileLoc.getLocWithOffset(Offs);
2787 }
2788
2789 return Loc;
2790}
2791
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002792bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2793 FileID FID;
2794 if (SourceMgr)
2795 FID = SourceMgr->getPreambleFileID();
2796
2797 if (Loc.isInvalid() || FID.isInvalid())
2798 return false;
2799
2800 return SourceMgr->isInFileID(Loc, FID);
2801}
2802
2803bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2804 FileID FID;
2805 if (SourceMgr)
2806 FID = SourceMgr->getMainFileID();
2807
2808 if (Loc.isInvalid() || FID.isInvalid())
2809 return false;
2810
2811 return SourceMgr->isInFileID(Loc, FID);
2812}
2813
2814SourceLocation ASTUnit::getEndOfPreambleFileID() {
2815 FileID FID;
2816 if (SourceMgr)
2817 FID = SourceMgr->getPreambleFileID();
2818
2819 if (FID.isInvalid())
2820 return SourceLocation();
2821
2822 return SourceMgr->getLocForEndOfFile(FID);
2823}
2824
2825SourceLocation ASTUnit::getStartOfMainFileID() {
2826 FileID FID;
2827 if (SourceMgr)
2828 FID = SourceMgr->getMainFileID();
2829
2830 if (FID.isInvalid())
2831 return SourceLocation();
2832
2833 return SourceMgr->getLocForStartOfFile(FID);
2834}
2835
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002836std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2837ASTUnit::getLocalPreprocessingEntities() const {
2838 if (isMainFileAST()) {
2839 serialization::ModuleFile &
2840 Mod = Reader->getModuleManager().getPrimaryModule();
2841 return Reader->getModulePreprocessedEntities(Mod);
2842 }
2843
2844 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2845 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2846
2847 return std::make_pair(PreprocessingRecord::iterator(),
2848 PreprocessingRecord::iterator());
2849}
2850
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002851bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002852 if (isMainFileAST()) {
2853 serialization::ModuleFile &
2854 Mod = Reader->getModuleManager().getPrimaryModule();
2855 ASTReader::ModuleDeclIterator MDI, MDE;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002856 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002857 for (; MDI != MDE; ++MDI) {
2858 if (!Fn(context, *MDI))
2859 return false;
2860 }
2861
2862 return true;
2863 }
2864
2865 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2866 TLEnd = top_level_end();
2867 TL != TLEnd; ++TL) {
2868 if (!Fn(context, *TL))
2869 return false;
2870 }
2871
2872 return true;
2873}
2874
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002875namespace {
2876struct PCHLocatorInfo {
2877 serialization::ModuleFile *Mod;
2878 PCHLocatorInfo() : Mod(0) {}
2879};
2880}
2881
2882static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2883 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2884 switch (M.Kind) {
2885 case serialization::MK_Module:
2886 return true; // skip dependencies.
2887 case serialization::MK_PCH:
2888 Info.Mod = &M;
2889 return true; // found it.
2890 case serialization::MK_Preamble:
2891 return false; // look in dependencies.
2892 case serialization::MK_MainFile:
2893 return false; // look in dependencies.
2894 }
2895
2896 return true;
2897}
2898
2899const FileEntry *ASTUnit::getPCHFile() {
2900 if (!Reader)
2901 return 0;
2902
2903 PCHLocatorInfo Info;
2904 Reader->getModuleManager().visit(PCHLocator, &Info);
2905 if (Info.Mod)
2906 return Info.Mod->File;
2907
2908 return 0;
2909}
2910
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002911bool ASTUnit::isModuleFile() {
2912 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2913}
2914
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002915void ASTUnit::PreambleData::countLines() const {
2916 NumLines = 0;
2917 if (empty())
2918 return;
2919
2920 for (std::vector<char>::const_iterator
2921 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2922 if (*I == '\n')
2923 ++NumLines;
2924 }
2925 if (Buffer.back() != '\n')
2926 ++NumLines;
2927}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002928
2929#ifndef NDEBUG
2930ASTUnit::ConcurrencyState::ConcurrencyState() {
2931 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2932}
2933
2934ASTUnit::ConcurrencyState::~ConcurrencyState() {
2935 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2936}
2937
2938void ASTUnit::ConcurrencyState::start() {
2939 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2940 assert(acquired && "Concurrent access to ASTUnit!");
2941}
2942
2943void ASTUnit::ConcurrencyState::finish() {
2944 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2945}
2946
2947#else // NDEBUG
2948
Alp Tokerb159c132013-11-22 07:49:39 +00002949ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002950ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2951void ASTUnit::ConcurrencyState::start() {}
2952void ASTUnit::ConcurrencyState::finish() {}
2953
2954#endif