blob: 6874986cbb42c4940347c7682aa73dcc97b282b7 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-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 Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Serialization/ASTReader.h"
33#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000034#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000035#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000037#include "llvm/Support/Atomic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000039#include "llvm/Support/FileSystem.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
Rafael Espindola34392372013-06-11 19:59:07 +000045#include "llvm/Support/PathV1.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000046#include "llvm/Support/Timer.h"
47#include "llvm/Support/raw_ostream.h"
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000049#include <cstdlib>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000050#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor213f18b2010-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 Krameredfb7ec2010-11-09 20:00:56 +000061 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000065 }
66
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 }
71
Douglas Gregor213f18b2010-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 Kremenek1872b312011-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
87 /// \brief Temporary files that should be removed when the ASTUnit is
88 /// destroyed.
89 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
90
91 /// \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 Kremeneke055f8a2011-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 Gribenkoc4a77902012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-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 Gribenkoc4a77902012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-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 Kremenek1872b312011-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 Kremeneke055f8a2011-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 Kremenek1872b312011-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 Kremeneke055f8a2011-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 Kremenek1872b312011-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 Gribenkocfa88f82013-01-12 19:30:44 +0000159static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-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)
169 TemporaryFiles[I].eraseFromDisk();
170 TemporaryFiles.clear();
171}
172
173void OnDiskData::CleanPreambleFile() {
174 if (!PreambleFile.empty()) {
175 llvm::sys::Path(PreambleFile).eraseFromDisk();
176 PreambleFile.clear();
177 }
178}
179
180void OnDiskData::Cleanup() {
181 CleanTemporaryFiles();
182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis900ab952012-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 Kyrtzidis332cb9b2011-10-31 07:19:59 +0000193void ASTUnit::clearFileLevelDecls() {
194 for (FileDeclsTy::iterator
195 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
196 delete I->second;
197 FileDecls.clear();
198}
199
Ted Kremenek1872b312011-10-27 17:55:18 +0000200void ASTUnit::CleanTemporaryFiles() {
201 getOnDiskData(this).CleanTemporaryFiles();
202}
203
204void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
205 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000206}
207
Douglas Gregoreababfb2010-08-04 05:53:38 +0000208/// \brief After failing to build a precompiled preamble (due to
209/// errors in the source that occurs in the preamble), the number of
210/// reparses during which we'll skip even trying to precompile the
211/// preamble.
212const unsigned DefaultPreambleRebuildInterval = 5;
213
Douglas Gregore3c60a72010-11-17 00:13:31 +0000214/// \brief Tracks the number of ASTUnit objects that are currently active.
215///
216/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000217static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000218
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000219ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +0000220 : Reader(0), HadModuleLoaderFatalFailure(false),
221 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000222 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000223 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000224 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000225 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000226 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000227 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000228 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000229 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000230 CompletionCacheTopLevelHashValue(0),
231 PreambleTopLevelHashValue(0),
232 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000233 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000234 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000235 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000236 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
237 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000238}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000239
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000240ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000241 // If we loaded from an AST file, balance out the BeginSourceFile call.
242 if (MainFileIsAST && getDiagnostics().getClient()) {
243 getDiagnostics().getClient()->EndSourceFile();
244 }
245
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000246 clearFileLevelDecls();
247
Ted Kremenek1872b312011-10-27 17:55:18 +0000248 // Clean up the temporary files and the preamble file.
249 removeOnDiskEntry(this);
250
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000251 // Free the buffers associated with remapped files. We are required to
252 // perform this operation here because we explicitly request that the
253 // compiler instance *not* free these buffers for each invocation of the
254 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000255 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000256 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
257 for (PreprocessorOptions::remapped_file_buffer_iterator
258 FB = PPOpts.remapped_file_buffer_begin(),
259 FBEnd = PPOpts.remapped_file_buffer_end();
260 FB != FBEnd;
261 ++FB)
262 delete FB->second;
263 }
Douglas Gregor28233422010-07-27 14:52:07 +0000264
265 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000266 delete PreambleBuffer;
267
Douglas Gregor213f18b2010-10-28 15:44:59 +0000268 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000269
270 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000271 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000272 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
273 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000274}
275
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000276void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278/// \brief Determine the set of code-completion contexts in which this
279/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000280static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000281 const LangOptions &LangOpts,
282 bool &IsNestedNameSpecifier) {
283 IsNestedNameSpecifier = false;
284
Douglas Gregor8071e422010-08-15 06:18:01 +0000285 if (isa<UsingShadowDecl>(ND))
286 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
287 if (!ND)
288 return 0;
289
Richard Smith026b3582012-08-14 03:13:00 +0000290 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000291 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
292 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
293 // Types can appear in these contexts.
294 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000295 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
296 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
297 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
298 | (1LL << CodeCompletionContext::CCC_Statement)
299 | (1LL << CodeCompletionContext::CCC_Type)
300 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000301
302 // In C++, types can appear in expressions contexts (for functional casts).
303 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000304 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000305
306 // In Objective-C, message sends can send interfaces. In Objective-C++,
307 // all types are available due to functional casts.
308 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000310
311 // In Objective-C, you can only be a subclass of another Objective-C class
312 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000313 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000314
315 // Deal with tag names.
316 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000318
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000320 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000321 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000322 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 else
Richard Smith026b3582012-08-14 03:13:00 +0000326 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000327
Douglas Gregor8071e422010-08-15 06:18:01 +0000328 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000330 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000332 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
333 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
335 | (1LL << CodeCompletionContext::CCC_Expression)
336 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
337 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000338 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000340 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000342 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000343 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000344
345 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000346 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000347 }
348
349 return Contexts;
350}
351
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352void ASTUnit::CacheCodeCompletionResults() {
353 if (!TheSema)
354 return;
355
Douglas Gregor213f18b2010-10-28 15:44:59 +0000356 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000357 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358
359 // Clear out the previous results.
360 ClearCachedCompletionResults();
361
362 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000363 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000364 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000365 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000366 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000367 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000368 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000369
370 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000371 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
372
Douglas Gregor87c08a52010-08-13 22:48:40 +0000373 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
374 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000376 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000377 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000378 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000379 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000380 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000381 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000382 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000383 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000384 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000385 CachedResult.Priority = Results[I].Priority;
386 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000387 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000388
Douglas Gregorf5586f62010-08-16 18:08:11 +0000389 // Keep track of the type of this completion in an ASTContext-agnostic
390 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000393 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000394 CachedResult.Type = 0;
395 } else {
396 CanQualType CanUsageType
397 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
398 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
399
400 // Determine whether we have already seen this type. If so, we save
401 // ourselves the work of formatting the type string by using the
402 // temporary, CanQualType-based hash table to find the associated value.
403 unsigned &TypeValue = CompletionTypes[CanUsageType];
404 if (TypeValue == 0) {
405 TypeValue = CompletionTypes.size();
406 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
407 = TypeValue;
408 }
409
410 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000411 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000412
Douglas Gregor8071e422010-08-15 06:18:01 +0000413 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000414
415 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000416 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000417 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
418 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000419 uint64_t NNSContexts
420 = (1LL << CodeCompletionContext::CCC_TopLevel)
421 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
422 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
423 | (1LL << CodeCompletionContext::CCC_Statement)
424 | (1LL << CodeCompletionContext::CCC_Expression)
425 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
426 | (1LL << CodeCompletionContext::CCC_EnumTag)
427 | (1LL << CodeCompletionContext::CCC_UnionTag)
428 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
429 | (1LL << CodeCompletionContext::CCC_Type)
430 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
431 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000432
433 if (isa<NamespaceDecl>(Results[I].Declaration) ||
434 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000435 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000436
437 if (unsigned RemainingContexts
438 = NNSContexts & ~CachedResult.ShowInContexts) {
439 // If there any contexts where this completion can be a
440 // nested-name-specifier but isn't already an option, create a
441 // nested-name-specifier completion.
442 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000443 CachedResult.Completion
444 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000445 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000446 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000447 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000448 CachedResult.ShowInContexts = RemainingContexts;
449 CachedResult.Priority = CCP_NestedNameSpecifier;
450 CachedResult.TypeClass = STC_Void;
451 CachedResult.Type = 0;
452 CachedCompletionResults.push_back(CachedResult);
453 }
454 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000455 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000456 }
457
Douglas Gregor87c08a52010-08-13 22:48:40 +0000458 case Result::RK_Keyword:
459 case Result::RK_Pattern:
460 // Ignore keywords and patterns; we don't care, since they are so
461 // easily regenerated.
462 break;
463
464 case Result::RK_Macro: {
465 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000466 CachedResult.Completion
467 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000468 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000469 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000470 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000471 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000472 = (1LL << CodeCompletionContext::CCC_TopLevel)
473 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
474 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
475 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
476 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
477 | (1LL << CodeCompletionContext::CCC_Statement)
478 | (1LL << CodeCompletionContext::CCC_Expression)
479 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
480 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
481 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
482 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
483 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000484
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485 CachedResult.Priority = Results[I].Priority;
486 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000487 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000488 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000489 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000490 CachedCompletionResults.push_back(CachedResult);
491 break;
492 }
493 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000494 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000495
496 // Save the current top-level hash value.
497 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000498}
499
500void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000501 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000502 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000503 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000504}
505
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506namespace {
507
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000508/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000510class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000511 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 LangOptions &LangOpt;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000514 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000518 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000520 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000521 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000522 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000523 unsigned &Counter)
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000524 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000525 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000526 Counter(Counter),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000527 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000529 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000530 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000531 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000532 return false;
533
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000534 LangOpt = LangOpts;
535 InitializedLanguage = true;
536
537 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000538 return false;
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000541 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000542 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000543 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000544 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000545 return false;
546
Douglas Gregor57016dd2012-10-16 23:40:58 +0000547 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000548 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
549 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000550
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000551 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000552 return false;
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000555 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 Counter = Value;
557 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000558
559private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000560 void updated() {
561 if (!Target || !InitializedLanguage)
562 return;
563
564 // Inform the target of the language options.
565 //
566 // FIXME: We shouldn't need to do this, the target should be immutable once
567 // created. This complexity should be lifted elsewhere.
568 Target->setForcedLangOptions(LangOpt);
569
570 // Initialize the preprocessor.
571 PP.Initialize(*Target);
572
573 // Initialize the ASTContext
574 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000575
576 // We didn't have access to the comment options when the ASTContext was
577 // constructed, so register them now.
578 Context.getCommentCommandTraits().registerCommentOptions(
579 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000580 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000581};
582
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000583 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000584class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000586 SourceManager *SourceMgr;
587
Douglas Gregora88084b2010-02-18 18:08:43 +0000588public:
David Blaikie26e7a902011-09-26 00:01:39 +0000589 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000590 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000591 : StoredDiags(StoredDiags), SourceMgr(0) { }
592
593 virtual void BeginSourceFile(const LangOptions &LangOpts,
594 const Preprocessor *PP = 0) {
595 if (PP)
596 SourceMgr = &PP->getSourceManager();
597 }
598
David Blaikied6471f72011-09-25 23:23:43 +0000599 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000600 const Diagnostic &Info);
Douglas Gregora88084b2010-02-18 18:08:43 +0000601};
602
603/// \brief RAII object that optionally captures diagnostics, if
604/// there is no diagnostic client to capture them already.
605class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000606 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000607 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000608 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000609
610public:
David Blaikied6471f72011-09-25 23:23:43 +0000611 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000612 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000613 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000614 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000615 if (RequestCapture || Diags.getClient() == 0) {
616 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000617 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000618 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000619 }
620
621 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000622 if (Diags.getClient() == &Client) {
623 Diags.takeClient();
624 Diags.setClient(PreviousClient);
625 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000626 }
627};
628
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000629} // anonymous namespace
630
David Blaikie26e7a902011-09-26 00:01:39 +0000631void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000632 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000633 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000634 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000635
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000636 // Only record the diagnostic if it's part of the source manager we know
637 // about. This effectively drops diagnostics from modules we're building.
638 // FIXME: In the long run, ee don't want to drop source managers from modules.
639 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
640 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000641}
642
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000643ASTMutationListener *ASTUnit::getASTMutationListener() {
644 if (WriterData)
645 return &WriterData->Writer;
646 return 0;
647}
648
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000649ASTDeserializationListener *ASTUnit::getDeserializationListener() {
650 if (WriterData)
651 return &WriterData->Writer;
652 return 0;
653}
654
Chris Lattner5f9e2722011-07-23 10:55:15 +0000655llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000656 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000657 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000658 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000659}
660
Douglas Gregore47be3e2010-11-11 00:39:14 +0000661/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000662void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000663 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000664 ASTUnit &AST, bool CaptureDiagnostics) {
665 if (!Diags.getPtr()) {
666 // No diagnostics engine was provided, so create our own diagnostics object
667 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000668 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000669 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000670 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000671 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000672 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000673 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000675 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000676 }
677}
678
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000679ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000680 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000681 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000682 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000683 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000684 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000685 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000686 bool AllowPCHWithCompilerErrors,
687 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000688 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000689
690 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000691 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
692 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000693 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
694 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000695 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000696
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000697 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000698
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000699 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000700 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000701 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000702 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000703 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000704 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000705 AST->getFileManager(),
706 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000707 AST->HSOpts = new HeaderSearchOptions();
708
709 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
710 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000711 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000712 AST->ASTFileLangOpts,
713 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000714
Douglas Gregor4db64a42010-01-23 00:14:00 +0000715 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000716 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
717 if (const llvm::MemoryBuffer *
718 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
719 // Create the file entry for the file that we're mapping from.
720 const FileEntry *FromFile
721 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
722 memBuf->getBufferSize(),
723 0);
724 if (!FromFile) {
725 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
726 << RemappedFiles[I].first;
727 delete memBuf;
728 continue;
729 }
730
731 // Override the contents of the "from" file with the contents of
732 // the "to" file.
733 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
734
735 } else {
736 const char *fname = fileOrBuf.get<const char *>();
737 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
738 if (!ToFile) {
739 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
740 << RemappedFiles[I].first << fname;
741 continue;
742 }
743
744 // Create the file entry for the file that we're mapping from.
745 const FileEntry *FromFile
746 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
747 ToFile->getSize(),
748 0);
749 if (!FromFile) {
750 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
751 << RemappedFiles[I].first;
752 delete memBuf;
753 continue;
754 }
755
756 // Override the contents of the "from" file with the contents of
757 // the "to" file.
758 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000759 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000760 }
761
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000764 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000765 unsigned Counter;
766
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000767 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768
Douglas Gregor36a16492012-10-24 17:46:57 +0000769 AST->PP = new Preprocessor(new PreprocessorOptions(),
770 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000771 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
772 *AST,
773 /*IILookup=*/0,
774 /*OwnsHeaderSearch=*/false,
775 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000776 Preprocessor &PP = *AST->PP;
777
778 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
779 AST->getSourceManager(),
780 /*Target=*/0,
781 PP.getIdentifierTable(),
782 PP.getSelectorTable(),
783 PP.getBuiltinInfo(),
784 /* size_reserve = */0,
785 /*DelayInitialization=*/true);
786 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000787
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000788 bool disableValid = false;
789 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
790 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000791 Reader.reset(new ASTReader(PP, Context,
792 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000793 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000794 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000795
796 // Recover resources if we crash before exiting this method.
797 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
798 ReaderCleanup(Reader.get());
799
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000800 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000801 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000802 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000803 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000804
Douglas Gregor38295be2012-10-22 23:51:00 +0000805 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000806 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000807 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000808 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000810 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000811 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000812 case ASTReader::OutOfDate:
813 case ASTReader::VersionMismatch:
814 case ASTReader::ConfigurationMismatch:
815 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000816 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000817 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000820 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
821
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000822 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000824 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000825 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000826 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000827 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000828 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000829
830 // Unregister the cleanup for ASTReader. It will get cleaned up
831 // by the ASTUnit cleanup.
832 ReaderCleanup.unregister();
833
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000834 Context.setExternalSource(Source);
835
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000836 // Create an AST consumer, even though it isn't used.
837 AST->Consumer.reset(new ASTConsumer);
838
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000839 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000840 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
841 AST->TheSema->Initialize();
842 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000843 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000844
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000845 // Tell the diagnostic client that we have started a source file.
846 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000849}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000850
851namespace {
852
Douglas Gregor9b7db622011-02-16 18:16:54 +0000853/// \brief Preprocessor callback class that updates a hash value with the names
854/// of all macros that have been defined by the translation unit.
855class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
856 unsigned &Hash;
857
858public:
859 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
860
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000861 virtual void MacroDefined(const Token &MacroNameTok,
862 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000863 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
864 }
865};
866
867/// \brief Add the given declaration to the hash of all top-level entities.
868void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
869 if (!D)
870 return;
871
872 DeclContext *DC = D->getDeclContext();
873 if (!DC)
874 return;
875
876 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
877 return;
878
879 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
880 if (ND->getIdentifier())
881 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
882 else if (DeclarationName Name = ND->getDeclName()) {
883 std::string NameStr = Name.getAsString();
884 Hash = llvm::HashString(NameStr, Hash);
885 }
886 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000887 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000888}
889
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000890class TopLevelDeclTrackerConsumer : public ASTConsumer {
891 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000892 unsigned &Hash;
893
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000894public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000895 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
896 : Unit(_Unit), Hash(Hash) {
897 Hash = 0;
898 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000899
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000900 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000901 if (!D)
902 return;
903
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000904 // FIXME: Currently ObjC method declarations are incorrectly being
905 // reported as top-level declarations, even though their DeclContext
906 // is the containing ObjC @interface/@implementation. This is a
907 // fundamental problem in the parser right now.
908 if (isa<ObjCMethodDecl>(D))
909 return;
910
911 AddTopLevelDeclarationToHash(D, Hash);
912 Unit.addTopLevelDecl(D);
913
914 handleFileLevelDecl(D);
915 }
916
917 void handleFileLevelDecl(Decl *D) {
918 Unit.addFileLevelDecl(D);
919 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
920 for (NamespaceDecl::decl_iterator
921 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
922 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000923 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000924 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000925
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000926 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000927 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
928 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000929 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000930 }
931
Sebastian Redl27372b42010-08-11 18:52:41 +0000932 // We're not interested in "interesting" decls.
933 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000934
935 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
936 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
937 handleTopLevelDecl(*it);
938 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000939
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000940 virtual ASTMutationListener *GetASTMutationListener() {
941 return Unit.getASTMutationListener();
942 }
943
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000944 virtual ASTDeserializationListener *GetASTDeserializationListener() {
945 return Unit.getDeserializationListener();
946 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000947};
948
949class TopLevelDeclTrackerAction : public ASTFrontendAction {
950public:
951 ASTUnit &Unit;
952
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000953 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000954 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000955 CI.getPreprocessor().addPPCallbacks(
956 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
957 return new TopLevelDeclTrackerConsumer(Unit,
958 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000959 }
960
961public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000962 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
963
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000964 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000965 virtual TranslationUnitKind getTranslationUnitKind() {
966 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000967 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000968};
969
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000970class PrecompilePreambleAction : public ASTFrontendAction {
971 ASTUnit &Unit;
972 bool HasEmittedPreamblePCH;
973
974public:
975 explicit PrecompilePreambleAction(ASTUnit &Unit)
976 : Unit(Unit), HasEmittedPreamblePCH(false) {}
977
978 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
979 StringRef InFile);
980 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
981 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
982 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
983
984 virtual bool hasCodeCompletionSupport() const { return false; }
985 virtual bool hasASTFileSupport() const { return false; }
986 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
987};
988
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000989class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000990 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000991 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000992 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000993 PrecompilePreambleAction *Action;
994
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000995public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000996 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
997 const Preprocessor &PP, StringRef isysroot,
998 raw_ostream *Out)
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +0000999 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001000 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +00001001 Hash = 0;
1002 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001003
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001004 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001005 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
1006 Decl *D = *it;
1007 // FIXME: Currently ObjC method declarations are incorrectly being
1008 // reported as top-level declarations, even though their DeclContext
1009 // is the containing ObjC @interface/@implementation. This is a
1010 // fundamental problem in the parser right now.
1011 if (isa<ObjCMethodDecl>(D))
1012 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +00001013 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001014 TopLevelDecls.push_back(D);
1015 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001016 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001017 }
1018
1019 virtual void HandleTranslationUnit(ASTContext &Ctx) {
1020 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001021 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001022 // Translate the top-level declarations we captured during
1023 // parsing into declaration IDs in the precompiled
1024 // preamble. This will allow us to deserialize those top-level
1025 // declarations when requested.
1026 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1027 Unit.addTopLevelDeclFromPreamble(
1028 getWriter().getDeclID(TopLevelDecls[I]));
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001029
1030 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001031 }
1032 }
1033};
1034
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001035}
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001036
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001037ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1038 StringRef InFile) {
1039 std::string Sysroot;
1040 std::string OutputFile;
1041 raw_ostream *OS = 0;
1042 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1043 OutputFile, OS))
1044 return 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001045
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001046 if (!CI.getFrontendOpts().RelocatablePCH)
1047 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +00001048
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001049 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1050 Unit.getCurrentTopLevelHashValue()));
1051 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1052 Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001053}
1054
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001055static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1056 return StoredDiag.getLocation().isValid();
1057}
1058
1059static void
1060checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001061 // Get rid of stored diagnostics except the ones from the driver which do not
1062 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001063 StoredDiags.erase(
1064 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1065 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001066}
1067
1068static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1069 StoredDiagnostics,
1070 SourceManager &SM) {
1071 // The stored diagnostic has the old source manager in it; update
1072 // the locations to refer into the new source manager. Since we've
1073 // been careful to make sure that the source manager's state
1074 // before and after are identical, so that we can reuse the source
1075 // location itself.
1076 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1077 if (StoredDiagnostics[I].getLocation().isValid()) {
1078 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1079 StoredDiagnostics[I].setLocation(Loc);
1080 }
1081 }
1082}
1083
Douglas Gregorabc563f2010-07-19 21:46:24 +00001084/// Parse the source file into a translation unit using the given compiler
1085/// invocation, replacing the current translation unit.
1086///
1087/// \returns True if a failure occurred that causes the ASTUnit not to
1088/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001089bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001090 delete SavedMainFileBuffer;
1091 SavedMainFileBuffer = 0;
1092
Ted Kremenek4f327862011-03-21 18:40:17 +00001093 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001094 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001095 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001096 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001097
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001098 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001099 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001100
1101 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001102 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1103 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001104
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001105 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001106 CCInvocation(new CompilerInvocation(*Invocation));
1107
1108 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001109 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001110
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001111 // Set up diagnostics, capturing any diagnostics that would
1112 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001113 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001114
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001115 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001116 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001117 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001118 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001119 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001120 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001121 }
1122
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001123 // Inform the target of the language options.
1124 //
1125 // FIXME: We shouldn't need to do this, the target should be immutable once
1126 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001127 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001128
Ted Kremenek03201fb2011-03-21 18:40:07 +00001129 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001130 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001131 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001132 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001133 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001134 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001135
Douglas Gregorabc563f2010-07-19 21:46:24 +00001136 // Configure the various subsystems.
1137 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001138 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001139 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001140 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001141 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1142 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001143 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001144 Ctx = 0;
1145 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001146 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001147
1148 // Clear out old caches and data.
1149 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001150 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001151 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001152
Douglas Gregorf128fed2010-08-20 00:02:33 +00001153 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001154 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001155 TopLevelDeclsInPreamble.clear();
1156 }
1157
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001158 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001159 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001160
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001161 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001162 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001163
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001164 // If the main file has been overridden due to the use of a preamble,
1165 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001166 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001167 if (OverrideMainBuffer) {
1168 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1169 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1170 PreprocessorOpts.PrecompiledPreambleBytes.second
1171 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001172 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001173 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001174
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001175 // The stored diagnostic has the old source manager in it; update
1176 // the locations to refer into the new source manager. Since we've
1177 // been careful to make sure that the source manager's state
1178 // before and after are identical, so that we can reuse the source
1179 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001180 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001181
1182 // Keep track of the override buffer;
1183 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001184 }
1185
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001186 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001187 new TopLevelDeclTrackerAction(*this));
1188
1189 // Recover resources if we crash before exiting this method.
1190 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1191 ActCleanup(Act.get());
1192
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001193 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001194 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001195
1196 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001197 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001198 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1199 getSourceManager(), PreambleDiagnostics,
1200 StoredDiagnostics);
1201 }
1202
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001203 if (!Act->Execute())
1204 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001205
1206 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001207
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001208 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001209
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001210 FailedParseDiagnostics.clear();
1211
Douglas Gregorabc563f2010-07-19 21:46:24 +00001212 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001213
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001214error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001215 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001216 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001217 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001218 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001219 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001220
1221 // Keep the ownership of the data in the ASTUnit because the client may
1222 // want to see the diagnostics.
1223 transferASTDataFromCompilerInstance(*Clang);
1224 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001225 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001226 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001227 return true;
1228}
1229
Douglas Gregor44c181a2010-07-23 00:33:23 +00001230/// \brief Simple function to retrieve a path for a preamble precompiled header.
1231static std::string GetPreamblePCHPath() {
1232 // FIXME: This is lame; sys::Path should provide this function (in particular,
1233 // it should know how to find the temporary files dir).
1234 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001235 // FIXME: This is a hack so that we can override the preamble file during
1236 // crash-recovery testing, which is the only case where the preamble files
1237 // are not necessarily cleaned up.
1238 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1239 if (TmpFile)
1240 return TmpFile;
1241
Douglas Gregor44c181a2010-07-23 00:33:23 +00001242 std::string Error;
1243 const char *TmpDir = ::getenv("TMPDIR");
1244 if (!TmpDir)
1245 TmpDir = ::getenv("TEMP");
1246 if (!TmpDir)
1247 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001248#ifdef LLVM_ON_WIN32
1249 if (!TmpDir)
1250 TmpDir = ::getenv("USERPROFILE");
1251#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001252 if (!TmpDir)
1253 TmpDir = "/tmp";
1254 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001255 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001257 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001258 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001259 return std::string();
1260
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261 return P.str();
1262}
1263
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001264/// \brief Compute the preamble for the main file, providing the source buffer
1265/// that corresponds to the main file along with a pair (bytes, start-of-line)
1266/// that describes the preamble.
1267std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001268ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1269 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001270 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001271 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001272 CreatedBuffer = false;
1273
Douglas Gregor44c181a2010-07-23 00:33:23 +00001274 // Try to determine if the main file has been remapped, either from the
1275 // command line (to another file) or directly through the compiler invocation
1276 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindola105b2072013-06-18 19:40:07 +00001278 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
1279 uint64_t MainFileID;
1280 if (!llvm::sys::fs::GetUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281 // Check whether there is a file-file remapping of the main file
1282 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283 M = PreprocessorOpts.remapped_file_begin(),
1284 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001285 M != E;
1286 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001287 std::string MPath(M->first);
1288 uint64_t MID;
1289 if (!llvm::sys::fs::GetUniqueID(MPath, MID)) {
1290 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001291 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001293 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001294 CreatedBuffer = false;
1295 }
1296
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001297 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001298 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001299 return std::make_pair((llvm::MemoryBuffer*)0,
1300 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001301 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001302 }
1303 }
1304 }
1305
1306 // Check whether there is a file-buffer remapping. It supercedes the
1307 // file-file remapping.
1308 for (PreprocessorOptions::remapped_file_buffer_iterator
1309 M = PreprocessorOpts.remapped_file_buffer_begin(),
1310 E = PreprocessorOpts.remapped_file_buffer_end();
1311 M != E;
1312 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001313 std::string MPath(M->first);
1314 uint64_t MID;
1315 if (!llvm::sys::fs::GetUniqueID(MPath, MID)) {
1316 if (MainFileID == MID) {
1317 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001318 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001319 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001320 CreatedBuffer = false;
1321 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001322
Douglas Gregor175c4a92010-07-23 23:58:40 +00001323 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001324 }
1325 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001326 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001327 }
1328
1329 // If the main source file was not remapped, load it now.
1330 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001331 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001332 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001333 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001334
1335 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001336 }
1337
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001338 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001339 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001340 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001341}
1342
Douglas Gregor754f3492010-07-24 00:38:13 +00001343static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001344 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001345 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001346 llvm::MemoryBuffer *Result
1347 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1348 memcpy(const_cast<char*>(Result->getBufferStart()),
1349 Old->getBufferStart(), Old->getBufferSize());
1350 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001351 ' ', NewSize - Old->getBufferSize() - 1);
1352 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001353
Douglas Gregor754f3492010-07-24 00:38:13 +00001354 return Result;
1355}
1356
Douglas Gregor175c4a92010-07-23 23:58:40 +00001357/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1358/// the source file.
1359///
1360/// This routine will compute the preamble of the main source file. If a
1361/// non-trivial preamble is found, it will precompile that preamble into a
1362/// precompiled header so that the precompiled preamble can be used to reduce
1363/// reparsing time. If a precompiled preamble has already been constructed,
1364/// this routine will determine if it is still valid and, if so, avoid
1365/// rebuilding the precompiled preamble.
1366///
Douglas Gregordf95a132010-08-09 20:45:32 +00001367/// \param AllowRebuild When true (the default), this routine is
1368/// allowed to rebuild the precompiled preamble if it is found to be
1369/// out-of-date.
1370///
1371/// \param MaxLines When non-zero, the maximum number of lines that
1372/// can occur within the preamble.
1373///
Douglas Gregor754f3492010-07-24 00:38:13 +00001374/// \returns If the precompiled preamble can be used, returns a newly-allocated
1375/// buffer that should be used in place of the main file when doing so.
1376/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001377llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001378 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001379 bool AllowRebuild,
1380 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001381
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001382 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001383 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1384 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001385 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001386 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001387
1388 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001389 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001390 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001391
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001392 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001393 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001394 if (CreatedPreambleBuffer)
1395 OwnedPreambleBuffer.reset(NewPreamble.first);
1396
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001397 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001398 // We couldn't find a preamble in the main source. Clear out the current
1399 // preamble, if we have one. It's obviously no good any more.
1400 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001401 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001402
1403 // The next time we actually see a preamble, precompile it.
1404 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001405 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001406 }
1407
1408 if (!Preamble.empty()) {
1409 // We've previously computed a preamble. Check whether we have the same
1410 // preamble now that we did before, and that there's enough space in
1411 // the main-file buffer within the precompiled preamble to fit the
1412 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001413 if (Preamble.size() == NewPreamble.second.first &&
1414 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001415 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001416 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001417 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001418 // The preamble has not changed. We may be able to re-use the precompiled
1419 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001420
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001421 // Check that none of the files used by the preamble have changed.
1422 bool AnyFileChanged = false;
1423
1424 // First, make a record of those files that have been overridden via
1425 // remapping or unsaved_files.
1426 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1427 for (PreprocessorOptions::remapped_file_iterator
1428 R = PreprocessorOpts.remapped_file_begin(),
1429 REnd = PreprocessorOpts.remapped_file_end();
1430 !AnyFileChanged && R != REnd;
1431 ++R) {
1432 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001433 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001434 // If we can't stat the file we're remapping to, assume that something
1435 // horrible happened.
1436 AnyFileChanged = true;
1437 break;
1438 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001439
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001440 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1441 StatBuf.st_mtime);
1442 }
1443 for (PreprocessorOptions::remapped_file_buffer_iterator
1444 R = PreprocessorOpts.remapped_file_buffer_begin(),
1445 REnd = PreprocessorOpts.remapped_file_buffer_end();
1446 !AnyFileChanged && R != REnd;
1447 ++R) {
1448 // FIXME: Should we actually compare the contents of file->buffer
1449 // remappings?
1450 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1451 0);
1452 }
1453
1454 // Check whether anything has changed.
1455 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1456 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1457 !AnyFileChanged && F != FEnd;
1458 ++F) {
1459 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1460 = OverriddenFiles.find(F->first());
1461 if (Overridden != OverriddenFiles.end()) {
1462 // This file was remapped; check whether the newly-mapped file
1463 // matches up with the previous mapping.
1464 if (Overridden->second != F->second)
1465 AnyFileChanged = true;
1466 continue;
1467 }
1468
1469 // The file was not remapped; check whether it has changed on disk.
1470 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001471 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001472 // If we can't stat the file, assume that something horrible happened.
1473 AnyFileChanged = true;
1474 } else if (StatBuf.st_size != F->second.first ||
1475 StatBuf.st_mtime != F->second.second)
1476 AnyFileChanged = true;
1477 }
1478
1479 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001480 // Okay! We can re-use the precompiled preamble.
1481
1482 // Set the state of the diagnostic object to mimic its state
1483 // after parsing the preamble.
1484 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001485 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001486 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001487 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001488
1489 // Create a version of the main file buffer that is padded to
1490 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001491 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001492 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001493 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001494 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001495 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001496
1497 // If we aren't allowed to rebuild the precompiled preamble, just
1498 // return now.
1499 if (!AllowRebuild)
1500 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001501
Douglas Gregor175c4a92010-07-23 23:58:40 +00001502 // We can't reuse the previously-computed preamble. Build a new one.
1503 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001504 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001505 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001506 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001507 } else if (!AllowRebuild) {
1508 // We aren't allowed to rebuild the precompiled preamble; just
1509 // return now.
1510 return 0;
1511 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001512
1513 // If the preamble rebuild counter > 1, it's because we previously
1514 // failed to build a preamble and we're not yet ready to try
1515 // again. Decrement the counter and return a failure.
1516 if (PreambleRebuildCounter > 1) {
1517 --PreambleRebuildCounter;
1518 return 0;
1519 }
1520
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001521 // Create a temporary file for the precompiled preamble. In rare
1522 // circumstances, this can fail.
1523 std::string PreamblePCHPath = GetPreamblePCHPath();
1524 if (PreamblePCHPath.empty()) {
1525 // Try again next time.
1526 PreambleRebuildCounter = 1;
1527 return 0;
1528 }
1529
Douglas Gregor175c4a92010-07-23 23:58:40 +00001530 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001531 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001532 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001533
1534 // Create a new buffer that stores the preamble. The buffer also contains
1535 // extra space for the original contents of the file (which will be present
1536 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001537 // grows.
1538 PreambleReservedSize = NewPreamble.first->getBufferSize();
1539 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001540 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001541 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001542 PreambleReservedSize *= 2;
1543
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001544 // Save the preamble text for later; we'll need to compare against it for
1545 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001546 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001547 Preamble.assign(FileMgr->getFile(MainFilename),
1548 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001549 NewPreamble.first->getBufferStart()
1550 + NewPreamble.second.first);
1551 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1552
Douglas Gregor671947b2010-08-19 01:33:06 +00001553 delete PreambleBuffer;
1554 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001555 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001556 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001557 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001558 NewPreamble.first->getBufferStart(), Preamble.size());
1559 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001560 ' ', PreambleReservedSize - Preamble.size() - 1);
1561 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001562
1563 // Remap the main source file to the preamble buffer.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001564 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001565 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1566
1567 // Tell the compiler invocation to generate a temporary precompiled header.
1568 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001569 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001570 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001571 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1572 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001573
1574 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001575 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001576
1577 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001578 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1579 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001580
Douglas Gregor01b6e312011-07-01 18:22:13 +00001581 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001582 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001583
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001584 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001585 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001586
1587 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001588 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001589 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001590 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001591 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1592 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001593 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001594 PreprocessorOpts.eraseRemappedFile(
1595 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001596 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001597 }
1598
1599 // Inform the target of the language options.
1600 //
1601 // FIXME: We shouldn't need to do this, the target should be immutable once
1602 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001603 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001604
Ted Kremenek03201fb2011-03-21 18:40:07 +00001605 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001606 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001607 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001608 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001609 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001610 "IR inputs not support here!");
1611
1612 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001613 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001614 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001615 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001616 TopLevelDecls.clear();
1617 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001618
1619 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001620 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001621
1622 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001623 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001624 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001625
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001626 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001627 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001628 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001629 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1630 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001631 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001632 PreprocessorOpts.eraseRemappedFile(
1633 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001634 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001635 }
1636
1637 Act->Execute();
1638 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001639
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001640 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001641 // The preamble PCH failed (e.g. there was a module loading fatal error),
1642 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001643 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001644 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1645 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001646 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001647 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001648 PreprocessorOpts.eraseRemappedFile(
1649 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001650 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001651 }
1652
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001653 // Transfer any diagnostics generated when parsing the preamble into the set
1654 // of preamble diagnostics.
1655 PreambleDiagnostics.clear();
1656 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001657 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001658 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001659
Douglas Gregor175c4a92010-07-23 23:58:40 +00001660 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001661 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001662 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001663
1664 // Keep track of all of the files that the source manager knows about,
1665 // so we can verify whether they have changed or not.
1666 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001667 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001668 const llvm::MemoryBuffer *MainFileBuffer
1669 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1670 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1671 FEnd = SourceMgr.fileinfo_end();
1672 F != FEnd;
1673 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001674 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001675 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1676 continue;
1677
1678 FilesInPreamble[File->getName()]
1679 = std::make_pair(F->second->getSize(), File->getModificationTime());
1680 }
1681
Douglas Gregoreababfb2010-08-04 05:53:38 +00001682 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001683 PreprocessorOpts.eraseRemappedFile(
1684 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001685
1686 // If the hash of top-level entities differs from the hash of the top-level
1687 // entities the last time we rebuilt the preamble, clear out the completion
1688 // cache.
1689 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1690 CompletionCacheTopLevelHashValue = 0;
1691 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1692 }
1693
Douglas Gregor754f3492010-07-24 00:38:13 +00001694 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001695 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001696 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001697}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001698
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001699void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1700 std::vector<Decl *> Resolved;
1701 Resolved.reserve(TopLevelDeclsInPreamble.size());
1702 ExternalASTSource &Source = *getASTContext().getExternalSource();
1703 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1704 // Resolve the declaration ID to an actual declaration, possibly
1705 // deserializing the declaration in the process.
1706 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1707 if (D)
1708 Resolved.push_back(D);
1709 }
1710 TopLevelDeclsInPreamble.clear();
1711 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1712}
1713
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001714void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1715 // Steal the created target, context, and preprocessor.
1716 TheSema.reset(CI.takeSema());
1717 Consumer.reset(CI.takeASTConsumer());
1718 Ctx = &CI.getASTContext();
1719 PP = &CI.getPreprocessor();
1720 CI.setSourceManager(0);
1721 CI.setFileManager(0);
1722 Target = &CI.getTarget();
1723 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001724 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001725}
1726
Chris Lattner5f9e2722011-07-23 10:55:15 +00001727StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001728 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1729 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1730 if (Input.isFile())
1731 return Input.getFile();
1732 else
1733 return Input.getBuffer()->getBufferIdentifier();
1734 }
1735
1736 if (SourceMgr) {
1737 if (const FileEntry *
1738 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1739 return FE->getName();
1740 }
1741
1742 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001743}
1744
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001745StringRef ASTUnit::getASTFileName() const {
1746 if (!isMainFileAST())
1747 return StringRef();
1748
1749 serialization::ModuleFile &
1750 Mod = Reader->getModuleManager().getPrimaryModule();
1751 return Mod.FileName;
1752}
1753
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001754ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001755 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001756 bool CaptureDiagnostics,
1757 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001758 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001759 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001760 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001761 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001762 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001763 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001764 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001765 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1766 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1767 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001768
1769 return AST.take();
1770}
1771
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001772ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001773 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001774 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001775 ASTUnit *Unit,
1776 bool Persistent,
1777 StringRef ResourceFilesPath,
1778 bool OnlyLocalDecls,
1779 bool CaptureDiagnostics,
1780 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001781 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001782 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001783 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001784 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001785 assert(CI && "A CompilerInvocation is required");
1786
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001787 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001788 ASTUnit *AST = Unit;
1789 if (!AST) {
1790 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001791 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001792 AST = OwnAST.get();
1793 }
1794
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001795 if (!ResourceFilesPath.empty()) {
1796 // Override the resources path.
1797 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1798 }
1799 AST->OnlyLocalDecls = OnlyLocalDecls;
1800 AST->CaptureDiagnostics = CaptureDiagnostics;
1801 if (PrecompilePreamble)
1802 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001803 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001804 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001805 AST->IncludeBriefCommentsInCodeCompletion
1806 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001807
1808 // Recover resources if we crash before exiting this method.
1809 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001810 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001811 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1812 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813 DiagCleanup(Diags.getPtr());
1814
1815 // We'll manage file buffers ourselves.
1816 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1817 CI->getFrontendOpts().DisableFree = false;
1818 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1819
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001820 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001821 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001822
1823 // Recover resources if we crash before exiting this method.
1824 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1825 CICleanup(Clang.get());
1826
1827 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001828 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001829
1830 // Set up diagnostics, capturing any diagnostics that would
1831 // otherwise be dropped.
1832 Clang->setDiagnostics(&AST->getDiagnostics());
1833
1834 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001835 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001836 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001837 if (!Clang->hasTarget())
1838 return 0;
1839
1840 // Inform the target of the language options.
1841 //
1842 // FIXME: We shouldn't need to do this, the target should be immutable once
1843 // created. This complexity should be lifted elsewhere.
1844 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1845
1846 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1847 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001848 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001849 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001850 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001851 "IR inputs not supported here!");
1852
1853 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001854 AST->TheSema.reset();
1855 AST->Ctx = 0;
1856 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001857 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001858
1859 // Create a file manager object to provide access to and cache the filesystem.
1860 Clang->setFileManager(&AST->getFileManager());
1861
1862 // Create the source manager.
1863 Clang->setSourceManager(&AST->getSourceManager());
1864
1865 ASTFrontendAction *Act = Action;
1866
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001867 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001868 if (!Act) {
1869 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1870 Act = TrackerAct.get();
1871 }
1872
1873 // Recover resources if we crash before exiting this method.
1874 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1875 ActCleanup(TrackerAct.get());
1876
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001877 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1878 AST->transferASTDataFromCompilerInstance(*Clang);
1879 if (OwnAST && ErrAST)
1880 ErrAST->swap(OwnAST);
1881
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001882 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001883 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001884
1885 if (Persistent && !TrackerAct) {
1886 Clang->getPreprocessor().addPPCallbacks(
1887 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1888 std::vector<ASTConsumer*> Consumers;
1889 if (Clang->hasASTConsumer())
1890 Consumers.push_back(Clang->takeASTConsumer());
1891 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1892 AST->getCurrentTopLevelHashValue()));
1893 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1894 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001895 if (!Act->Execute()) {
1896 AST->transferASTDataFromCompilerInstance(*Clang);
1897 if (OwnAST && ErrAST)
1898 ErrAST->swap(OwnAST);
1899
1900 return 0;
1901 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001902
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001903 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001904 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001905
1906 Act->EndSourceFile();
1907
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001908 if (OwnAST)
1909 return OwnAST.take();
1910 else
1911 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001912}
1913
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001914bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1915 if (!Invocation)
1916 return true;
1917
1918 // We'll manage file buffers ourselves.
1919 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1920 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001921 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001922
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001923 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001924 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001925 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001926 OverrideMainBuffer
1927 = getMainBufferWithPrecompiledPreamble(*Invocation);
1928 }
1929
Douglas Gregor213f18b2010-10-28 15:44:59 +00001930 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001931 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001932
Ted Kremenek25a11e12011-03-22 01:15:24 +00001933 // Recover resources if we crash before exiting this method.
1934 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1935 MemBufferCleanup(OverrideMainBuffer);
1936
Douglas Gregor213f18b2010-10-28 15:44:59 +00001937 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001938}
1939
Douglas Gregorabc563f2010-07-19 21:46:24 +00001940ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001941 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001942 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001943 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001944 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001945 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001946 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001947 bool IncludeBriefCommentsInCodeCompletion,
1948 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001949 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001950 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001951 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001952 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001953 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001954 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001955 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001956 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001957 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001958 AST->IncludeBriefCommentsInCodeCompletion
1959 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001960 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001961 AST->FileSystemOpts = CI->getFileSystemOpts();
1962 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001963 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001964
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001965 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001966 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1967 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001968 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1969 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001970 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001971
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001972 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001973}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001974
1975ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1976 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001977 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001978 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001979 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001980 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001981 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001982 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001983 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001984 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001985 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001986 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001987 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001988 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001989 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001990 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001991 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001992 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001993 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001994 // No diagnostics engine was provided, so create our own diagnostics object
1995 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001996 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001997 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001998
Chris Lattner5f9e2722011-07-23 10:55:15 +00001999 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002000
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002001 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002002
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002003 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002004
Douglas Gregore47be3e2010-11-11 00:39:14 +00002005 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002006 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00002007
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00002008 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00002009 llvm::makeArrayRef(ArgBegin, ArgEnd),
2010 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00002011 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00002012 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002013 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00002014
Douglas Gregor4db64a42010-01-23 00:14:00 +00002015 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002016 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2017 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2018 if (const llvm::MemoryBuffer *
2019 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2020 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2021 } else {
2022 const char *fname = fileOrBuf.get<const char *>();
2023 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2024 }
2025 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002026 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2027 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2028 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002029
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002030 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002031 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002032
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002033 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2034
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002035 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002036 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002037 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002038 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002039 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002040 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002041 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002042 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002043 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002044 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002045 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002046 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002047 AST->IncludeBriefCommentsInCodeCompletion
2048 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002049 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002050 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002051 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002052 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002053 if (ForSerialization)
2054 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002055 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002056
2057 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002058 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2059 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002060
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002061 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2062 // Some error occurred, if caller wants to examine diagnostics, pass it the
2063 // ASTUnit.
2064 if (ErrAST) {
2065 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2066 ErrAST->swap(AST);
2067 }
2068 return 0;
2069 }
2070
2071 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002072}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002073
2074bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002075 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002076 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002077
2078 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002079
Douglas Gregor213f18b2010-10-28 15:44:59 +00002080 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002081 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002082
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002083 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002084 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2085 for (PreprocessorOptions::remapped_file_buffer_iterator
2086 R = PPOpts.remapped_file_buffer_begin(),
2087 REnd = PPOpts.remapped_file_buffer_end();
2088 R != REnd;
2089 ++R) {
2090 delete R->second;
2091 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002092 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002093 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2094 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2095 if (const llvm::MemoryBuffer *
2096 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2097 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2098 memBuf);
2099 } else {
2100 const char *fname = fileOrBuf.get<const char *>();
2101 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2102 fname);
2103 }
2104 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002105
Douglas Gregoreababfb2010-08-04 05:53:38 +00002106 // If we have a preamble file lying around, or if we might try to
2107 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002108 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002109 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002110 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002111
Douglas Gregorabc563f2010-07-19 21:46:24 +00002112 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002113 getDiagnostics().Reset();
2114 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002115 if (OverrideMainBuffer)
2116 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002117
Douglas Gregor175c4a92010-07-23 23:58:40 +00002118 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002119 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002120
2121 // If we're caching global code-completion results, and the top-level
2122 // declarations have changed, clear out the code-completion cache.
2123 if (!Result && ShouldCacheCodeCompletionResults &&
2124 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2125 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002126
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002127 // We now need to clear out the completion info related to this translation
2128 // unit; it'll be recreated if necessary.
2129 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002130
Douglas Gregor175c4a92010-07-23 23:58:40 +00002131 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002132}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002133
Douglas Gregor87c08a52010-08-13 22:48:40 +00002134//----------------------------------------------------------------------------//
2135// Code completion
2136//----------------------------------------------------------------------------//
2137
2138namespace {
2139 /// \brief Code completion consumer that combines the cached code-completion
2140 /// results from an ASTUnit with the code-completion results provided to it,
2141 /// then passes the result on to
2142 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002143 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002144 ASTUnit &AST;
2145 CodeCompleteConsumer &Next;
2146
2147 public:
2148 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002149 const CodeCompleteOptions &CodeCompleteOpts)
2150 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2151 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002152 {
2153 // Compute the set of contexts in which we will look when we don't have
2154 // any information about the specific context.
2155 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002156 = (1LL << CodeCompletionContext::CCC_TopLevel)
2157 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2158 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2159 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2160 | (1LL << CodeCompletionContext::CCC_Statement)
2161 | (1LL << CodeCompletionContext::CCC_Expression)
2162 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2163 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2164 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2165 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2166 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2167 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2168 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002169
David Blaikie4e4d0842012-03-11 07:00:24 +00002170 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002171 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2172 | (1LL << CodeCompletionContext::CCC_UnionTag)
2173 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002174 }
2175
2176 virtual void ProcessCodeCompleteResults(Sema &S,
2177 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002178 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002179 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002180
2181 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2182 OverloadCandidate *Candidates,
2183 unsigned NumCandidates) {
2184 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2185 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002186
Douglas Gregordae68752011-02-01 22:57:45 +00002187 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002188 return Next.getAllocator();
2189 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002190
2191 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2192 return Next.getCodeCompletionTUInfo();
2193 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002194 };
2195}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002196
Douglas Gregor5f808c22010-08-16 21:18:39 +00002197/// \brief Helper function that computes which global names are hidden by the
2198/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002199static void CalculateHiddenNames(const CodeCompletionContext &Context,
2200 CodeCompletionResult *Results,
2201 unsigned NumResults,
2202 ASTContext &Ctx,
2203 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002204 bool OnlyTagNames = false;
2205 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002206 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002207 case CodeCompletionContext::CCC_TopLevel:
2208 case CodeCompletionContext::CCC_ObjCInterface:
2209 case CodeCompletionContext::CCC_ObjCImplementation:
2210 case CodeCompletionContext::CCC_ObjCIvarList:
2211 case CodeCompletionContext::CCC_ClassStructUnion:
2212 case CodeCompletionContext::CCC_Statement:
2213 case CodeCompletionContext::CCC_Expression:
2214 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002215 case CodeCompletionContext::CCC_DotMemberAccess:
2216 case CodeCompletionContext::CCC_ArrowMemberAccess:
2217 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002218 case CodeCompletionContext::CCC_Namespace:
2219 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002220 case CodeCompletionContext::CCC_Name:
2221 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002222 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002223 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002224 break;
2225
2226 case CodeCompletionContext::CCC_EnumTag:
2227 case CodeCompletionContext::CCC_UnionTag:
2228 case CodeCompletionContext::CCC_ClassOrStructTag:
2229 OnlyTagNames = true;
2230 break;
2231
2232 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002233 case CodeCompletionContext::CCC_MacroName:
2234 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002235 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002236 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002237 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002238 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002239 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002240 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002241 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002242 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2243 case CodeCompletionContext::CCC_ObjCClassMessage:
2244 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002245 // We're looking for nothing, or we're looking for names that cannot
2246 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002247 return;
2248 }
2249
John McCall0a2c5e22010-08-25 06:19:51 +00002250 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002251 for (unsigned I = 0; I != NumResults; ++I) {
2252 if (Results[I].Kind != Result::RK_Declaration)
2253 continue;
2254
2255 unsigned IDNS
2256 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2257
2258 bool Hiding = false;
2259 if (OnlyTagNames)
2260 Hiding = (IDNS & Decl::IDNS_Tag);
2261 else {
2262 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002263 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2264 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002265 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002266 HiddenIDNS |= Decl::IDNS_Tag;
2267 Hiding = (IDNS & HiddenIDNS);
2268 }
2269
2270 if (!Hiding)
2271 continue;
2272
2273 DeclarationName Name = Results[I].Declaration->getDeclName();
2274 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2275 HiddenNames.insert(Identifier->getName());
2276 else
2277 HiddenNames.insert(Name.getAsString());
2278 }
2279}
2280
2281
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002282void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2283 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002284 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002285 unsigned NumResults) {
2286 // Merge the results we were given with the results we cached.
2287 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002288 uint64_t InContexts =
2289 Context.getKind() == CodeCompletionContext::CCC_Recovery
2290 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002291 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002292 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002293 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002294 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002295 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002296 C = AST.cached_completion_begin(),
2297 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002298 C != CEnd; ++C) {
2299 // If the context we are in matches any of the contexts we are
2300 // interested in, we'll add this result.
2301 if ((C->ShowInContexts & InContexts) == 0)
2302 continue;
2303
2304 // If we haven't added any results previously, do so now.
2305 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002306 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2307 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002308 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2309 AddedResult = true;
2310 }
2311
Douglas Gregor5f808c22010-08-16 21:18:39 +00002312 // Determine whether this global completion result is hidden by a local
2313 // completion result. If so, skip it.
2314 if (C->Kind != CXCursor_MacroDefinition &&
2315 HiddenNames.count(C->Completion->getTypedText()))
2316 continue;
2317
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002318 // Adjust priority based on similar type classes.
2319 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002320 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002321 if (!Context.getPreferredType().isNull()) {
2322 if (C->Kind == CXCursor_MacroDefinition) {
2323 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002324 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002325 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002326 } else if (C->Type) {
2327 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002328 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002329 Context.getPreferredType().getUnqualifiedType());
2330 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2331 if (ExpectedSTC == C->TypeClass) {
2332 // We know this type is similar; check for an exact match.
2333 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002334 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002335 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002336 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002337 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2338 Priority /= CCF_ExactTypeMatch;
2339 else
2340 Priority /= CCF_SimilarTypeMatch;
2341 }
2342 }
2343 }
2344
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002345 // Adjust the completion string, if required.
2346 if (C->Kind == CXCursor_MacroDefinition &&
2347 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2348 // Create a new code-completion string that just contains the
2349 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002350 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2351 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002352 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002353 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002354 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002355 }
2356
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002357 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002358 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002359 }
2360
2361 // If we did not add any cached completion results, just forward the
2362 // results we were given to the next consumer.
2363 if (!AddedResult) {
2364 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2365 return;
2366 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002367
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002368 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2369 AllResults.size());
2370}
2371
2372
2373
Chris Lattner5f9e2722011-07-23 10:55:15 +00002374void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 RemappedFile *RemappedFiles,
2376 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002377 bool IncludeMacros,
2378 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002379 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002380 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002381 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002383 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2384 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002385 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002386 return;
2387
Douglas Gregor213f18b2010-10-28 15:44:59 +00002388 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002389 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002390 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002391
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002392 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002393 CCInvocation(new CompilerInvocation(*Invocation));
2394
2395 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002396 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002397 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002398
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002399 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2400 CachedCompletionResults.empty();
2401 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2402 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2403 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2404
2405 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2406
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002407 FrontendOpts.CodeCompletionAt.FileName = File;
2408 FrontendOpts.CodeCompletionAt.Line = Line;
2409 FrontendOpts.CodeCompletionAt.Column = Column;
2410
2411 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002412 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002413
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002414 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002415
2416 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002417 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2418 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002419
Ted Kremenek4f327862011-03-21 18:40:17 +00002420 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002421 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002422
2423 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002424 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002425 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002426 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002427 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002428 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002429
2430 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002431 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002432 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002433 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002434 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002435 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002436 }
2437
2438 // Inform the target of the language options.
2439 //
2440 // FIXME: We shouldn't need to do this, the target should be immutable once
2441 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002442 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002443
Ted Kremenek03201fb2011-03-21 18:40:07 +00002444 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002445 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002446 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002447 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002448 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002449 "IR inputs not support here!");
2450
2451
2452 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002453 Clang->setFileManager(&FileMgr);
2454 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002455
2456 // Remap files.
2457 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002458 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002459 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002460 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2461 if (const llvm::MemoryBuffer *
2462 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2463 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2464 OwnedBuffers.push_back(memBuf);
2465 } else {
2466 const char *fname = fileOrBuf.get<const char *>();
2467 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2468 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002469 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002470
Douglas Gregor87c08a52010-08-13 22:48:40 +00002471 // Use the code completion consumer we were given, but adding any cached
2472 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002473 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002474 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002475 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002476
Douglas Gregordf95a132010-08-09 20:45:32 +00002477 // If we have a precompiled preamble, try to use it. We only allow
2478 // the use of the precompiled preamble if we're if the completion
2479 // point is within the main file, after the end of the precompiled
2480 // preamble.
2481 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002482 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002483 using llvm::sys::FileStatus;
Rafael Espindola105b2072013-06-18 19:40:07 +00002484 std::string CompleteFilePath(File);
2485 uint64_t CompleteFileID;
2486
2487 if (!llvm::sys::fs::GetUniqueID(CompleteFilePath, CompleteFileID)) {
2488 std::string MainPath(OriginalSourceFile);
2489 uint64_t MainID;
2490 if (!llvm::sys::fs::GetUniqueID(MainPath, MainID)) {
2491 if (CompleteFileID == MainID && Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002492 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002493 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002494 Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002495 }
2496 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002497 }
2498
2499 // If the main file has been overridden due to the use of a preamble,
2500 // make that override happen and introduce the preamble.
2501 if (OverrideMainBuffer) {
2502 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2503 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2504 PreprocessorOpts.PrecompiledPreambleBytes.second
2505 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002506 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002507 PreprocessorOpts.DisablePCHValidation = true;
2508
Douglas Gregor2283d792010-08-20 00:59:43 +00002509 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002510 } else {
2511 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2512 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002513 }
2514
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002515 // Disable the preprocessing record if modules are not enabled.
2516 if (!Clang->getLangOpts().Modules)
2517 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002518
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002519 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002520 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002521 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002522 Act->Execute();
2523 Act->EndSourceFile();
2524 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002525}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002526
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002527bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002528 if (HadModuleLoaderFatalFailure)
2529 return true;
2530
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002531 // Write to a temporary file and later rename it to the actual file, to avoid
2532 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002533 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002534 TempPath = File;
2535 TempPath += "-%%%%%%%%";
2536 int fd;
2537 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2538 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002539 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002540
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002541 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2542 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002543 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002544
2545 serialize(Out);
2546 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002547 if (Out.has_error()) {
2548 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002549 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002550 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002551
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002552 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002553 bool exists;
2554 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002555 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002556 }
2557
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002558 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002559}
2560
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002561static bool serializeUnit(ASTWriter &Writer,
2562 SmallVectorImpl<char> &Buffer,
2563 Sema &S,
2564 bool hasErrors,
2565 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002566 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002567
2568 // Write the generated bitstream to "Out".
2569 if (!Buffer.empty())
2570 OS.write(Buffer.data(), Buffer.size());
2571
2572 return false;
2573}
2574
Chris Lattner5f9e2722011-07-23 10:55:15 +00002575bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002576 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002577
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002578 if (WriterData)
2579 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2580 getSema(), hasErrors, OS);
2581
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002582 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002583 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002584 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002585 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002586}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002587
2588typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2589
2590static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2591 unsigned Raw = L.getRawEncoding();
2592 const unsigned MacroBit = 1U << 31;
2593 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2594 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2595}
2596
2597void ASTUnit::TranslateStoredDiagnostics(
2598 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002599 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002600 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002601 const SmallVectorImpl<StoredDiagnostic> &Diags,
2602 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002603 // The stored diagnostic has the old source manager in it; update
2604 // the locations to refer into the new source manager. We also need to remap
2605 // all the locations to the new view. This includes the diag location, any
2606 // associated source ranges, and the source ranges of associated fix-its.
2607 // FIXME: There should be a cleaner way to do this.
2608
Chris Lattner5f9e2722011-07-23 10:55:15 +00002609 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002610 Result.reserve(Diags.size());
2611 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002612 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002613 assert(Mod && "Don't have preamble module");
2614 SLocRemap &Remap = Mod->SLocRemap;
2615 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2616 // Rebuild the StoredDiagnostic.
2617 const StoredDiagnostic &SD = Diags[I];
2618 SourceLocation L = SD.getLocation();
2619 TranslateSLoc(L, Remap);
2620 FullSourceLoc Loc(L, SrcMgr);
2621
Chris Lattner5f9e2722011-07-23 10:55:15 +00002622 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002623 Ranges.reserve(SD.range_size());
2624 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2625 E = SD.range_end();
2626 I != E; ++I) {
2627 SourceLocation BL = I->getBegin();
2628 TranslateSLoc(BL, Remap);
2629 SourceLocation EL = I->getEnd();
2630 TranslateSLoc(EL, Remap);
2631 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2632 }
2633
Chris Lattner5f9e2722011-07-23 10:55:15 +00002634 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002635 FixIts.reserve(SD.fixit_size());
2636 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2637 E = SD.fixit_end();
2638 I != E; ++I) {
2639 FixIts.push_back(FixItHint());
2640 FixItHint &FH = FixIts.back();
2641 FH.CodeToInsert = I->CodeToInsert;
2642 SourceLocation BL = I->RemoveRange.getBegin();
2643 TranslateSLoc(BL, Remap);
2644 SourceLocation EL = I->RemoveRange.getEnd();
2645 TranslateSLoc(EL, Remap);
2646 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2647 I->RemoveRange.isTokenRange());
2648 }
2649
2650 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2651 SD.getMessage(), Loc, Ranges, FixIts));
2652 }
2653 Result.swap(Out);
2654}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002655
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002656static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2657 std::pair<unsigned, Decl *> R) {
2658 return L.first < R.first;
2659}
2660
2661void ASTUnit::addFileLevelDecl(Decl *D) {
2662 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002663
2664 // We only care about local declarations.
2665 if (D->isFromASTFile())
2666 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002667
2668 SourceManager &SM = *SourceMgr;
2669 SourceLocation Loc = D->getLocation();
2670 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2671 return;
2672
2673 // We only keep track of the file-level declarations of each file.
2674 if (!D->getLexicalDeclContext()->isFileContext())
2675 return;
2676
2677 SourceLocation FileLoc = SM.getFileLoc(Loc);
2678 assert(SM.isLocalSourceLocation(FileLoc));
2679 FileID FID;
2680 unsigned Offset;
2681 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2682 if (FID.isInvalid())
2683 return;
2684
2685 LocDeclsTy *&Decls = FileDecls[FID];
2686 if (!Decls)
2687 Decls = new LocDeclsTy();
2688
2689 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2690
2691 if (Decls->empty() || Decls->back().first <= Offset) {
2692 Decls->push_back(LocDecl);
2693 return;
2694 }
2695
2696 LocDeclsTy::iterator
2697 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2698
2699 Decls->insert(I, LocDecl);
2700}
2701
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002702void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2703 SmallVectorImpl<Decl *> &Decls) {
2704 if (File.isInvalid())
2705 return;
2706
2707 if (SourceMgr->isLoadedFileID(File)) {
2708 assert(Ctx->getExternalSource() && "No external source!");
2709 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2710 Decls);
2711 }
2712
2713 FileDeclsTy::iterator I = FileDecls.find(File);
2714 if (I == FileDecls.end())
2715 return;
2716
2717 LocDeclsTy &LocDecls = *I->second;
2718 if (LocDecls.empty())
2719 return;
2720
2721 LocDeclsTy::iterator
2722 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2723 std::make_pair(Offset, (Decl*)0), compLocDecl);
2724 if (BeginIt != LocDecls.begin())
2725 --BeginIt;
2726
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002727 // If we are pointing at a top-level decl inside an objc container, we need
2728 // to backtrack until we find it otherwise we will fail to report that the
2729 // region overlaps with an objc container.
2730 while (BeginIt != LocDecls.begin() &&
2731 BeginIt->second->isTopLevelDeclInObjCContainer())
2732 --BeginIt;
2733
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002734 LocDeclsTy::iterator
2735 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2736 std::make_pair(Offset+Length, (Decl*)0),
2737 compLocDecl);
2738 if (EndIt != LocDecls.end())
2739 ++EndIt;
2740
2741 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2742 Decls.push_back(DIt->second);
2743}
2744
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002745SourceLocation ASTUnit::getLocation(const FileEntry *File,
2746 unsigned Line, unsigned Col) const {
2747 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002748 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002749 return SM.getMacroArgExpandedLocation(Loc);
2750}
2751
2752SourceLocation ASTUnit::getLocation(const FileEntry *File,
2753 unsigned Offset) const {
2754 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002755 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002756 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2757}
2758
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002759/// \brief If \arg Loc is a loaded location from the preamble, returns
2760/// the corresponding local location of the main file, otherwise it returns
2761/// \arg Loc.
2762SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2763 FileID PreambleID;
2764 if (SourceMgr)
2765 PreambleID = SourceMgr->getPreambleFileID();
2766
2767 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2768 return Loc;
2769
2770 unsigned Offs;
2771 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2772 SourceLocation FileLoc
2773 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2774 return FileLoc.getLocWithOffset(Offs);
2775 }
2776
2777 return Loc;
2778}
2779
2780/// \brief If \arg Loc is a local location of the main file but inside the
2781/// preamble chunk, returns the corresponding loaded location from the
2782/// preamble, otherwise it returns \arg Loc.
2783SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2784 FileID PreambleID;
2785 if (SourceMgr)
2786 PreambleID = SourceMgr->getPreambleFileID();
2787
2788 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2789 return Loc;
2790
2791 unsigned Offs;
2792 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2793 Offs < Preamble.size()) {
2794 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2795 return FileLoc.getLocWithOffset(Offs);
2796 }
2797
2798 return Loc;
2799}
2800
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002801bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2802 FileID FID;
2803 if (SourceMgr)
2804 FID = SourceMgr->getPreambleFileID();
2805
2806 if (Loc.isInvalid() || FID.isInvalid())
2807 return false;
2808
2809 return SourceMgr->isInFileID(Loc, FID);
2810}
2811
2812bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2813 FileID FID;
2814 if (SourceMgr)
2815 FID = SourceMgr->getMainFileID();
2816
2817 if (Loc.isInvalid() || FID.isInvalid())
2818 return false;
2819
2820 return SourceMgr->isInFileID(Loc, FID);
2821}
2822
2823SourceLocation ASTUnit::getEndOfPreambleFileID() {
2824 FileID FID;
2825 if (SourceMgr)
2826 FID = SourceMgr->getPreambleFileID();
2827
2828 if (FID.isInvalid())
2829 return SourceLocation();
2830
2831 return SourceMgr->getLocForEndOfFile(FID);
2832}
2833
2834SourceLocation ASTUnit::getStartOfMainFileID() {
2835 FileID FID;
2836 if (SourceMgr)
2837 FID = SourceMgr->getMainFileID();
2838
2839 if (FID.isInvalid())
2840 return SourceLocation();
2841
2842 return SourceMgr->getLocForStartOfFile(FID);
2843}
2844
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002845std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2846ASTUnit::getLocalPreprocessingEntities() const {
2847 if (isMainFileAST()) {
2848 serialization::ModuleFile &
2849 Mod = Reader->getModuleManager().getPrimaryModule();
2850 return Reader->getModulePreprocessedEntities(Mod);
2851 }
2852
2853 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2854 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2855
2856 return std::make_pair(PreprocessingRecord::iterator(),
2857 PreprocessingRecord::iterator());
2858}
2859
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002860bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002861 if (isMainFileAST()) {
2862 serialization::ModuleFile &
2863 Mod = Reader->getModuleManager().getPrimaryModule();
2864 ASTReader::ModuleDeclIterator MDI, MDE;
2865 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2866 for (; MDI != MDE; ++MDI) {
2867 if (!Fn(context, *MDI))
2868 return false;
2869 }
2870
2871 return true;
2872 }
2873
2874 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2875 TLEnd = top_level_end();
2876 TL != TLEnd; ++TL) {
2877 if (!Fn(context, *TL))
2878 return false;
2879 }
2880
2881 return true;
2882}
2883
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002884namespace {
2885struct PCHLocatorInfo {
2886 serialization::ModuleFile *Mod;
2887 PCHLocatorInfo() : Mod(0) {}
2888};
2889}
2890
2891static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2892 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2893 switch (M.Kind) {
2894 case serialization::MK_Module:
2895 return true; // skip dependencies.
2896 case serialization::MK_PCH:
2897 Info.Mod = &M;
2898 return true; // found it.
2899 case serialization::MK_Preamble:
2900 return false; // look in dependencies.
2901 case serialization::MK_MainFile:
2902 return false; // look in dependencies.
2903 }
2904
2905 return true;
2906}
2907
2908const FileEntry *ASTUnit::getPCHFile() {
2909 if (!Reader)
2910 return 0;
2911
2912 PCHLocatorInfo Info;
2913 Reader->getModuleManager().visit(PCHLocator, &Info);
2914 if (Info.Mod)
2915 return Info.Mod->File;
2916
2917 return 0;
2918}
2919
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002920bool ASTUnit::isModuleFile() {
2921 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2922}
2923
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002924void ASTUnit::PreambleData::countLines() const {
2925 NumLines = 0;
2926 if (empty())
2927 return;
2928
2929 for (std::vector<char>::const_iterator
2930 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2931 if (*I == '\n')
2932 ++NumLines;
2933 }
2934 if (Buffer.back() != '\n')
2935 ++NumLines;
2936}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002937
2938#ifndef NDEBUG
2939ASTUnit::ConcurrencyState::ConcurrencyState() {
2940 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2941}
2942
2943ASTUnit::ConcurrencyState::~ConcurrencyState() {
2944 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2945}
2946
2947void ASTUnit::ConcurrencyState::start() {
2948 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2949 assert(acquired && "Concurrent access to ASTUnit!");
2950}
2951
2952void ASTUnit::ConcurrencyState::finish() {
2953 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2954}
2955
2956#else // NDEBUG
2957
2958ASTUnit::ConcurrencyState::ConcurrencyState() {}
2959ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2960void ASTUnit::ConcurrencyState::start() {}
2961void ASTUnit::ConcurrencyState::finish() {}
2962
2963#endif