blob: d6bdae4aafe154bca9ca4510248cc55577707838 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000033#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000036#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000042#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000045#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000046#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000047#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000048#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000049using namespace clang;
50
Douglas Gregor16896c42010-10-28 15:44:59 +000051using llvm::TimeRecord;
52
53namespace {
54 class SimpleTimer {
55 bool WantTiming;
56 TimeRecord Start;
57 std::string Output;
58
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000059 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000060 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000061 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000062 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000063 }
64
Chris Lattner0e62c1c2011-07-23 10:55:15 +000065 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000067 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000068 }
69
Douglas Gregor16896c42010-10-28 15:44:59 +000070 ~SimpleTimer() {
71 if (WantTiming) {
72 TimeRecord Elapsed = TimeRecord::getCurrentTime();
73 Elapsed -= Start;
74 llvm::errs() << Output << ':';
75 Elapsed.print(Elapsed, llvm::errs());
76 llvm::errs() << '\n';
77 }
78 }
79 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000080
81 struct OnDiskData {
82 /// \brief The file in which the precompiled preamble is stored.
83 std::string PreambleFile;
84
85 /// \brief Temporary files that should be removed when the ASTUnit is
86 /// destroyed.
87 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
88
89 /// \brief Erase temporary files.
90 void CleanTemporaryFiles();
91
92 /// \brief Erase the preamble file.
93 void CleanPreambleFile();
94
95 /// \brief Erase temporary files and the preamble file.
96 void Cleanup();
97 };
98}
99
Ted Kremenekbd307a52011-10-27 19:44:25 +0000100static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
101 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
102 return M;
103}
104
Ted Kremenek06b4f912011-10-27 17:55:18 +0000105static void cleanupOnDiskMapAtExit(void);
106
107typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
108static OnDiskDataMap &getOnDiskDataMap() {
109 static OnDiskDataMap M;
110 static bool hasRegisteredAtExit = false;
111 if (!hasRegisteredAtExit) {
112 hasRegisteredAtExit = true;
113 atexit(cleanupOnDiskMapAtExit);
114 }
115 return M;
116}
117
118static void cleanupOnDiskMapAtExit(void) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000119 // No mutex required here since we are leaving the program.
Ted Kremenek06b4f912011-10-27 17:55:18 +0000120 OnDiskDataMap &M = getOnDiskDataMap();
121 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
122 // We don't worry about freeing the memory associated with OnDiskDataMap.
123 // All we care about is erasing stale files.
124 I->second->Cleanup();
125 }
126}
127
128static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000129 // We require the mutex since we are modifying the structure of the
130 // DenseMap.
131 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000132 OnDiskDataMap &M = getOnDiskDataMap();
133 OnDiskData *&D = M[AU];
134 if (!D)
135 D = new OnDiskData();
136 return *D;
137}
138
139static void erasePreambleFile(const ASTUnit *AU) {
140 getOnDiskData(AU).CleanPreambleFile();
141}
142
143static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000144 // We require the mutex since we are modifying the structure of the
145 // DenseMap.
146 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000147 OnDiskDataMap &M = getOnDiskDataMap();
148 OnDiskDataMap::iterator I = M.find(AU);
149 if (I != M.end()) {
150 I->second->Cleanup();
151 delete I->second;
152 M.erase(AU);
153 }
154}
155
156static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
157 getOnDiskData(AU).PreambleFile = preambleFile;
158}
159
160static const std::string &getPreambleFile(const ASTUnit *AU) {
161 return getOnDiskData(AU).PreambleFile;
162}
163
164void OnDiskData::CleanTemporaryFiles() {
165 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
166 TemporaryFiles[I].eraseFromDisk();
167 TemporaryFiles.clear();
168}
169
170void OnDiskData::CleanPreambleFile() {
171 if (!PreambleFile.empty()) {
172 llvm::sys::Path(PreambleFile).eraseFromDisk();
173 PreambleFile.clear();
174 }
175}
176
177void OnDiskData::Cleanup() {
178 CleanTemporaryFiles();
179 CleanPreambleFile();
180}
181
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000182void ASTUnit::clearFileLevelDecls() {
183 for (FileDeclsTy::iterator
184 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
185 delete I->second;
186 FileDecls.clear();
187}
188
Ted Kremenek06b4f912011-10-27 17:55:18 +0000189void ASTUnit::CleanTemporaryFiles() {
190 getOnDiskData(this).CleanTemporaryFiles();
191}
192
193void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
194 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000195}
196
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000197/// \brief After failing to build a precompiled preamble (due to
198/// errors in the source that occurs in the preamble), the number of
199/// reparses during which we'll skip even trying to precompile the
200/// preamble.
201const unsigned DefaultPreambleRebuildInterval = 5;
202
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000203/// \brief Tracks the number of ASTUnit objects that are currently active.
204///
205/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000206static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000207
Douglas Gregord03e8232010-04-05 21:10:19 +0000208ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000209 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000210 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000211 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000212 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000213 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000214 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis85b4a372011-11-29 18:18:33 +0000215 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000216 ShouldCacheCodeCompletionResults(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000217 CompletionCacheTopLevelHashValue(0),
218 PreambleTopLevelHashValue(0),
219 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000220 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000221 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000222 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000223 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
224 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000225}
Douglas Gregord03e8232010-04-05 21:10:19 +0000226
Daniel Dunbar764c0822009-12-01 09:51:01 +0000227ASTUnit::~ASTUnit() {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000228 clearFileLevelDecls();
229
Ted Kremenek06b4f912011-10-27 17:55:18 +0000230 // Clean up the temporary files and the preamble file.
231 removeOnDiskEntry(this);
232
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000233 // Free the buffers associated with remapped files. We are required to
234 // perform this operation here because we explicitly request that the
235 // compiler instance *not* free these buffers for each invocation of the
236 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000237 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000238 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
239 for (PreprocessorOptions::remapped_file_buffer_iterator
240 FB = PPOpts.remapped_file_buffer_begin(),
241 FBEnd = PPOpts.remapped_file_buffer_end();
242 FB != FBEnd;
243 ++FB)
244 delete FB->second;
245 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000246
247 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000248 delete PreambleBuffer;
249
Douglas Gregor16896c42010-10-28 15:44:59 +0000250 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000251
252 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000253 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000254 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
255 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000256}
257
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000258void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
259
Douglas Gregor39982192010-08-15 06:18:01 +0000260/// \brief Determine the set of code-completion contexts in which this
261/// declaration should be shown.
262static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000263 const LangOptions &LangOpts,
264 bool &IsNestedNameSpecifier) {
265 IsNestedNameSpecifier = false;
266
Douglas Gregor39982192010-08-15 06:18:01 +0000267 if (isa<UsingShadowDecl>(ND))
268 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
269 if (!ND)
270 return 0;
271
272 unsigned Contexts = 0;
273 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
274 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
275 // Types can appear in these contexts.
276 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
277 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
278 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
279 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
280 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000281 | (1 << (CodeCompletionContext::CCC_Type - 1))
282 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000283
284 // In C++, types can appear in expressions contexts (for functional casts).
285 if (LangOpts.CPlusPlus)
286 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
287
288 // In Objective-C, message sends can send interfaces. In Objective-C++,
289 // all types are available due to functional casts.
290 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
291 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000292
293 // In Objective-C, you can only be a subclass of another Objective-C class
294 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor2c595ad2011-07-30 06:55:39 +0000295 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000296
297 // Deal with tag names.
298 if (isa<EnumDecl>(ND)) {
299 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
300
Douglas Gregor59cab552010-08-16 23:05:20 +0000301 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000302 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000303 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000304 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
305 if (Record->isUnion())
306 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
307 else
308 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
309
Douglas Gregor39982192010-08-15 06:18:01 +0000310 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000311 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000312 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000314 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
315 // Values can appear in these contexts.
316 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
317 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000318 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000319 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
320 } else if (isa<ObjCProtocolDecl>(ND)) {
321 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000322 } else if (isa<ObjCCategoryDecl>(ND)) {
323 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000324 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000325 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000326
327 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000328 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000329 }
330
331 return Contexts;
332}
333
Douglas Gregorb14904c2010-08-13 22:48:40 +0000334void ASTUnit::CacheCodeCompletionResults() {
335 if (!TheSema)
336 return;
337
Douglas Gregor16896c42010-10-28 15:44:59 +0000338 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000339 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340
341 // Clear out the previous results.
342 ClearCachedCompletionResults();
343
344 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000345 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000346 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000347 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000348 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
349 getCodeCompletionTUInfo(), Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000350
351 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000352 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
353
Douglas Gregorb14904c2010-08-13 22:48:40 +0000354 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
355 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000356 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000357 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000358 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000359 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000360 *CachedCompletionAllocator,
361 getCodeCompletionTUInfo());
Douglas Gregor39982192010-08-15 06:18:01 +0000362 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000363 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000364 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000365 CachedResult.Priority = Results[I].Priority;
366 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000367 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000368
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000369 // Keep track of the type of this completion in an ASTContext-agnostic
370 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000371 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000372 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000373 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000374 CachedResult.Type = 0;
375 } else {
376 CanQualType CanUsageType
377 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
378 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
379
380 // Determine whether we have already seen this type. If so, we save
381 // ourselves the work of formatting the type string by using the
382 // temporary, CanQualType-based hash table to find the associated value.
383 unsigned &TypeValue = CompletionTypes[CanUsageType];
384 if (TypeValue == 0) {
385 TypeValue = CompletionTypes.size();
386 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
387 = TypeValue;
388 }
389
390 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000391 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000392
Douglas Gregor39982192010-08-15 06:18:01 +0000393 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000394
395 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000396 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000397 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
398 // The contexts in which a nested-name-specifier can appear in C++.
399 unsigned NNSContexts
400 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
401 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
402 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
403 | (1 << (CodeCompletionContext::CCC_Statement - 1))
404 | (1 << (CodeCompletionContext::CCC_Expression - 1))
405 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
406 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
407 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
408 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000409 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000410 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
411 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000412
413 if (isa<NamespaceDecl>(Results[I].Declaration) ||
414 isa<NamespaceAliasDecl>(Results[I].Declaration))
415 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
416
417 if (unsigned RemainingContexts
418 = NNSContexts & ~CachedResult.ShowInContexts) {
419 // If there any contexts where this completion can be a
420 // nested-name-specifier but isn't already an option, create a
421 // nested-name-specifier completion.
422 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000423 CachedResult.Completion
424 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000425 *CachedCompletionAllocator,
426 getCodeCompletionTUInfo());
Douglas Gregor59cab552010-08-16 23:05:20 +0000427 CachedResult.ShowInContexts = RemainingContexts;
428 CachedResult.Priority = CCP_NestedNameSpecifier;
429 CachedResult.TypeClass = STC_Void;
430 CachedResult.Type = 0;
431 CachedCompletionResults.push_back(CachedResult);
432 }
433 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000434 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000435 }
436
Douglas Gregorb14904c2010-08-13 22:48:40 +0000437 case Result::RK_Keyword:
438 case Result::RK_Pattern:
439 // Ignore keywords and patterns; we don't care, since they are so
440 // easily regenerated.
441 break;
442
443 case Result::RK_Macro: {
444 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000445 CachedResult.Completion
446 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000447 *CachedCompletionAllocator,
448 getCodeCompletionTUInfo());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000449 CachedResult.ShowInContexts
450 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
451 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
452 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
453 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
454 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
455 | (1 << (CodeCompletionContext::CCC_Statement - 1))
456 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000457 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000458 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000459 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000460 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
461 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000462
Douglas Gregorb14904c2010-08-13 22:48:40 +0000463 CachedResult.Priority = Results[I].Priority;
464 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000465 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000466 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000467 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000468 CachedCompletionResults.push_back(CachedResult);
469 break;
470 }
471 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000472 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000473
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000476}
477
478void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000479 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000480 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000481 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482}
483
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000484namespace {
485
Sebastian Redl2c499f62010-08-18 23:56:43 +0000486/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000487/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000488class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000489 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000490 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000491 LangOptions &LangOpt;
492 HeaderSearch &HSI;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000493 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494 std::string &Predefines;
495 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregore8bbc122011-09-02 00:18:52 +0000499 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000500public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000501 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
502 HeaderSearch &HSI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000503 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor83297df2011-09-01 23:39:15 +0000504 std::string &Predefines,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000505 unsigned &Counter)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000506 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor83297df2011-09-01 23:39:15 +0000507 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000508 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000509
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000510 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000511 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000512 return false;
513
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000514 LangOpt = LangOpts;
Douglas Gregor83297df2011-09-01 23:39:15 +0000515
516 // Initialize the preprocessor.
517 PP.Initialize(*Target);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000518
519 // Initialize the ASTContext
520 Context.InitBuiltinTypes(*Target);
521
522 InitializedLanguage = true;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000523 return false;
524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000526 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000527 // If we've already initialized the target, don't do it again.
528 if (Target)
529 return false;
530
531 // FIXME: This is broken, we should store the TargetOptions in the AST file.
532 TargetOptions TargetOpts;
533 TargetOpts.ABI = "";
534 TargetOpts.CXXABI = "";
535 TargetOpts.CPU = "";
536 TargetOpts.Features.clear();
537 TargetOpts.Triple = Triple;
538 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000539 return false;
540 }
Mike Stump11289f42009-09-09 15:08:12 +0000541
Sebastian Redl8b41f302010-07-14 23:29:55 +0000542 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000543 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000544 std::string &SuggestedPredefines,
545 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000546 Predefines = Buffers[0].Data;
547 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
548 Predefines += Buffers[I].Data;
549 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000550 return false;
551 }
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregora2f49452010-03-16 19:09:18 +0000553 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000554 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
555 }
Mike Stump11289f42009-09-09 15:08:12 +0000556
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000557 virtual void ReadCounter(unsigned Value) {
558 Counter = Value;
559 }
560};
561
David Blaikief18d91a2011-09-26 00:01:39 +0000562class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000563 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000564
565public:
David Blaikief18d91a2011-09-26 00:01:39 +0000566 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000567 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000568 : StoredDiags(StoredDiags) { }
569
David Blaikie9c902b52011-09-25 23:23:43 +0000570 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000571 const Diagnostic &Info);
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000572
573 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
574 // Just drop any diagnostics that come from cloned consumers; they'll
575 // have different source managers anyway.
Douglas Gregore1fbde52012-01-29 19:57:03 +0000576 // FIXME: We'd like to be able to capture these somehow, even if it's just
577 // file/line/column, because they could occur when parsing module maps or
578 // building modules on-demand.
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000579 return new IgnoringDiagConsumer();
580 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000581};
582
583/// \brief RAII object that optionally captures diagnostics, if
584/// there is no diagnostic client to capture them already.
585class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000586 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000587 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000588 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000589
590public:
David Blaikie9c902b52011-09-25 23:23:43 +0000591 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000592 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000593 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000594 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000595 if (RequestCapture || Diags.getClient() == 0) {
596 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000597 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000598 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000599 }
600
601 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000602 if (Diags.getClient() == &Client) {
603 Diags.takeClient();
604 Diags.setClient(PreviousClient);
605 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000606 }
607};
608
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000609} // anonymous namespace
610
David Blaikief18d91a2011-09-26 00:01:39 +0000611void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000612 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000613 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000614 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000615
Douglas Gregor33cdd812010-02-18 18:08:43 +0000616 StoredDiags.push_back(StoredDiagnostic(Level, Info));
617}
618
Steve Naroffc0683b92009-09-03 18:19:54 +0000619const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000620 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000621}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000622
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000623llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000624 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000625 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000626 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000627}
628
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000629/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000630void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000631 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000632 ASTUnit &AST, bool CaptureDiagnostics) {
633 if (!Diags.getPtr()) {
634 // No diagnostics engine was provided, so create our own diagnostics object
635 // with the default options.
636 DiagnosticOptions DiagOpts;
David Blaikiee2eefae2011-09-25 23:39:51 +0000637 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000638 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000639 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerffe7c7f2012-04-14 09:11:56 +0000640 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
641 ArgBegin, Client,
642 /*ShouldOwnClient=*/true,
643 /*ShouldCloneClient=*/false);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000644 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000645 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000646 }
647}
648
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000649ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000650 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000651 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000652 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000653 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000654 unsigned NumRemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000655 bool CaptureDiagnostics,
656 bool AllowPCHWithCompilerErrors) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000657 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000658
659 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000660 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
661 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000662 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
663 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000664 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000665
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000666 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000667
Douglas Gregor16bef852009-10-16 20:01:17 +0000668 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000669 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000670 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000671 AST->FileMgr = new FileManager(FileSystemOpts);
672 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
673 AST->getFileManager());
Douglas Gregor197ac202011-11-11 00:35:06 +0000674 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000675 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000676 AST->ASTFileLangOpts,
677 /*Target=*/0));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000678
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000679 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000680 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
681 if (const llvm::MemoryBuffer *
682 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
683 // Create the file entry for the file that we're mapping from.
684 const FileEntry *FromFile
685 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
686 memBuf->getBufferSize(),
687 0);
688 if (!FromFile) {
689 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
690 << RemappedFiles[I].first;
691 delete memBuf;
692 continue;
693 }
694
695 // Override the contents of the "from" file with the contents of
696 // the "to" file.
697 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
698
699 } else {
700 const char *fname = fileOrBuf.get<const char *>();
701 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
702 if (!ToFile) {
703 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
704 << RemappedFiles[I].first << fname;
705 continue;
706 }
707
708 // Create the file entry for the file that we're mapping from.
709 const FileEntry *FromFile
710 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
711 ToFile->getSize(),
712 0);
713 if (!FromFile) {
714 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
715 << RemappedFiles[I].first;
716 delete memBuf;
717 continue;
718 }
719
720 // Override the contents of the "from" file with the contents of
721 // the "to" file.
722 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000723 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000724 }
725
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000726 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000727
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000728 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000729 std::string Predefines;
730 unsigned Counter;
731
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000732 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000733
Douglas Gregor83297df2011-09-01 23:39:15 +0000734 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
735 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
736 *AST,
737 /*IILookup=*/0,
738 /*OwnsHeaderSearch=*/false,
739 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000740 Preprocessor &PP = *AST->PP;
741
742 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
743 AST->getSourceManager(),
744 /*Target=*/0,
745 PP.getIdentifierTable(),
746 PP.getSelectorTable(),
747 PP.getBuiltinInfo(),
748 /* size_reserve = */0,
749 /*DelayInitialization=*/true);
750 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000751
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000752 Reader.reset(new ASTReader(PP, Context,
753 /*isysroot=*/"",
754 /*DisableValidation=*/false,
755 /*DisableStatCache=*/false,
756 AllowPCHWithCompilerErrors));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000757
758 // Recover resources if we crash before exiting this method.
759 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
760 ReaderCleanup(Reader.get());
761
Douglas Gregore8bbc122011-09-02 00:18:52 +0000762 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor83297df2011-09-01 23:39:15 +0000763 AST->ASTFileLangOpts, HeaderInfo,
764 AST->Target, Predefines, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000765
Douglas Gregora6895d82011-07-22 16:00:58 +0000766 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000767 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000768 break;
Mike Stump11289f42009-09-09 15:08:12 +0000769
Sebastian Redl2c499f62010-08-18 23:56:43 +0000770 case ASTReader::Failure:
771 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000772 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000773 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Daniel Dunbara8a50932009-12-02 08:44:16 +0000776 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
777
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000778 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000779 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000780
Sebastian Redl2c499f62010-08-18 23:56:43 +0000781 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000782 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000783 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000784 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000785 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000786
787 // Unregister the cleanup for ASTReader. It will get cleaned up
788 // by the ASTUnit cleanup.
789 ReaderCleanup.unregister();
790
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000791 Context.setExternalSource(Source);
792
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000793 // Create an AST consumer, even though it isn't used.
794 AST->Consumer.reset(new ASTConsumer);
795
Sebastian Redl2c499f62010-08-18 23:56:43 +0000796 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000797 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
798 AST->TheSema->Initialize();
799 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000800 AST->Reader = ReaderPtr;
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000801
Mike Stump11289f42009-09-09 15:08:12 +0000802 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000803}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000804
805namespace {
806
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000807/// \brief Preprocessor callback class that updates a hash value with the names
808/// of all macros that have been defined by the translation unit.
809class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
810 unsigned &Hash;
811
812public:
813 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
814
815 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
816 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
817 }
818};
819
820/// \brief Add the given declaration to the hash of all top-level entities.
821void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
822 if (!D)
823 return;
824
825 DeclContext *DC = D->getDeclContext();
826 if (!DC)
827 return;
828
829 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
830 return;
831
832 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
833 if (ND->getIdentifier())
834 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
835 else if (DeclarationName Name = ND->getDeclName()) {
836 std::string NameStr = Name.getAsString();
837 Hash = llvm::HashString(NameStr, Hash);
838 }
839 return;
Douglas Gregorf6102672012-01-01 21:23:57 +0000840 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000841}
842
Daniel Dunbar644dca02009-12-04 08:17:33 +0000843class TopLevelDeclTrackerConsumer : public ASTConsumer {
844 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000845 unsigned &Hash;
846
Daniel Dunbar644dca02009-12-04 08:17:33 +0000847public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
849 : Unit(_Unit), Hash(Hash) {
850 Hash = 0;
851 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000853 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000854 if (!D)
855 return;
856
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000857 // FIXME: Currently ObjC method declarations are incorrectly being
858 // reported as top-level declarations, even though their DeclContext
859 // is the containing ObjC @interface/@implementation. This is a
860 // fundamental problem in the parser right now.
861 if (isa<ObjCMethodDecl>(D))
862 return;
863
864 AddTopLevelDeclarationToHash(D, Hash);
865 Unit.addTopLevelDecl(D);
866
867 handleFileLevelDecl(D);
868 }
869
870 void handleFileLevelDecl(Decl *D) {
871 Unit.addFileLevelDecl(D);
872 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
873 for (NamespaceDecl::decl_iterator
874 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
875 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000876 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000877 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000878
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000879 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000880 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
881 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000882 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000883 }
884
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000885 // We're not interested in "interesting" decls.
886 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000887
888 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
889 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
890 handleTopLevelDecl(*it);
891 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000892};
893
894class TopLevelDeclTrackerAction : public ASTFrontendAction {
895public:
896 ASTUnit &Unit;
897
Daniel Dunbar764c0822009-12-01 09:51:01 +0000898 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000899 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000900 CI.getPreprocessor().addPPCallbacks(
901 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
902 return new TopLevelDeclTrackerConsumer(Unit,
903 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000904 }
905
906public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000907 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
908
Daniel Dunbar764c0822009-12-01 09:51:01 +0000909 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000910 virtual TranslationUnitKind getTranslationUnitKind() {
911 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000912 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000913};
914
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000915class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000916 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000917 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000918 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000919
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000920public:
Douglas Gregor36db4f92011-08-25 22:35:51 +0000921 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000922 StringRef isysroot, raw_ostream *Out)
Douglas Gregorf7a700fd2011-11-30 04:39:39 +0000923 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000924 Hash(Unit.getCurrentTopLevelHashValue()) {
925 Hash = 0;
926 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000927
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000928 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000929 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
930 Decl *D = *it;
931 // FIXME: Currently ObjC method declarations are incorrectly being
932 // reported as top-level declarations, even though their DeclContext
933 // is the containing ObjC @interface/@implementation. This is a
934 // fundamental problem in the parser right now.
935 if (isa<ObjCMethodDecl>(D))
936 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000937 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000938 TopLevelDecls.push_back(D);
939 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000940 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000941 }
942
943 virtual void HandleTranslationUnit(ASTContext &Ctx) {
944 PCHGenerator::HandleTranslationUnit(Ctx);
945 if (!Unit.getDiagnostics().hasErrorOccurred()) {
946 // Translate the top-level declarations we captured during
947 // parsing into declaration IDs in the precompiled
948 // preamble. This will allow us to deserialize those top-level
949 // declarations when requested.
950 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
951 Unit.addTopLevelDeclFromPreamble(
952 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000953 }
954 }
955};
956
957class PrecompilePreambleAction : public ASTFrontendAction {
958 ASTUnit &Unit;
959
960public:
961 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
962
963 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000964 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000965 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000966 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000967 raw_ostream *OS = 0;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000968 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
969 OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000970 OS))
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000971 return 0;
972
Douglas Gregorc567ba22011-07-22 16:35:34 +0000973 if (!CI.getFrontendOpts().RelocatablePCH)
974 Sysroot.clear();
975
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000976 CI.getPreprocessor().addPPCallbacks(
977 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor36db4f92011-08-25 22:35:51 +0000978 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
979 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000980 }
981
982 virtual bool hasCodeCompletionSupport() const { return false; }
983 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000984 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000985};
986
Daniel Dunbar764c0822009-12-01 09:51:01 +0000987}
988
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000989static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
990 StoredDiagnostics) {
991 // Get rid of stored diagnostics except the ones from the driver which do not
992 // have a source location.
993 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
994 if (StoredDiagnostics[I].getLocation().isValid()) {
995 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
996 --I;
997 }
998 }
999}
1000
1001static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1002 StoredDiagnostics,
1003 SourceManager &SM) {
1004 // The stored diagnostic has the old source manager in it; update
1005 // the locations to refer into the new source manager. Since we've
1006 // been careful to make sure that the source manager's state
1007 // before and after are identical, so that we can reuse the source
1008 // location itself.
1009 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1010 if (StoredDiagnostics[I].getLocation().isValid()) {
1011 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1012 StoredDiagnostics[I].setLocation(Loc);
1013 }
1014 }
1015}
1016
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001017/// Parse the source file into a translation unit using the given compiler
1018/// invocation, replacing the current translation unit.
1019///
1020/// \returns True if a failure occurred that causes the ASTUnit not to
1021/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001022bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001023 delete SavedMainFileBuffer;
1024 SavedMainFileBuffer = 0;
1025
Ted Kremenek5e14d392011-03-21 18:40:17 +00001026 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001027 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001028 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001029 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001030
Daniel Dunbar764c0822009-12-01 09:51:01 +00001031 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001032 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001033
1034 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001035 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1036 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001037
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001038 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001039 CCInvocation(new CompilerInvocation(*Invocation));
1040
1041 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor32fbe312012-01-20 16:28:04 +00001042 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001043
Douglas Gregor8e984da2010-08-04 16:47:14 +00001044 // Set up diagnostics, capturing any diagnostics that would
1045 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001046 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001047
Daniel Dunbar764c0822009-12-01 09:51:01 +00001048 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001049 Clang->getTargetOpts().Features = TargetFeatures;
1050 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001051 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001052 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001053 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001054 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001055 }
1056
Daniel Dunbar764c0822009-12-01 09:51:01 +00001057 // Inform the target of the language options.
1058 //
1059 // FIXME: We shouldn't need to do this, the target should be immutable once
1060 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001061 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001062
Ted Kremenek84de4a12011-03-21 18:40:07 +00001063 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001064 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001065 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001066 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001067 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001068 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001069
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070 // Configure the various subsystems.
1071 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001072 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001073 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001074 FileMgr = new FileManager(FileSystemOpts);
1075 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001076 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001077 Ctx = 0;
1078 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001079 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001080
1081 // Clear out old caches and data.
1082 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001083 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001084 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001085
Douglas Gregor7b02b582010-08-20 00:02:33 +00001086 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001087 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001088 TopLevelDeclsInPreamble.clear();
1089 }
1090
Daniel Dunbar764c0822009-12-01 09:51:01 +00001091 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001092 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001093
Daniel Dunbar764c0822009-12-01 09:51:01 +00001094 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001095 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001096
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001097 // If the main file has been overridden due to the use of a preamble,
1098 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001100 if (OverrideMainBuffer) {
1101 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1102 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1103 PreprocessorOpts.PrecompiledPreambleBytes.second
1104 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001105 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001106 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001107
Douglas Gregord9a30af2010-08-02 20:51:39 +00001108 // The stored diagnostic has the old source manager in it; update
1109 // the locations to refer into the new source manager. Since we've
1110 // been careful to make sure that the source manager's state
1111 // before and after are identical, so that we can reuse the source
1112 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001113 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001114
1115 // Keep track of the override buffer;
1116 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001117 }
1118
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001119 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001120 new TopLevelDeclTrackerAction(*this));
1121
1122 // Recover resources if we crash before exiting this method.
1123 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1124 ActCleanup(Act.get());
1125
Douglas Gregor32fbe312012-01-20 16:28:04 +00001126 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001127 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001128
1129 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001130 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001131 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1132 getSourceManager(), PreambleDiagnostics,
1133 StoredDiagnostics);
1134 }
1135
Daniel Dunbar644dca02009-12-04 08:17:33 +00001136 Act->Execute();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001137
1138 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001139
Daniel Dunbar644dca02009-12-04 08:17:33 +00001140 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001141
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001142 FailedParseDiagnostics.clear();
1143
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001144 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001145
Daniel Dunbar764c0822009-12-01 09:51:01 +00001146error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001147 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001148 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001149 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001150 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001151 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001152
1153 // Keep the ownership of the data in the ASTUnit because the client may
1154 // want to see the diagnostics.
1155 transferASTDataFromCompilerInstance(*Clang);
1156 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001157 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001158 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001159 return true;
1160}
1161
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001162/// \brief Simple function to retrieve a path for a preamble precompiled header.
1163static std::string GetPreamblePCHPath() {
1164 // FIXME: This is lame; sys::Path should provide this function (in particular,
1165 // it should know how to find the temporary files dir).
1166 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001167 // FIXME: This is a hack so that we can override the preamble file during
1168 // crash-recovery testing, which is the only case where the preamble files
1169 // are not necessarily cleaned up.
1170 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1171 if (TmpFile)
1172 return TmpFile;
1173
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001174 std::string Error;
1175 const char *TmpDir = ::getenv("TMPDIR");
1176 if (!TmpDir)
1177 TmpDir = ::getenv("TEMP");
1178 if (!TmpDir)
1179 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001180#ifdef LLVM_ON_WIN32
1181 if (!TmpDir)
1182 TmpDir = ::getenv("USERPROFILE");
1183#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001184 if (!TmpDir)
1185 TmpDir = "/tmp";
1186 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001187 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001188 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001189 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001190 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191 return std::string();
1192
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001193 return P.str();
1194}
1195
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001196/// \brief Compute the preamble for the main file, providing the source buffer
1197/// that corresponds to the main file along with a pair (bytes, start-of-line)
1198/// that describes the preamble.
1199std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001200ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1201 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001202 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001203 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001204 CreatedBuffer = false;
1205
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206 // Try to determine if the main file has been remapped, either from the
1207 // command line (to another file) or directly through the compiler invocation
1208 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001209 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor32fbe312012-01-20 16:28:04 +00001210 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001211 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1212 // Check whether there is a file-file remapping of the main file
1213 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001214 M = PreprocessorOpts.remapped_file_begin(),
1215 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001216 M != E;
1217 ++M) {
1218 llvm::sys::PathWithStatus MPath(M->first);
1219 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1220 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1221 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001222 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001223 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001224 CreatedBuffer = false;
1225 }
1226
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001227 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001228 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001229 return std::make_pair((llvm::MemoryBuffer*)0,
1230 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001231 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001232 }
1233 }
1234 }
1235
1236 // Check whether there is a file-buffer remapping. It supercedes the
1237 // file-file remapping.
1238 for (PreprocessorOptions::remapped_file_buffer_iterator
1239 M = PreprocessorOpts.remapped_file_buffer_begin(),
1240 E = PreprocessorOpts.remapped_file_buffer_end();
1241 M != E;
1242 ++M) {
1243 llvm::sys::PathWithStatus MPath(M->first);
1244 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1245 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1246 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001247 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001248 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001249 CreatedBuffer = false;
1250 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001251
Douglas Gregor4dde7492010-07-23 23:58:40 +00001252 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001253 }
1254 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001255 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001256 }
1257
1258 // If the main source file was not remapped, load it now.
1259 if (!Buffer) {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001260 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001261 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001262 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263
1264 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001265 }
1266
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001267 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001268 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001269 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001270}
1271
Douglas Gregor6481ef12010-07-24 00:38:13 +00001272static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001273 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001274 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001275 llvm::MemoryBuffer *Result
1276 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1277 memcpy(const_cast<char*>(Result->getBufferStart()),
1278 Old->getBufferStart(), Old->getBufferSize());
1279 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001280 ' ', NewSize - Old->getBufferSize() - 1);
1281 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001282
Douglas Gregor6481ef12010-07-24 00:38:13 +00001283 return Result;
1284}
1285
Douglas Gregor4dde7492010-07-23 23:58:40 +00001286/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1287/// the source file.
1288///
1289/// This routine will compute the preamble of the main source file. If a
1290/// non-trivial preamble is found, it will precompile that preamble into a
1291/// precompiled header so that the precompiled preamble can be used to reduce
1292/// reparsing time. If a precompiled preamble has already been constructed,
1293/// this routine will determine if it is still valid and, if so, avoid
1294/// rebuilding the precompiled preamble.
1295///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001296/// \param AllowRebuild When true (the default), this routine is
1297/// allowed to rebuild the precompiled preamble if it is found to be
1298/// out-of-date.
1299///
1300/// \param MaxLines When non-zero, the maximum number of lines that
1301/// can occur within the preamble.
1302///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001303/// \returns If the precompiled preamble can be used, returns a newly-allocated
1304/// buffer that should be used in place of the main file when doing so.
1305/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001306llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001307 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001308 bool AllowRebuild,
1309 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001310
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001311 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001312 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1313 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001314 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001315 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001316
1317 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001318 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001319 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001320
Douglas Gregor925296b2011-07-19 16:10:42 +00001321 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001322 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001323 if (CreatedPreambleBuffer)
1324 OwnedPreambleBuffer.reset(NewPreamble.first);
1325
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001326 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001327 // We couldn't find a preamble in the main source. Clear out the current
1328 // preamble, if we have one. It's obviously no good any more.
1329 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001330 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001331
1332 // The next time we actually see a preamble, precompile it.
1333 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001334 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001335 }
1336
1337 if (!Preamble.empty()) {
1338 // We've previously computed a preamble. Check whether we have the same
1339 // preamble now that we did before, and that there's enough space in
1340 // the main-file buffer within the precompiled preamble to fit the
1341 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001342 if (Preamble.size() == NewPreamble.second.first &&
1343 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001344 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001345 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001346 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001347 // The preamble has not changed. We may be able to re-use the precompiled
1348 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001349
Douglas Gregor0e119552010-07-31 00:40:00 +00001350 // Check that none of the files used by the preamble have changed.
1351 bool AnyFileChanged = false;
1352
1353 // First, make a record of those files that have been overridden via
1354 // remapping or unsaved_files.
1355 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1356 for (PreprocessorOptions::remapped_file_iterator
1357 R = PreprocessorOpts.remapped_file_begin(),
1358 REnd = PreprocessorOpts.remapped_file_end();
1359 !AnyFileChanged && R != REnd;
1360 ++R) {
1361 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001362 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001363 // If we can't stat the file we're remapping to, assume that something
1364 // horrible happened.
1365 AnyFileChanged = true;
1366 break;
1367 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001368
Douglas Gregor0e119552010-07-31 00:40:00 +00001369 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1370 StatBuf.st_mtime);
1371 }
1372 for (PreprocessorOptions::remapped_file_buffer_iterator
1373 R = PreprocessorOpts.remapped_file_buffer_begin(),
1374 REnd = PreprocessorOpts.remapped_file_buffer_end();
1375 !AnyFileChanged && R != REnd;
1376 ++R) {
1377 // FIXME: Should we actually compare the contents of file->buffer
1378 // remappings?
1379 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1380 0);
1381 }
1382
1383 // Check whether anything has changed.
1384 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1385 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1386 !AnyFileChanged && F != FEnd;
1387 ++F) {
1388 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1389 = OverriddenFiles.find(F->first());
1390 if (Overridden != OverriddenFiles.end()) {
1391 // This file was remapped; check whether the newly-mapped file
1392 // matches up with the previous mapping.
1393 if (Overridden->second != F->second)
1394 AnyFileChanged = true;
1395 continue;
1396 }
1397
1398 // The file was not remapped; check whether it has changed on disk.
1399 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001400 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001401 // If we can't stat the file, assume that something horrible happened.
1402 AnyFileChanged = true;
1403 } else if (StatBuf.st_size != F->second.first ||
1404 StatBuf.st_mtime != F->second.second)
1405 AnyFileChanged = true;
1406 }
1407
1408 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001409 // Okay! We can re-use the precompiled preamble.
1410
1411 // Set the state of the diagnostic object to mimic its state
1412 // after parsing the preamble.
1413 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001414 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001415 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001416 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001417
1418 // Create a version of the main file buffer that is padded to
1419 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001420 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001421 PreambleReservedSize,
Douglas Gregor32fbe312012-01-20 16:28:04 +00001422 FrontendOpts.Inputs[0].File);
Douglas Gregor0e119552010-07-31 00:40:00 +00001423 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001424 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001425
1426 // If we aren't allowed to rebuild the precompiled preamble, just
1427 // return now.
1428 if (!AllowRebuild)
1429 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001430
Douglas Gregor4dde7492010-07-23 23:58:40 +00001431 // We can't reuse the previously-computed preamble. Build a new one.
1432 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001433 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001434 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001435 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001436 } else if (!AllowRebuild) {
1437 // We aren't allowed to rebuild the precompiled preamble; just
1438 // return now.
1439 return 0;
1440 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001441
1442 // If the preamble rebuild counter > 1, it's because we previously
1443 // failed to build a preamble and we're not yet ready to try
1444 // again. Decrement the counter and return a failure.
1445 if (PreambleRebuildCounter > 1) {
1446 --PreambleRebuildCounter;
1447 return 0;
1448 }
1449
Douglas Gregore10f0e52010-09-11 17:56:52 +00001450 // Create a temporary file for the precompiled preamble. In rare
1451 // circumstances, this can fail.
1452 std::string PreamblePCHPath = GetPreamblePCHPath();
1453 if (PreamblePCHPath.empty()) {
1454 // Try again next time.
1455 PreambleRebuildCounter = 1;
1456 return 0;
1457 }
1458
Douglas Gregor4dde7492010-07-23 23:58:40 +00001459 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001460 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001461 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001462
1463 // Create a new buffer that stores the preamble. The buffer also contains
1464 // extra space for the original contents of the file (which will be present
1465 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001466 // grows.
1467 PreambleReservedSize = NewPreamble.first->getBufferSize();
1468 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001469 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001470 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001471 PreambleReservedSize *= 2;
1472
Douglas Gregord9a30af2010-08-02 20:51:39 +00001473 // Save the preamble text for later; we'll need to compare against it for
1474 // subsequent reparses.
Douglas Gregor32fbe312012-01-20 16:28:04 +00001475 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001476 Preamble.assign(FileMgr->getFile(MainFilename),
1477 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001478 NewPreamble.first->getBufferStart()
1479 + NewPreamble.second.first);
1480 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1481
Douglas Gregora0734c52010-08-19 01:33:06 +00001482 delete PreambleBuffer;
1483 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001484 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor32fbe312012-01-20 16:28:04 +00001485 FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001486 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001487 NewPreamble.first->getBufferStart(), Preamble.size());
1488 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001489 ' ', PreambleReservedSize - Preamble.size() - 1);
1490 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001491
1492 // Remap the main source file to the preamble buffer.
Douglas Gregor32fbe312012-01-20 16:28:04 +00001493 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001494 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1495
1496 // Tell the compiler invocation to generate a temporary precompiled header.
1497 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001498 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001499 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001500 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1501 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001502
1503 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001504 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001505
1506 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001507 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1508 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001509
Douglas Gregor3cc15812011-07-01 18:22:13 +00001510 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor32fbe312012-01-20 16:28:04 +00001511 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001512
Douglas Gregor8e984da2010-08-04 16:47:14 +00001513 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001514 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001515
1516 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001517 Clang->getTargetOpts().Features = TargetFeatures;
1518 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1519 Clang->getTargetOpts()));
1520 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001521 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1522 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001523 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001524 PreprocessorOpts.eraseRemappedFile(
1525 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001526 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001527 }
1528
1529 // Inform the target of the language options.
1530 //
1531 // FIXME: We shouldn't need to do this, the target should be immutable once
1532 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001533 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001534
Ted Kremenek84de4a12011-03-21 18:40:07 +00001535 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001536 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001537 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001538 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001539 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001540 "IR inputs not support here!");
1541
1542 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001543 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001544 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001545 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001546 TopLevelDecls.clear();
1547 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001548
1549 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001550 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001551
1552 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001553 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001554 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001555
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001556 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001557 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001558 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001559 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1560 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001561 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001562 PreprocessorOpts.eraseRemappedFile(
1563 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001564 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001565 }
1566
1567 Act->Execute();
1568 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001569
Douglas Gregore9db88f2010-08-03 19:06:41 +00001570 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001571 // There were errors parsing the preamble, so no precompiled header was
1572 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001573 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001574 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1575 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001576 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001577 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001578 PreprocessorOpts.eraseRemappedFile(
1579 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001580 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001581 }
1582
Douglas Gregor925296b2011-07-19 16:10:42 +00001583 // Transfer any diagnostics generated when parsing the preamble into the set
1584 // of preamble diagnostics.
1585 PreambleDiagnostics.clear();
1586 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001587 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001588 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001589
Douglas Gregor4dde7492010-07-23 23:58:40 +00001590 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001591 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001592 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001593
1594 // Keep track of all of the files that the source manager knows about,
1595 // so we can verify whether they have changed or not.
1596 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001597 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001598 const llvm::MemoryBuffer *MainFileBuffer
1599 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1600 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1601 FEnd = SourceMgr.fileinfo_end();
1602 F != FEnd;
1603 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001604 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001605 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1606 continue;
1607
1608 FilesInPreamble[File->getName()]
1609 = std::make_pair(F->second->getSize(), File->getModificationTime());
1610 }
1611
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001612 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001613 PreprocessorOpts.eraseRemappedFile(
1614 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001615
1616 // If the hash of top-level entities differs from the hash of the top-level
1617 // entities the last time we rebuilt the preamble, clear out the completion
1618 // cache.
1619 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1620 CompletionCacheTopLevelHashValue = 0;
1621 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1622 }
1623
Douglas Gregor6481ef12010-07-24 00:38:13 +00001624 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001625 PreambleReservedSize,
Douglas Gregor32fbe312012-01-20 16:28:04 +00001626 FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001627}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001628
Douglas Gregore9db88f2010-08-03 19:06:41 +00001629void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1630 std::vector<Decl *> Resolved;
1631 Resolved.reserve(TopLevelDeclsInPreamble.size());
1632 ExternalASTSource &Source = *getASTContext().getExternalSource();
1633 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1634 // Resolve the declaration ID to an actual declaration, possibly
1635 // deserializing the declaration in the process.
1636 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1637 if (D)
1638 Resolved.push_back(D);
1639 }
1640 TopLevelDeclsInPreamble.clear();
1641 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1642}
1643
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001644void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1645 // Steal the created target, context, and preprocessor.
1646 TheSema.reset(CI.takeSema());
1647 Consumer.reset(CI.takeASTConsumer());
1648 Ctx = &CI.getASTContext();
1649 PP = &CI.getPreprocessor();
1650 CI.setSourceManager(0);
1651 CI.setFileManager(0);
1652 Target = &CI.getTarget();
1653 Reader = CI.getModuleManager();
1654}
1655
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001656StringRef ASTUnit::getMainFileName() const {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001657 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor16896c42010-10-28 15:44:59 +00001658}
1659
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001660ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001661 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001662 bool CaptureDiagnostics) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001663 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001664 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001665 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001666 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001667 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001668 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001669 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001670 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001671
1672 return AST.take();
1673}
1674
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001675ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001676 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001677 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001678 ASTUnit *Unit,
1679 bool Persistent,
1680 StringRef ResourceFilesPath,
1681 bool OnlyLocalDecls,
1682 bool CaptureDiagnostics,
1683 bool PrecompilePreamble,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001684 bool CacheCodeCompletionResults,
1685 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001686 assert(CI && "A CompilerInvocation is required");
1687
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001688 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001689 ASTUnit *AST = Unit;
1690 if (!AST) {
1691 // Create the AST unit.
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001692 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001693 AST = OwnAST.get();
1694 }
1695
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001696 if (!ResourceFilesPath.empty()) {
1697 // Override the resources path.
1698 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1699 }
1700 AST->OnlyLocalDecls = OnlyLocalDecls;
1701 AST->CaptureDiagnostics = CaptureDiagnostics;
1702 if (PrecompilePreamble)
1703 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001704 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001705 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001706
1707 // Recover resources if we crash before exiting this method.
1708 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001709 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001710 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1711 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001712 DiagCleanup(Diags.getPtr());
1713
1714 // We'll manage file buffers ourselves.
1715 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1716 CI->getFrontendOpts().DisableFree = false;
1717 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1718
1719 // Save the target features.
1720 AST->TargetFeatures = CI->getTargetOpts().Features;
1721
1722 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001723 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001724
1725 // Recover resources if we crash before exiting this method.
1726 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1727 CICleanup(Clang.get());
1728
1729 Clang->setInvocation(CI);
Douglas Gregor32fbe312012-01-20 16:28:04 +00001730 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001731
1732 // Set up diagnostics, capturing any diagnostics that would
1733 // otherwise be dropped.
1734 Clang->setDiagnostics(&AST->getDiagnostics());
1735
1736 // Create the target instance.
1737 Clang->getTargetOpts().Features = AST->TargetFeatures;
1738 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1739 Clang->getTargetOpts()));
1740 if (!Clang->hasTarget())
1741 return 0;
1742
1743 // Inform the target of the language options.
1744 //
1745 // FIXME: We shouldn't need to do this, the target should be immutable once
1746 // created. This complexity should be lifted elsewhere.
1747 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1748
1749 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1750 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001751 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001752 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001753 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001754 "IR inputs not supported here!");
1755
1756 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001757 AST->TheSema.reset();
1758 AST->Ctx = 0;
1759 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001760 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001761
1762 // Create a file manager object to provide access to and cache the filesystem.
1763 Clang->setFileManager(&AST->getFileManager());
1764
1765 // Create the source manager.
1766 Clang->setSourceManager(&AST->getSourceManager());
1767
1768 ASTFrontendAction *Act = Action;
1769
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001770 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001771 if (!Act) {
1772 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1773 Act = TrackerAct.get();
1774 }
1775
1776 // Recover resources if we crash before exiting this method.
1777 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1778 ActCleanup(TrackerAct.get());
1779
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001780 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1781 AST->transferASTDataFromCompilerInstance(*Clang);
1782 if (OwnAST && ErrAST)
1783 ErrAST->swap(OwnAST);
1784
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001785 return 0;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001786 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001787
1788 if (Persistent && !TrackerAct) {
1789 Clang->getPreprocessor().addPPCallbacks(
1790 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1791 std::vector<ASTConsumer*> Consumers;
1792 if (Clang->hasASTConsumer())
1793 Consumers.push_back(Clang->takeASTConsumer());
1794 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1795 AST->getCurrentTopLevelHashValue()));
1796 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1797 }
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001798 Act->Execute();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001799
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001800 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001801 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001802
1803 Act->EndSourceFile();
1804
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001805 if (OwnAST)
1806 return OwnAST.take();
1807 else
1808 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001809}
1810
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001811bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1812 if (!Invocation)
1813 return true;
1814
1815 // We'll manage file buffers ourselves.
1816 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1817 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001818 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001819
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001820 // Save the target features.
1821 TargetFeatures = Invocation->getTargetOpts().Features;
1822
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001823 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001824 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001825 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001826 OverrideMainBuffer
1827 = getMainBufferWithPrecompiledPreamble(*Invocation);
1828 }
1829
Douglas Gregor16896c42010-10-28 15:44:59 +00001830 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001831 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001832
Ted Kremenek022a4902011-03-22 01:15:24 +00001833 // Recover resources if we crash before exiting this method.
1834 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1835 MemBufferCleanup(OverrideMainBuffer);
1836
Douglas Gregor16896c42010-10-28 15:44:59 +00001837 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001838}
1839
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001840ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001841 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001842 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001843 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001844 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001845 TranslationUnitKind TUKind,
Argyrios Kyrtzidis335c5a42012-02-25 02:41:16 +00001846 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001847 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001848 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001849 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001850 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001851 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001852 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001853 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001854 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001855 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001856 AST->Invocation = CI;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001857
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001858 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001859 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1860 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001861 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1862 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001863 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001864
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001865 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001866}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001867
1868ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1869 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001870 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001871 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001872 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001873 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001874 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001875 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001876 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001877 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001878 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001879 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001880 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6e922512012-04-12 10:11:59 +00001881 bool SkipFunctionBodies,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001882 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001883 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001884 // No diagnostics engine was provided, so create our own diagnostics object
1885 // with the default options.
1886 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001887 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1888 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001889 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001890
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001891 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001892
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001893 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001894
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001895 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001896
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001897 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001898 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001899
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001900 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001901 llvm::makeArrayRef(ArgBegin, ArgEnd),
1902 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001903 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001904 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001905 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001906
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001907 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001908 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1909 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1910 if (const llvm::MemoryBuffer *
1911 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1912 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1913 } else {
1914 const char *fname = fileOrBuf.get<const char *>();
1915 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1916 }
1917 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001918 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1919 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1920 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001921
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001922 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001923 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001924
Erik Verbruggen6e922512012-04-12 10:11:59 +00001925 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1926
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001927 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001928 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001929 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001930 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001931 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00001932 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001933 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001934 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001935 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001936 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001937 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001938 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1939 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001940 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001941 AST->Invocation = CI;
Ted Kremenek25047602011-11-17 23:01:17 +00001942 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001943
1944 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001945 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1946 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001947
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001948 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1949 // Some error occurred, if caller wants to examine diagnostics, pass it the
1950 // ASTUnit.
1951 if (ErrAST) {
1952 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1953 ErrAST->swap(AST);
1954 }
1955 return 0;
1956 }
1957
1958 return AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001959}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001960
1961bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001962 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001963 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001964
1965 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001966
Douglas Gregor16896c42010-10-28 15:44:59 +00001967 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001968 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001969
Douglas Gregor0e119552010-07-31 00:40:00 +00001970 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001971 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001972 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001973 for (PreprocessorOptions::remapped_file_buffer_iterator
1974 R = PPOpts.remapped_file_buffer_begin(),
1975 REnd = PPOpts.remapped_file_buffer_end();
1976 R != REnd;
1977 ++R) {
1978 delete R->second;
1979 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001980 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001981 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1982 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1983 if (const llvm::MemoryBuffer *
1984 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1985 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1986 memBuf);
1987 } else {
1988 const char *fname = fileOrBuf.get<const char *>();
1989 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1990 fname);
1991 }
1992 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001993
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001994 // If we have a preamble file lying around, or if we might try to
1995 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001996 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001997 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001998 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001999
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002000 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002001 getDiagnostics().Reset();
2002 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002003 if (OverrideMainBuffer)
2004 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002005
Douglas Gregor4dde7492010-07-23 23:58:40 +00002006 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002007 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002008
2009 // If we're caching global code-completion results, and the top-level
2010 // declarations have changed, clear out the code-completion cache.
2011 if (!Result && ShouldCacheCodeCompletionResults &&
2012 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2013 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002014
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002015 // We now need to clear out the completion info related to this translation
2016 // unit; it'll be recreated if necessary.
2017 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002018
Douglas Gregor4dde7492010-07-23 23:58:40 +00002019 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002020}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002021
Douglas Gregorb14904c2010-08-13 22:48:40 +00002022//----------------------------------------------------------------------------//
2023// Code completion
2024//----------------------------------------------------------------------------//
2025
2026namespace {
2027 /// \brief Code completion consumer that combines the cached code-completion
2028 /// results from an ASTUnit with the code-completion results provided to it,
2029 /// then passes the result on to
2030 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00002031 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002032 ASTUnit &AST;
2033 CodeCompleteConsumer &Next;
2034
2035 public:
2036 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00002037 bool IncludeMacros, bool IncludeCodePatterns,
2038 bool IncludeGlobals)
2039 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00002040 Next.isOutputBinary()), AST(AST), Next(Next)
2041 {
2042 // Compute the set of contexts in which we will look when we don't have
2043 // any information about the specific context.
2044 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00002045 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2046 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2047 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2048 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2049 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2050 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2051 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2052 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2053 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2054 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2055 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2056 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2057 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00002058
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (AST.getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00002060 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2061 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2062 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00002063 }
2064
2065 virtual void ProcessCodeCompleteResults(Sema &S,
2066 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002067 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002068 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002069
2070 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2071 OverloadCandidate *Candidates,
2072 unsigned NumCandidates) {
2073 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2074 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002075
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002076 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002077 return Next.getAllocator();
2078 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002079
2080 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2081 return Next.getCodeCompletionTUInfo();
2082 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002083 };
2084}
Douglas Gregord46cf182010-08-16 20:01:48 +00002085
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002086/// \brief Helper function that computes which global names are hidden by the
2087/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002088static void CalculateHiddenNames(const CodeCompletionContext &Context,
2089 CodeCompletionResult *Results,
2090 unsigned NumResults,
2091 ASTContext &Ctx,
2092 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002093 bool OnlyTagNames = false;
2094 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002095 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002096 case CodeCompletionContext::CCC_TopLevel:
2097 case CodeCompletionContext::CCC_ObjCInterface:
2098 case CodeCompletionContext::CCC_ObjCImplementation:
2099 case CodeCompletionContext::CCC_ObjCIvarList:
2100 case CodeCompletionContext::CCC_ClassStructUnion:
2101 case CodeCompletionContext::CCC_Statement:
2102 case CodeCompletionContext::CCC_Expression:
2103 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002104 case CodeCompletionContext::CCC_DotMemberAccess:
2105 case CodeCompletionContext::CCC_ArrowMemberAccess:
2106 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002107 case CodeCompletionContext::CCC_Namespace:
2108 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002109 case CodeCompletionContext::CCC_Name:
2110 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002111 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002112 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002113 break;
2114
2115 case CodeCompletionContext::CCC_EnumTag:
2116 case CodeCompletionContext::CCC_UnionTag:
2117 case CodeCompletionContext::CCC_ClassOrStructTag:
2118 OnlyTagNames = true;
2119 break;
2120
2121 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002122 case CodeCompletionContext::CCC_MacroName:
2123 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002124 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002125 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002126 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002127 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002128 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002129 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002130 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002131 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2132 case CodeCompletionContext::CCC_ObjCClassMessage:
2133 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002134 // We're looking for nothing, or we're looking for names that cannot
2135 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002136 return;
2137 }
2138
John McCall276321a2010-08-25 06:19:51 +00002139 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002140 for (unsigned I = 0; I != NumResults; ++I) {
2141 if (Results[I].Kind != Result::RK_Declaration)
2142 continue;
2143
2144 unsigned IDNS
2145 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2146
2147 bool Hiding = false;
2148 if (OnlyTagNames)
2149 Hiding = (IDNS & Decl::IDNS_Tag);
2150 else {
2151 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002152 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2153 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002154 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002155 HiddenIDNS |= Decl::IDNS_Tag;
2156 Hiding = (IDNS & HiddenIDNS);
2157 }
2158
2159 if (!Hiding)
2160 continue;
2161
2162 DeclarationName Name = Results[I].Declaration->getDeclName();
2163 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2164 HiddenNames.insert(Identifier->getName());
2165 else
2166 HiddenNames.insert(Name.getAsString());
2167 }
2168}
2169
2170
Douglas Gregord46cf182010-08-16 20:01:48 +00002171void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2172 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002173 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002174 unsigned NumResults) {
2175 // Merge the results we were given with the results we cached.
2176 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002177 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00002178 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi203f87c2011-08-17 01:46:16 +00002179 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002180 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002181 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002182 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002183 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002184 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002185 C = AST.cached_completion_begin(),
2186 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002187 C != CEnd; ++C) {
2188 // If the context we are in matches any of the contexts we are
2189 // interested in, we'll add this result.
2190 if ((C->ShowInContexts & InContexts) == 0)
2191 continue;
2192
2193 // If we haven't added any results previously, do so now.
2194 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002195 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2196 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002197 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2198 AddedResult = true;
2199 }
2200
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002201 // Determine whether this global completion result is hidden by a local
2202 // completion result. If so, skip it.
2203 if (C->Kind != CXCursor_MacroDefinition &&
2204 HiddenNames.count(C->Completion->getTypedText()))
2205 continue;
2206
Douglas Gregord46cf182010-08-16 20:01:48 +00002207 // Adjust priority based on similar type classes.
2208 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002209 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002210 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002211 if (!Context.getPreferredType().isNull()) {
2212 if (C->Kind == CXCursor_MacroDefinition) {
2213 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002214 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002215 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002216 } else if (C->Type) {
2217 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002218 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002219 Context.getPreferredType().getUnqualifiedType());
2220 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2221 if (ExpectedSTC == C->TypeClass) {
2222 // We know this type is similar; check for an exact match.
2223 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002224 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002225 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002226 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002227 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2228 Priority /= CCF_ExactTypeMatch;
2229 else
2230 Priority /= CCF_SimilarTypeMatch;
2231 }
2232 }
2233 }
2234
Douglas Gregor12785102010-08-24 20:21:13 +00002235 // Adjust the completion string, if required.
2236 if (C->Kind == CXCursor_MacroDefinition &&
2237 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2238 // Create a new code-completion string that just contains the
2239 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002240 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2241 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002242 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002243 CursorKind = CXCursor_NotImplemented;
2244 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002245 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002246 }
2247
Douglas Gregor8850aa32010-08-25 18:03:13 +00002248 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002249 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002250 }
2251
2252 // If we did not add any cached completion results, just forward the
2253 // results we were given to the next consumer.
2254 if (!AddedResult) {
2255 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2256 return;
2257 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002258
Douglas Gregord46cf182010-08-16 20:01:48 +00002259 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2260 AllResults.size());
2261}
2262
2263
2264
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002265void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002266 RemappedFile *RemappedFiles,
2267 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002268 bool IncludeMacros,
2269 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002270 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002271 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002272 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002273 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2274 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002275 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002276 return;
2277
Douglas Gregor16896c42010-10-28 15:44:59 +00002278 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002279 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002280 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002281
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002282 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002283 CCInvocation(new CompilerInvocation(*Invocation));
2284
2285 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2286 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002287
Douglas Gregorb14904c2010-08-13 22:48:40 +00002288 FrontendOpts.ShowMacrosInCodeCompletion
2289 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002290 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002291 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2292 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002293 FrontendOpts.CodeCompletionAt.FileName = File;
2294 FrontendOpts.CodeCompletionAt.Line = Line;
2295 FrontendOpts.CodeCompletionAt.Column = Column;
2296
2297 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002298 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002299
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002300 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002301
2302 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002303 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2304 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002305
Ted Kremenek5e14d392011-03-21 18:40:17 +00002306 Clang->setInvocation(&*CCInvocation);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002307 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002308
2309 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002310 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002311 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002312 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002313 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002314 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002315
2316 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002317 Clang->getTargetOpts().Features = TargetFeatures;
2318 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2319 Clang->getTargetOpts()));
2320 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002321 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002322 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002323 }
2324
2325 // Inform the target of the language options.
2326 //
2327 // FIXME: We shouldn't need to do this, the target should be immutable once
2328 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002329 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002330
Ted Kremenek84de4a12011-03-21 18:40:07 +00002331 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002332 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00002333 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002334 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00002335 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002336 "IR inputs not support here!");
2337
2338
2339 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002340 Clang->setFileManager(&FileMgr);
2341 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002342
2343 // Remap files.
2344 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002345 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002346 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002347 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2348 if (const llvm::MemoryBuffer *
2349 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2350 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2351 OwnedBuffers.push_back(memBuf);
2352 } else {
2353 const char *fname = fileOrBuf.get<const char *>();
2354 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2355 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002356 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002357
Douglas Gregorb14904c2010-08-13 22:48:40 +00002358 // Use the code completion consumer we were given, but adding any cached
2359 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002360 AugmentedCodeCompleteConsumer *AugmentedConsumer
2361 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2362 FrontendOpts.ShowMacrosInCodeCompletion,
2363 FrontendOpts.ShowCodePatternsInCodeCompletion,
2364 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002365 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002366
Erik Verbruggen6e922512012-04-12 10:11:59 +00002367 Clang->getFrontendOpts().SkipFunctionBodies = true;
2368
Douglas Gregor028d3e42010-08-09 20:45:32 +00002369 // If we have a precompiled preamble, try to use it. We only allow
2370 // the use of the precompiled preamble if we're if the completion
2371 // point is within the main file, after the end of the precompiled
2372 // preamble.
2373 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002374 if (!getPreambleFile(this).empty()) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002375 using llvm::sys::FileStatus;
2376 llvm::sys::PathWithStatus CompleteFilePath(File);
2377 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2378 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2379 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +00002380 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2381 Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002382 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002383 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002384 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002385 }
2386
2387 // If the main file has been overridden due to the use of a preamble,
2388 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002389 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002390 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00002391 stored_diag_begin(),
2392 stored_diag_afterDriver_begin());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002393 if (OverrideMainBuffer) {
2394 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2395 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2396 PreprocessorOpts.PrecompiledPreambleBytes.second
2397 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002398 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002399 PreprocessorOpts.DisablePCHValidation = true;
2400
Douglas Gregorb97b6662010-08-20 00:59:43 +00002401 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002402 } else {
2403 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2404 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002405 }
2406
Douglas Gregor998caea2011-05-06 16:33:08 +00002407 // Disable the preprocessing record
2408 PreprocessorOpts.DetailedRecord = false;
2409
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002410 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002411 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002412 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002413 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00002414 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00002415 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2416 getSourceManager(), PreambleDiagnostics,
2417 StoredDiagnostics);
2418 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002419 Act->Execute();
2420 Act->EndSourceFile();
2421 }
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00002422
2423 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002424}
Douglas Gregore9386682010-08-13 05:36:37 +00002425
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002426CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002427 // Write to a temporary file and later rename it to the actual file, to avoid
2428 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002429 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002430 TempPath = File;
2431 TempPath += "-%%%%%%%%";
2432 int fd;
2433 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2434 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002435 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002436
Douglas Gregore9386682010-08-13 05:36:37 +00002437 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2438 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002439 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002440
2441 serialize(Out);
2442 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002443 if (Out.has_error()) {
2444 Out.clear_error();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002445 return CXSaveError_Unknown;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002446 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002447
Rafael Espindola65e025c2011-12-25 01:18:52 +00002448 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002449 bool exists;
2450 llvm::sys::fs::remove(TempPath.str(), exists);
2451 return CXSaveError_Unknown;
2452 }
2453
2454 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002455}
2456
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002457bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002458 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002459
Daniel Dunbar9a963862012-02-29 20:31:23 +00002460 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002461 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002462 ASTWriter Writer(Stream);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002463 // FIXME: Handle modules
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002464 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregore9386682010-08-13 05:36:37 +00002465
2466 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002467 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002468 OS.write((char *)&Buffer.front(), Buffer.size());
2469
2470 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002471}
Douglas Gregor925296b2011-07-19 16:10:42 +00002472
2473typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2474
2475static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2476 unsigned Raw = L.getRawEncoding();
2477 const unsigned MacroBit = 1U << 31;
2478 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2479 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2480}
2481
2482void ASTUnit::TranslateStoredDiagnostics(
2483 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002484 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002485 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002486 const SmallVectorImpl<StoredDiagnostic> &Diags,
2487 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002488 // The stored diagnostic has the old source manager in it; update
2489 // the locations to refer into the new source manager. We also need to remap
2490 // all the locations to the new view. This includes the diag location, any
2491 // associated source ranges, and the source ranges of associated fix-its.
2492 // FIXME: There should be a cleaner way to do this.
2493
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002494 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002495 Result.reserve(Diags.size());
2496 assert(MMan && "Don't have a module manager");
Douglas Gregorde3ef502011-11-30 23:21:26 +00002497 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002498 assert(Mod && "Don't have preamble module");
2499 SLocRemap &Remap = Mod->SLocRemap;
2500 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2501 // Rebuild the StoredDiagnostic.
2502 const StoredDiagnostic &SD = Diags[I];
2503 SourceLocation L = SD.getLocation();
2504 TranslateSLoc(L, Remap);
2505 FullSourceLoc Loc(L, SrcMgr);
2506
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002507 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002508 Ranges.reserve(SD.range_size());
2509 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2510 E = SD.range_end();
2511 I != E; ++I) {
2512 SourceLocation BL = I->getBegin();
2513 TranslateSLoc(BL, Remap);
2514 SourceLocation EL = I->getEnd();
2515 TranslateSLoc(EL, Remap);
2516 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2517 }
2518
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002519 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002520 FixIts.reserve(SD.fixit_size());
2521 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2522 E = SD.fixit_end();
2523 I != E; ++I) {
2524 FixIts.push_back(FixItHint());
2525 FixItHint &FH = FixIts.back();
2526 FH.CodeToInsert = I->CodeToInsert;
2527 SourceLocation BL = I->RemoveRange.getBegin();
2528 TranslateSLoc(BL, Remap);
2529 SourceLocation EL = I->RemoveRange.getEnd();
2530 TranslateSLoc(EL, Remap);
2531 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2532 I->RemoveRange.isTokenRange());
2533 }
2534
2535 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2536 SD.getMessage(), Loc, Ranges, FixIts));
2537 }
2538 Result.swap(Out);
2539}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002540
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002541static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2542 std::pair<unsigned, Decl *> R) {
2543 return L.first < R.first;
2544}
2545
2546void ASTUnit::addFileLevelDecl(Decl *D) {
2547 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002548
2549 // We only care about local declarations.
2550 if (D->isFromASTFile())
2551 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002552
2553 SourceManager &SM = *SourceMgr;
2554 SourceLocation Loc = D->getLocation();
2555 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2556 return;
2557
2558 // We only keep track of the file-level declarations of each file.
2559 if (!D->getLexicalDeclContext()->isFileContext())
2560 return;
2561
2562 SourceLocation FileLoc = SM.getFileLoc(Loc);
2563 assert(SM.isLocalSourceLocation(FileLoc));
2564 FileID FID;
2565 unsigned Offset;
2566 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2567 if (FID.isInvalid())
2568 return;
2569
2570 LocDeclsTy *&Decls = FileDecls[FID];
2571 if (!Decls)
2572 Decls = new LocDeclsTy();
2573
2574 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2575
2576 if (Decls->empty() || Decls->back().first <= Offset) {
2577 Decls->push_back(LocDecl);
2578 return;
2579 }
2580
2581 LocDeclsTy::iterator
2582 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2583
2584 Decls->insert(I, LocDecl);
2585}
2586
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002587void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2588 SmallVectorImpl<Decl *> &Decls) {
2589 if (File.isInvalid())
2590 return;
2591
2592 if (SourceMgr->isLoadedFileID(File)) {
2593 assert(Ctx->getExternalSource() && "No external source!");
2594 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2595 Decls);
2596 }
2597
2598 FileDeclsTy::iterator I = FileDecls.find(File);
2599 if (I == FileDecls.end())
2600 return;
2601
2602 LocDeclsTy &LocDecls = *I->second;
2603 if (LocDecls.empty())
2604 return;
2605
2606 LocDeclsTy::iterator
2607 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2608 std::make_pair(Offset, (Decl*)0), compLocDecl);
2609 if (BeginIt != LocDecls.begin())
2610 --BeginIt;
2611
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002612 // If we are pointing at a top-level decl inside an objc container, we need
2613 // to backtrack until we find it otherwise we will fail to report that the
2614 // region overlaps with an objc container.
2615 while (BeginIt != LocDecls.begin() &&
2616 BeginIt->second->isTopLevelDeclInObjCContainer())
2617 --BeginIt;
2618
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002619 LocDeclsTy::iterator
2620 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2621 std::make_pair(Offset+Length, (Decl*)0),
2622 compLocDecl);
2623 if (EndIt != LocDecls.end())
2624 ++EndIt;
2625
2626 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2627 Decls.push_back(DIt->second);
2628}
2629
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002630SourceLocation ASTUnit::getLocation(const FileEntry *File,
2631 unsigned Line, unsigned Col) const {
2632 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002633 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002634 return SM.getMacroArgExpandedLocation(Loc);
2635}
2636
2637SourceLocation ASTUnit::getLocation(const FileEntry *File,
2638 unsigned Offset) const {
2639 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002640 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002641 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2642}
2643
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002644/// \brief If \arg Loc is a loaded location from the preamble, returns
2645/// the corresponding local location of the main file, otherwise it returns
2646/// \arg Loc.
2647SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2648 FileID PreambleID;
2649 if (SourceMgr)
2650 PreambleID = SourceMgr->getPreambleFileID();
2651
2652 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2653 return Loc;
2654
2655 unsigned Offs;
2656 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2657 SourceLocation FileLoc
2658 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2659 return FileLoc.getLocWithOffset(Offs);
2660 }
2661
2662 return Loc;
2663}
2664
2665/// \brief If \arg Loc is a local location of the main file but inside the
2666/// preamble chunk, returns the corresponding loaded location from the
2667/// preamble, otherwise it returns \arg Loc.
2668SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2669 FileID PreambleID;
2670 if (SourceMgr)
2671 PreambleID = SourceMgr->getPreambleFileID();
2672
2673 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2674 return Loc;
2675
2676 unsigned Offs;
2677 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2678 Offs < Preamble.size()) {
2679 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2680 return FileLoc.getLocWithOffset(Offs);
2681 }
2682
2683 return Loc;
2684}
2685
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002686bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2687 FileID FID;
2688 if (SourceMgr)
2689 FID = SourceMgr->getPreambleFileID();
2690
2691 if (Loc.isInvalid() || FID.isInvalid())
2692 return false;
2693
2694 return SourceMgr->isInFileID(Loc, FID);
2695}
2696
2697bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2698 FileID FID;
2699 if (SourceMgr)
2700 FID = SourceMgr->getMainFileID();
2701
2702 if (Loc.isInvalid() || FID.isInvalid())
2703 return false;
2704
2705 return SourceMgr->isInFileID(Loc, FID);
2706}
2707
2708SourceLocation ASTUnit::getEndOfPreambleFileID() {
2709 FileID FID;
2710 if (SourceMgr)
2711 FID = SourceMgr->getPreambleFileID();
2712
2713 if (FID.isInvalid())
2714 return SourceLocation();
2715
2716 return SourceMgr->getLocForEndOfFile(FID);
2717}
2718
2719SourceLocation ASTUnit::getStartOfMainFileID() {
2720 FileID FID;
2721 if (SourceMgr)
2722 FID = SourceMgr->getMainFileID();
2723
2724 if (FID.isInvalid())
2725 return SourceLocation();
2726
2727 return SourceMgr->getLocForStartOfFile(FID);
2728}
2729
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002730void ASTUnit::PreambleData::countLines() const {
2731 NumLines = 0;
2732 if (empty())
2733 return;
2734
2735 for (std::vector<char>::const_iterator
2736 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2737 if (*I == '\n')
2738 ++NumLines;
2739 }
2740 if (Buffer.back() != '\n')
2741 ++NumLines;
2742}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002743
2744#ifndef NDEBUG
2745ASTUnit::ConcurrencyState::ConcurrencyState() {
2746 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2747}
2748
2749ASTUnit::ConcurrencyState::~ConcurrencyState() {
2750 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2751}
2752
2753void ASTUnit::ConcurrencyState::start() {
2754 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2755 assert(acquired && "Concurrent access to ASTUnit!");
2756}
2757
2758void ASTUnit::ConcurrencyState::finish() {
2759 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2760}
2761
2762#else // NDEBUG
2763
2764ASTUnit::ConcurrencyState::ConcurrencyState() {}
2765ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2766void ASTUnit::ConcurrencyState::start() {}
2767void ASTUnit::ConcurrencyState::finish() {}
2768
2769#endif