blob: 3eb418c39b354d34b68d44fb80559f478ad7a3d0 [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 Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Douglas Gregorf88e35b2010-11-30 06:16:57 +000032#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000039#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000040#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000041#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000046#include "llvm/Support/Timer.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000047#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000048#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000049#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000050#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000067 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
82}
83
Douglas Gregorbb420ab2010-08-04 05:53:38 +000084/// \brief After failing to build a precompiled preamble (due to
85/// errors in the source that occurs in the preamble), the number of
86/// reparses during which we'll skip even trying to precompile the
87/// preamble.
88const unsigned DefaultPreambleRebuildInterval = 5;
89
Douglas Gregor68dbaea2010-11-17 00:13:31 +000090/// \brief Tracks the number of ASTUnit objects that are currently active.
91///
92/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000093static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +000094
Douglas Gregord03e8232010-04-05 21:10:19 +000095ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +000096 : OnlyLocalDecls(false), CaptureDiagnostics(false),
97 MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000098 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +000099 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000100 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000101 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +0000102 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000103 ShouldCacheCodeCompletionResults(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000104 CompletionCacheTopLevelHashValue(0),
105 PreambleTopLevelHashValue(0),
106 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000107 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000108 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000109 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000110 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
111 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000112}
Douglas Gregord03e8232010-04-05 21:10:19 +0000113
Daniel Dunbar764c0822009-12-01 09:51:01 +0000114ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000115 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000116 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000117 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000118 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000119
120 // Free the buffers associated with remapped files. We are required to
121 // perform this operation here because we explicitly request that the
122 // compiler instance *not* free these buffers for each invocation of the
123 // parser.
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000124 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000125 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
126 for (PreprocessorOptions::remapped_file_buffer_iterator
127 FB = PPOpts.remapped_file_buffer_begin(),
128 FBEnd = PPOpts.remapped_file_buffer_end();
129 FB != FBEnd;
130 ++FB)
131 delete FB->second;
132 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000133
134 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000135 delete PreambleBuffer;
136
Douglas Gregor16896c42010-10-28 15:44:59 +0000137 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000138
139 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000140 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000141 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
142 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000143}
144
145void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000146 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
147 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000148 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000149}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000150
Douglas Gregor39982192010-08-15 06:18:01 +0000151/// \brief Determine the set of code-completion contexts in which this
152/// declaration should be shown.
153static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000154 const LangOptions &LangOpts,
155 bool &IsNestedNameSpecifier) {
156 IsNestedNameSpecifier = false;
157
Douglas Gregor39982192010-08-15 06:18:01 +0000158 if (isa<UsingShadowDecl>(ND))
159 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
160 if (!ND)
161 return 0;
162
163 unsigned Contexts = 0;
164 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
165 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
166 // Types can appear in these contexts.
167 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
168 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
169 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
170 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
171 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000172 | (1 << (CodeCompletionContext::CCC_Type - 1))
173 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000174
175 // In C++, types can appear in expressions contexts (for functional casts).
176 if (LangOpts.CPlusPlus)
177 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
178
179 // In Objective-C, message sends can send interfaces. In Objective-C++,
180 // all types are available due to functional casts.
181 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
182 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
183
184 // Deal with tag names.
185 if (isa<EnumDecl>(ND)) {
186 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
187
Douglas Gregor59cab552010-08-16 23:05:20 +0000188 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000189 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000190 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000191 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
192 if (Record->isUnion())
193 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
194 else
195 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
196
Douglas Gregor39982192010-08-15 06:18:01 +0000197 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000198 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000199 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000200 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000201 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
202 // Values can appear in these contexts.
203 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
204 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000205 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000206 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
207 } else if (isa<ObjCProtocolDecl>(ND)) {
208 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
209 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000210 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000211
212 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000213 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000214 }
215
216 return Contexts;
217}
218
Douglas Gregorb14904c2010-08-13 22:48:40 +0000219void ASTUnit::CacheCodeCompletionResults() {
220 if (!TheSema)
221 return;
222
Douglas Gregor16896c42010-10-28 15:44:59 +0000223 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000224 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000225
226 // Clear out the previous results.
227 ClearCachedCompletionResults();
228
229 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000230 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000231 llvm::SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000232 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
233 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000234
235 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000236 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
237
Douglas Gregorb14904c2010-08-13 22:48:40 +0000238 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
239 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000240 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000241 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000242 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000243 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000244 *CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000245 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000246 Ctx->getLangOptions(),
247 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000248 CachedResult.Priority = Results[I].Priority;
249 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000250 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000251
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000252 // Keep track of the type of this completion in an ASTContext-agnostic
253 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000254 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000255 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000256 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000257 CachedResult.Type = 0;
258 } else {
259 CanQualType CanUsageType
260 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
261 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
262
263 // Determine whether we have already seen this type. If so, we save
264 // ourselves the work of formatting the type string by using the
265 // temporary, CanQualType-based hash table to find the associated value.
266 unsigned &TypeValue = CompletionTypes[CanUsageType];
267 if (TypeValue == 0) {
268 TypeValue = CompletionTypes.size();
269 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
270 = TypeValue;
271 }
272
273 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000274 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000275
Douglas Gregor39982192010-08-15 06:18:01 +0000276 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000277
278 /// Handle nested-name-specifiers in C++.
279 if (TheSema->Context.getLangOptions().CPlusPlus &&
280 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
281 // The contexts in which a nested-name-specifier can appear in C++.
282 unsigned NNSContexts
283 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
286 | (1 << (CodeCompletionContext::CCC_Statement - 1))
287 | (1 << (CodeCompletionContext::CCC_Expression - 1))
288 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
289 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
290 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
291 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000292 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000293 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
294 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000295
296 if (isa<NamespaceDecl>(Results[I].Declaration) ||
297 isa<NamespaceAliasDecl>(Results[I].Declaration))
298 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
299
300 if (unsigned RemainingContexts
301 = NNSContexts & ~CachedResult.ShowInContexts) {
302 // If there any contexts where this completion can be a
303 // nested-name-specifier but isn't already an option, create a
304 // nested-name-specifier completion.
305 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000306 CachedResult.Completion
307 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000308 *CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000309 CachedResult.ShowInContexts = RemainingContexts;
310 CachedResult.Priority = CCP_NestedNameSpecifier;
311 CachedResult.TypeClass = STC_Void;
312 CachedResult.Type = 0;
313 CachedCompletionResults.push_back(CachedResult);
314 }
315 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000316 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000317 }
318
Douglas Gregorb14904c2010-08-13 22:48:40 +0000319 case Result::RK_Keyword:
320 case Result::RK_Pattern:
321 // Ignore keywords and patterns; we don't care, since they are so
322 // easily regenerated.
323 break;
324
325 case Result::RK_Macro: {
326 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000327 CachedResult.Completion
328 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000329 *CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000330 CachedResult.ShowInContexts
331 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
332 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
333 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
334 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
335 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
336 | (1 << (CodeCompletionContext::CCC_Statement - 1))
337 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000338 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000339 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000340 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000341 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
342 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000343
Douglas Gregorb14904c2010-08-13 22:48:40 +0000344 CachedResult.Priority = Results[I].Priority;
345 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000346 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000347 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000348 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000349 CachedCompletionResults.push_back(CachedResult);
350 break;
351 }
352 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000353 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000354
355 // Save the current top-level hash value.
356 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000357}
358
359void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000360 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000361 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000362 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000363}
364
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000365namespace {
366
Sebastian Redl2c499f62010-08-18 23:56:43 +0000367/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000368/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000369class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000370 LangOptions &LangOpt;
371 HeaderSearch &HSI;
372 std::string &TargetTriple;
373 std::string &Predefines;
374 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000375
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000376 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000377
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000378public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000379 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000380 std::string &TargetTriple, std::string &Predefines,
381 unsigned &Counter)
382 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
383 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000384
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000385 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
386 LangOpt = LangOpts;
387 return false;
388 }
Mike Stump11289f42009-09-09 15:08:12 +0000389
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000390 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000391 TargetTriple = Triple;
392 return false;
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Sebastian Redl8b41f302010-07-14 23:29:55 +0000395 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000396 llvm::StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000397 std::string &SuggestedPredefines,
398 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000399 Predefines = Buffers[0].Data;
400 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
401 Predefines += Buffers[I].Data;
402 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000403 return false;
404 }
Mike Stump11289f42009-09-09 15:08:12 +0000405
Douglas Gregora2f49452010-03-16 19:09:18 +0000406 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000407 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
408 }
Mike Stump11289f42009-09-09 15:08:12 +0000409
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000410 virtual void ReadCounter(unsigned Value) {
411 Counter = Value;
412 }
413};
414
Douglas Gregor33cdd812010-02-18 18:08:43 +0000415class StoredDiagnosticClient : public DiagnosticClient {
416 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
417
418public:
419 explicit StoredDiagnosticClient(
420 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
421 : StoredDiags(StoredDiags) { }
422
423 virtual void HandleDiagnostic(Diagnostic::Level Level,
424 const DiagnosticInfo &Info);
425};
426
427/// \brief RAII object that optionally captures diagnostics, if
428/// there is no diagnostic client to capture them already.
429class CaptureDroppedDiagnostics {
430 Diagnostic &Diags;
431 StoredDiagnosticClient Client;
432 DiagnosticClient *PreviousClient;
433
434public:
435 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000436 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000437 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000438 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000439 if (RequestCapture || Diags.getClient() == 0) {
440 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000441 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000442 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000443 }
444
445 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000446 if (Diags.getClient() == &Client) {
447 Diags.takeClient();
448 Diags.setClient(PreviousClient);
449 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000450 }
451};
452
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000453} // anonymous namespace
454
Douglas Gregor33cdd812010-02-18 18:08:43 +0000455void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
456 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000457 // Default implementation (Warnings/errors count).
458 DiagnosticClient::HandleDiagnostic(Level, Info);
459
Douglas Gregor33cdd812010-02-18 18:08:43 +0000460 StoredDiags.push_back(StoredDiagnostic(Level, Info));
461}
462
Steve Naroffc0683b92009-09-03 18:19:54 +0000463const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000464 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000465}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000466
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000467const std::string &ASTUnit::getASTFileName() {
468 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000469 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000470}
471
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000472llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000473 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000474 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000475 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000476}
477
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000478/// \brief Configure the diagnostics object for use with ASTUnit.
479void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000480 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000481 ASTUnit &AST, bool CaptureDiagnostics) {
482 if (!Diags.getPtr()) {
483 // No diagnostics engine was provided, so create our own diagnostics object
484 // with the default options.
485 DiagnosticOptions DiagOpts;
486 DiagnosticClient *Client = 0;
487 if (CaptureDiagnostics)
488 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000489 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
490 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000491 } else if (CaptureDiagnostics) {
492 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
493 }
494}
495
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000496ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000497 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000498 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000499 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000500 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000501 unsigned NumRemappedFiles,
502 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000503 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000504
505 // Recover resources if we crash before exiting this method.
506 llvm::CrashRecoveryContextCleanupRegistrar
507 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
508 create<ASTUnit>(AST.get()));
509
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000510 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000511
Douglas Gregor16bef852009-10-16 20:01:17 +0000512 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000513 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000514 AST->Diagnostics = Diags;
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000515 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000516 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +0000517 AST->getFileManager()));
518 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000519
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000520 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000521 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
522 if (const llvm::MemoryBuffer *
523 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
524 // Create the file entry for the file that we're mapping from.
525 const FileEntry *FromFile
526 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
527 memBuf->getBufferSize(),
528 0);
529 if (!FromFile) {
530 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
531 << RemappedFiles[I].first;
532 delete memBuf;
533 continue;
534 }
535
536 // Override the contents of the "from" file with the contents of
537 // the "to" file.
538 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
539
540 } else {
541 const char *fname = fileOrBuf.get<const char *>();
542 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
543 if (!ToFile) {
544 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
545 << RemappedFiles[I].first << fname;
546 continue;
547 }
548
549 // Create the file entry for the file that we're mapping from.
550 const FileEntry *FromFile
551 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
552 ToFile->getSize(),
553 0);
554 if (!FromFile) {
555 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
556 << RemappedFiles[I].first;
557 delete memBuf;
558 continue;
559 }
560
561 // Override the contents of the "from" file with the contents of
562 // the "to" file.
563 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000564 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000565 }
566
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000567 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000568
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000569 LangOptions LangInfo;
570 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
571 std::string TargetTriple;
572 std::string Predefines;
573 unsigned Counter;
574
Sebastian Redl2c499f62010-08-18 23:56:43 +0000575 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000576
Sebastian Redl2c499f62010-08-18 23:56:43 +0000577 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000578 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000579 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000580 Predefines, Counter));
581
Sebastian Redl009e7f22010-10-05 16:15:19 +0000582 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000583 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000584 break;
Mike Stump11289f42009-09-09 15:08:12 +0000585
Sebastian Redl2c499f62010-08-18 23:56:43 +0000586 case ASTReader::Failure:
587 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000588 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000589 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Daniel Dunbara8a50932009-12-02 08:44:16 +0000592 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
593
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000594 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000595
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000596 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000597 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000598 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000599 TargetOptions TargetOpts;
600 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000601 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000602 TargetOpts.CPU = "";
603 TargetOpts.Features.clear();
604 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000605 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
606 TargetOpts));
607 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
608 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000609 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000610 Preprocessor &PP = *AST->PP.get();
611
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000612 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000613 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000614 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000615
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000616 // Create and initialize the ASTContext.
617
618 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000619 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000620 *AST->Target.get(),
621 PP.getIdentifierTable(),
622 PP.getSelectorTable(),
623 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000624 /* size_reserve = */0));
625 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000626
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000627 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000628
Sebastian Redl2c499f62010-08-18 23:56:43 +0000629 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000630 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000631 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000632 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000633 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000634 Context.setExternalSource(Source);
635
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000636 // Create an AST consumer, even though it isn't used.
637 AST->Consumer.reset(new ASTConsumer);
638
Sebastian Redl2c499f62010-08-18 23:56:43 +0000639 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000640 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
641 AST->TheSema->Initialize();
642 ReaderPtr->InitializeSema(*AST->TheSema);
643
Mike Stump11289f42009-09-09 15:08:12 +0000644 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000645}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000646
647namespace {
648
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000649/// \brief Preprocessor callback class that updates a hash value with the names
650/// of all macros that have been defined by the translation unit.
651class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
652 unsigned &Hash;
653
654public:
655 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
656
657 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
658 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
659 }
660};
661
662/// \brief Add the given declaration to the hash of all top-level entities.
663void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
664 if (!D)
665 return;
666
667 DeclContext *DC = D->getDeclContext();
668 if (!DC)
669 return;
670
671 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
672 return;
673
674 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
675 if (ND->getIdentifier())
676 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
677 else if (DeclarationName Name = ND->getDeclName()) {
678 std::string NameStr = Name.getAsString();
679 Hash = llvm::HashString(NameStr, Hash);
680 }
681 return;
682 }
683
684 if (ObjCForwardProtocolDecl *Forward
685 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
686 for (ObjCForwardProtocolDecl::protocol_iterator
687 P = Forward->protocol_begin(),
688 PEnd = Forward->protocol_end();
689 P != PEnd; ++P)
690 AddTopLevelDeclarationToHash(*P, Hash);
691 return;
692 }
693
694 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) {
695 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
696 I != IEnd; ++I)
697 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
698 return;
699 }
700}
701
Daniel Dunbar644dca02009-12-04 08:17:33 +0000702class TopLevelDeclTrackerConsumer : public ASTConsumer {
703 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000704 unsigned &Hash;
705
Daniel Dunbar644dca02009-12-04 08:17:33 +0000706public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000707 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
708 : Unit(_Unit), Hash(Hash) {
709 Hash = 0;
710 }
711
Daniel Dunbar644dca02009-12-04 08:17:33 +0000712 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000713 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
714 Decl *D = *it;
715 // FIXME: Currently ObjC method declarations are incorrectly being
716 // reported as top-level declarations, even though their DeclContext
717 // is the containing ObjC @interface/@implementation. This is a
718 // fundamental problem in the parser right now.
719 if (isa<ObjCMethodDecl>(D))
720 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000721
722 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000723 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000724 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000725 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000726
727 // We're not interested in "interesting" decls.
728 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000729};
730
731class TopLevelDeclTrackerAction : public ASTFrontendAction {
732public:
733 ASTUnit &Unit;
734
Daniel Dunbar764c0822009-12-01 09:51:01 +0000735 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
736 llvm::StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000737 CI.getPreprocessor().addPPCallbacks(
738 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
739 return new TopLevelDeclTrackerConsumer(Unit,
740 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000741 }
742
743public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000744 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
745
Daniel Dunbar764c0822009-12-01 09:51:01 +0000746 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000747 virtual bool usesCompleteTranslationUnit() {
748 return Unit.isCompleteTranslationUnit();
749 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000750};
751
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000752class PrecompilePreambleConsumer : public PCHGenerator,
753 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000754 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000755 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000756 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000757
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000758public:
759 PrecompilePreambleConsumer(ASTUnit &Unit,
760 const Preprocessor &PP, bool Chaining,
761 const char *isysroot, llvm::raw_ostream *Out)
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000762 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
763 Hash(Unit.getCurrentTopLevelHashValue()) {
764 Hash = 0;
765 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000766
Douglas Gregore9db88f2010-08-03 19:06:41 +0000767 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000768 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
769 Decl *D = *it;
770 // FIXME: Currently ObjC method declarations are incorrectly being
771 // reported as top-level declarations, even though their DeclContext
772 // is the containing ObjC @interface/@implementation. This is a
773 // fundamental problem in the parser right now.
774 if (isa<ObjCMethodDecl>(D))
775 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000776 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000777 TopLevelDecls.push_back(D);
778 }
779 }
780
781 virtual void HandleTranslationUnit(ASTContext &Ctx) {
782 PCHGenerator::HandleTranslationUnit(Ctx);
783 if (!Unit.getDiagnostics().hasErrorOccurred()) {
784 // Translate the top-level declarations we captured during
785 // parsing into declaration IDs in the precompiled
786 // preamble. This will allow us to deserialize those top-level
787 // declarations when requested.
788 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
789 Unit.addTopLevelDeclFromPreamble(
790 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000791 }
792 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000793
794 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
795 uint64_t Offset) {
796 Unit.addPreprocessedEntityFromPreamble(Offset);
797 }
798
799 virtual ASTSerializationListener *GetASTSerializationListener() {
800 return this;
801 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000802};
803
804class PrecompilePreambleAction : public ASTFrontendAction {
805 ASTUnit &Unit;
806
807public:
808 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
809
810 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
811 llvm::StringRef InFile) {
812 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000813 std::string OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000814 llvm::raw_ostream *OS = 0;
815 bool Chaining;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000816 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
817 OutputFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000818 OS, Chaining))
819 return 0;
820
821 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
822 Sysroot.c_str() : 0;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000823 CI.getPreprocessor().addPPCallbacks(
824 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000825 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
826 isysroot, OS);
827 }
828
829 virtual bool hasCodeCompletionSupport() const { return false; }
830 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000831 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000832};
833
Daniel Dunbar764c0822009-12-01 09:51:01 +0000834}
835
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000836/// Parse the source file into a translation unit using the given compiler
837/// invocation, replacing the current translation unit.
838///
839/// \returns True if a failure occurred that causes the ASTUnit not to
840/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000841bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000842 delete SavedMainFileBuffer;
843 SavedMainFileBuffer = 0;
844
Douglas Gregora0734c52010-08-19 01:33:06 +0000845 if (!Invocation.get()) {
846 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000847 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000848 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000849
Daniel Dunbar764c0822009-12-01 09:51:01 +0000850 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000851 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000852 Clang.setInvocation(Invocation.take());
853 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
854
Douglas Gregor8e984da2010-08-04 16:47:14 +0000855 // Set up diagnostics, capturing any diagnostics that would
856 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000857 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000858
Daniel Dunbar764c0822009-12-01 09:51:01 +0000859 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +0000860 Clang.getTargetOpts().Features = TargetFeatures;
Daniel Dunbar764c0822009-12-01 09:51:01 +0000861 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
862 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000863 if (!Clang.hasTarget()) {
864 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000865 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000866 }
867
Daniel Dunbar764c0822009-12-01 09:51:01 +0000868 // Inform the target of the language options.
869 //
870 // FIXME: We shouldn't need to do this, the target should be immutable once
871 // created. This complexity should be lifted elsewhere.
872 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000873
Daniel Dunbar764c0822009-12-01 09:51:01 +0000874 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
875 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000876 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000877 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000878 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
879 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000880
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000881 // Configure the various subsystems.
882 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000883 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000884 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
885 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000886 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000887 Ctx.reset();
888 PP.reset();
889
890 // Clear out old caches and data.
891 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000892 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000893 CleanTemporaryFiles();
894 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000895
Douglas Gregor7b02b582010-08-20 00:02:33 +0000896 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000897 StoredDiagnostics.erase(
898 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
899 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000900 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000901 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000902 }
903
Daniel Dunbar764c0822009-12-01 09:51:01 +0000904 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000905 Clang.setFileManager(&getFileManager());
906
Daniel Dunbar764c0822009-12-01 09:51:01 +0000907 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000908 Clang.setSourceManager(&getSourceManager());
909
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000910 // If the main file has been overridden due to the use of a preamble,
911 // make that override happen and introduce the preamble.
912 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000913 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000914 if (OverrideMainBuffer) {
915 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
916 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
917 PreprocessorOpts.PrecompiledPreambleBytes.second
918 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000919 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000920 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000921 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000922
Douglas Gregord9a30af2010-08-02 20:51:39 +0000923 // The stored diagnostic has the old source manager in it; update
924 // the locations to refer into the new source manager. Since we've
925 // been careful to make sure that the source manager's state
926 // before and after are identical, so that we can reuse the source
927 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000928 for (unsigned I = NumStoredDiagnosticsFromDriver,
929 N = StoredDiagnostics.size();
930 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000931 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
932 getSourceManager());
933 StoredDiagnostics[I].setLocation(Loc);
934 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000935
936 // Keep track of the override buffer;
937 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000938 } else {
939 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
940 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000941 }
942
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000943 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
944 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000945 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000946 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000947 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000948
Daniel Dunbar644dca02009-12-04 08:17:33 +0000949 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000950
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000951 // Steal the created target, context, and preprocessor, and take back the
952 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000953 TheSema.reset(Clang.takeSema());
954 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000955 Ctx.reset(Clang.takeASTContext());
956 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000957 Clang.takeSourceManager();
958 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000959 Target.reset(Clang.takeTarget());
960
Daniel Dunbar644dca02009-12-04 08:17:33 +0000961 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000962
963 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000964 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000965 PreprocessorOpts.eraseRemappedFile(
966 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000967 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
968 }
969
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000970 Invocation.reset(Clang.takeInvocation());
971 return false;
972
Daniel Dunbar764c0822009-12-01 09:51:01 +0000973error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000974 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000975 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000976 PreprocessorOpts.eraseRemappedFile(
977 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000978 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000979 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000980 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000981 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000982
Douglas Gregorefc46952010-10-12 16:25:54 +0000983 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000984 Clang.takeSourceManager();
985 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000986 Invocation.reset(Clang.takeInvocation());
987 return true;
988}
989
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000990/// \brief Simple function to retrieve a path for a preamble precompiled header.
991static std::string GetPreamblePCHPath() {
992 // FIXME: This is lame; sys::Path should provide this function (in particular,
993 // it should know how to find the temporary files dir).
994 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000995 // FIXME: This is a hack so that we can override the preamble file during
996 // crash-recovery testing, which is the only case where the preamble files
997 // are not necessarily cleaned up.
998 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
999 if (TmpFile)
1000 return TmpFile;
1001
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001002 std::string Error;
1003 const char *TmpDir = ::getenv("TMPDIR");
1004 if (!TmpDir)
1005 TmpDir = ::getenv("TEMP");
1006 if (!TmpDir)
1007 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001008#ifdef LLVM_ON_WIN32
1009 if (!TmpDir)
1010 TmpDir = ::getenv("USERPROFILE");
1011#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001012 if (!TmpDir)
1013 TmpDir = "/tmp";
1014 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001015 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001016 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001017 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001018 if (P.createTemporaryFileOnDisk())
1019 return std::string();
1020
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001021 return P.str();
1022}
1023
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001024/// \brief Compute the preamble for the main file, providing the source buffer
1025/// that corresponds to the main file along with a pair (bytes, start-of-line)
1026/// that describes the preamble.
1027std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001028ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1029 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001030 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001031 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001032 CreatedBuffer = false;
1033
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001034 // Try to determine if the main file has been remapped, either from the
1035 // command line (to another file) or directly through the compiler invocation
1036 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001037 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001038 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1039 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1040 // Check whether there is a file-file remapping of the main file
1041 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001042 M = PreprocessorOpts.remapped_file_begin(),
1043 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001044 M != E;
1045 ++M) {
1046 llvm::sys::PathWithStatus MPath(M->first);
1047 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1048 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1049 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001050 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001051 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001052 CreatedBuffer = false;
1053 }
1054
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001055 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001056 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001057 return std::make_pair((llvm::MemoryBuffer*)0,
1058 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001059 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001060 }
1061 }
1062 }
1063
1064 // Check whether there is a file-buffer remapping. It supercedes the
1065 // file-file remapping.
1066 for (PreprocessorOptions::remapped_file_buffer_iterator
1067 M = PreprocessorOpts.remapped_file_buffer_begin(),
1068 E = PreprocessorOpts.remapped_file_buffer_end();
1069 M != E;
1070 ++M) {
1071 llvm::sys::PathWithStatus MPath(M->first);
1072 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1073 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1074 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001075 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001076 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001077 CreatedBuffer = false;
1078 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001079
Douglas Gregor4dde7492010-07-23 23:58:40 +00001080 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001081 }
1082 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001083 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001084 }
1085
1086 // If the main source file was not remapped, load it now.
1087 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001088 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001089 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001090 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001091
1092 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001093 }
1094
Douglas Gregor028d3e42010-08-09 20:45:32 +00001095 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001096}
1097
Douglas Gregor6481ef12010-07-24 00:38:13 +00001098static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001099 unsigned NewSize,
1100 llvm::StringRef NewName) {
1101 llvm::MemoryBuffer *Result
1102 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1103 memcpy(const_cast<char*>(Result->getBufferStart()),
1104 Old->getBufferStart(), Old->getBufferSize());
1105 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001106 ' ', NewSize - Old->getBufferSize() - 1);
1107 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001108
Douglas Gregor6481ef12010-07-24 00:38:13 +00001109 return Result;
1110}
1111
Douglas Gregor4dde7492010-07-23 23:58:40 +00001112/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1113/// the source file.
1114///
1115/// This routine will compute the preamble of the main source file. If a
1116/// non-trivial preamble is found, it will precompile that preamble into a
1117/// precompiled header so that the precompiled preamble can be used to reduce
1118/// reparsing time. If a precompiled preamble has already been constructed,
1119/// this routine will determine if it is still valid and, if so, avoid
1120/// rebuilding the precompiled preamble.
1121///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001122/// \param AllowRebuild When true (the default), this routine is
1123/// allowed to rebuild the precompiled preamble if it is found to be
1124/// out-of-date.
1125///
1126/// \param MaxLines When non-zero, the maximum number of lines that
1127/// can occur within the preamble.
1128///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001129/// \returns If the precompiled preamble can be used, returns a newly-allocated
1130/// buffer that should be used in place of the main file when doing so.
1131/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001132llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001133 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001134 bool AllowRebuild,
1135 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001136 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1137 PreprocessorOptions &PreprocessorOpts
1138 = PreambleInvocation.getPreprocessorOpts();
1139
1140 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001141 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001142 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001143
Douglas Gregor3edb1672010-11-16 20:45:51 +00001144 // If ComputePreamble() Take ownership of the
1145 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1146 if (CreatedPreambleBuffer)
1147 OwnedPreambleBuffer.reset(NewPreamble.first);
1148
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001149 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001150 // We couldn't find a preamble in the main source. Clear out the current
1151 // preamble, if we have one. It's obviously no good any more.
1152 Preamble.clear();
1153 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001154 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001155 PreambleFile.clear();
1156 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001157
1158 // The next time we actually see a preamble, precompile it.
1159 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001160 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001161 }
1162
1163 if (!Preamble.empty()) {
1164 // We've previously computed a preamble. Check whether we have the same
1165 // preamble now that we did before, and that there's enough space in
1166 // the main-file buffer within the precompiled preamble to fit the
1167 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001168 if (Preamble.size() == NewPreamble.second.first &&
1169 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001170 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001171 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001172 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001173 // The preamble has not changed. We may be able to re-use the precompiled
1174 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001175
Douglas Gregor0e119552010-07-31 00:40:00 +00001176 // Check that none of the files used by the preamble have changed.
1177 bool AnyFileChanged = false;
1178
1179 // First, make a record of those files that have been overridden via
1180 // remapping or unsaved_files.
1181 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1182 for (PreprocessorOptions::remapped_file_iterator
1183 R = PreprocessorOpts.remapped_file_begin(),
1184 REnd = PreprocessorOpts.remapped_file_end();
1185 !AnyFileChanged && R != REnd;
1186 ++R) {
1187 struct stat StatBuf;
1188 if (stat(R->second.c_str(), &StatBuf)) {
1189 // If we can't stat the file we're remapping to, assume that something
1190 // horrible happened.
1191 AnyFileChanged = true;
1192 break;
1193 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001194
Douglas Gregor0e119552010-07-31 00:40:00 +00001195 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1196 StatBuf.st_mtime);
1197 }
1198 for (PreprocessorOptions::remapped_file_buffer_iterator
1199 R = PreprocessorOpts.remapped_file_buffer_begin(),
1200 REnd = PreprocessorOpts.remapped_file_buffer_end();
1201 !AnyFileChanged && R != REnd;
1202 ++R) {
1203 // FIXME: Should we actually compare the contents of file->buffer
1204 // remappings?
1205 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1206 0);
1207 }
1208
1209 // Check whether anything has changed.
1210 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1211 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1212 !AnyFileChanged && F != FEnd;
1213 ++F) {
1214 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1215 = OverriddenFiles.find(F->first());
1216 if (Overridden != OverriddenFiles.end()) {
1217 // This file was remapped; check whether the newly-mapped file
1218 // matches up with the previous mapping.
1219 if (Overridden->second != F->second)
1220 AnyFileChanged = true;
1221 continue;
1222 }
1223
1224 // The file was not remapped; check whether it has changed on disk.
1225 struct stat StatBuf;
1226 if (stat(F->first(), &StatBuf)) {
1227 // If we can't stat the file, assume that something horrible happened.
1228 AnyFileChanged = true;
1229 } else if (StatBuf.st_size != F->second.first ||
1230 StatBuf.st_mtime != F->second.second)
1231 AnyFileChanged = true;
1232 }
1233
1234 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001235 // Okay! We can re-use the precompiled preamble.
1236
1237 // Set the state of the diagnostic object to mimic its state
1238 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001239 // FIXME: This won't catch any #pragma push warning changes that
1240 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001241 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001242 ProcessWarningOptions(getDiagnostics(),
1243 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001244 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1245 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1246 StoredDiagnostics.erase(
1247 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1248 StoredDiagnostics.end());
1249
1250 // Create a version of the main file buffer that is padded to
1251 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001252 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001253 PreambleReservedSize,
1254 FrontendOpts.Inputs[0].second);
1255 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001256 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001257
1258 // If we aren't allowed to rebuild the precompiled preamble, just
1259 // return now.
1260 if (!AllowRebuild)
1261 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001262
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 // We can't reuse the previously-computed preamble. Build a new one.
1264 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001265 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001266 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001267 } else if (!AllowRebuild) {
1268 // We aren't allowed to rebuild the precompiled preamble; just
1269 // return now.
1270 return 0;
1271 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001272
1273 // If the preamble rebuild counter > 1, it's because we previously
1274 // failed to build a preamble and we're not yet ready to try
1275 // again. Decrement the counter and return a failure.
1276 if (PreambleRebuildCounter > 1) {
1277 --PreambleRebuildCounter;
1278 return 0;
1279 }
1280
Douglas Gregore10f0e52010-09-11 17:56:52 +00001281 // Create a temporary file for the precompiled preamble. In rare
1282 // circumstances, this can fail.
1283 std::string PreamblePCHPath = GetPreamblePCHPath();
1284 if (PreamblePCHPath.empty()) {
1285 // Try again next time.
1286 PreambleRebuildCounter = 1;
1287 return 0;
1288 }
1289
Douglas Gregor4dde7492010-07-23 23:58:40 +00001290 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001291 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001292 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001293
1294 // Create a new buffer that stores the preamble. The buffer also contains
1295 // extra space for the original contents of the file (which will be present
1296 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001297 // grows.
1298 PreambleReservedSize = NewPreamble.first->getBufferSize();
1299 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001300 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001301 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001302 PreambleReservedSize *= 2;
1303
Douglas Gregord9a30af2010-08-02 20:51:39 +00001304 // Save the preamble text for later; we'll need to compare against it for
1305 // subsequent reparses.
1306 Preamble.assign(NewPreamble.first->getBufferStart(),
1307 NewPreamble.first->getBufferStart()
1308 + NewPreamble.second.first);
1309 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1310
Douglas Gregora0734c52010-08-19 01:33:06 +00001311 delete PreambleBuffer;
1312 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001313 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001314 FrontendOpts.Inputs[0].second);
1315 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001316 NewPreamble.first->getBufferStart(), Preamble.size());
1317 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001318 ' ', PreambleReservedSize - Preamble.size() - 1);
1319 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001320
1321 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001323 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1324
1325 // Tell the compiler invocation to generate a temporary precompiled header.
1326 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001327 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001328 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001329 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001330 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1331 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001332
1333 // Create the compiler instance to use for building the precompiled preamble.
1334 CompilerInstance Clang;
1335 Clang.setInvocation(&PreambleInvocation);
1336 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1337
Douglas Gregor8e984da2010-08-04 16:47:14 +00001338 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001339 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001340
1341 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001342 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001343 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1344 Clang.getTargetOpts()));
1345 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001346 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1347 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001348 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001349 PreprocessorOpts.eraseRemappedFile(
1350 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001351 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001352 }
1353
1354 // Inform the target of the language options.
1355 //
1356 // FIXME: We shouldn't need to do this, the target should be immutable once
1357 // created. This complexity should be lifted elsewhere.
1358 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1359
1360 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1361 "Invocation must have exactly one source file!");
1362 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1363 "FIXME: AST inputs not yet supported here!");
1364 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1365 "IR inputs not support here!");
1366
1367 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001368 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001369 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001370 StoredDiagnostics.erase(
1371 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1372 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001373 TopLevelDecls.clear();
1374 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001375 PreprocessedEntities.clear();
1376 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001377
1378 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner3f5a9ef2010-11-23 07:51:02 +00001379 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001380
1381 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001382 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +00001383 Clang.getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001384
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001385 llvm::OwningPtr<PrecompilePreambleAction> Act;
1386 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001387 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1388 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001389 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001390 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1391 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001392 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001393 PreprocessorOpts.eraseRemappedFile(
1394 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001395 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001396 }
1397
1398 Act->Execute();
1399 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001400 Clang.takeInvocation();
1401
Douglas Gregore9db88f2010-08-03 19:06:41 +00001402 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001403 // There were errors parsing the preamble, so no precompiled header was
1404 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001405 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001406 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1407 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001408 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001409 PreprocessedEntities.clear();
1410 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001411 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001412 PreprocessorOpts.eraseRemappedFile(
1413 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001414 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001415 }
1416
1417 // Keep track of the preamble we precompiled.
1418 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001419 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1420 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001421
1422 // Keep track of all of the files that the source manager knows about,
1423 // so we can verify whether they have changed or not.
1424 FilesInPreamble.clear();
1425 SourceManager &SourceMgr = Clang.getSourceManager();
1426 const llvm::MemoryBuffer *MainFileBuffer
1427 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1428 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1429 FEnd = SourceMgr.fileinfo_end();
1430 F != FEnd;
1431 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001432 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001433 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1434 continue;
1435
1436 FilesInPreamble[File->getName()]
1437 = std::make_pair(F->second->getSize(), File->getModificationTime());
1438 }
1439
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001440 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001441 PreprocessorOpts.eraseRemappedFile(
1442 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001443
1444 // If the hash of top-level entities differs from the hash of the top-level
1445 // entities the last time we rebuilt the preamble, clear out the completion
1446 // cache.
1447 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1448 CompletionCacheTopLevelHashValue = 0;
1449 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1450 }
1451
Douglas Gregor6481ef12010-07-24 00:38:13 +00001452 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001453 PreambleReservedSize,
1454 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001455}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001456
Douglas Gregore9db88f2010-08-03 19:06:41 +00001457void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1458 std::vector<Decl *> Resolved;
1459 Resolved.reserve(TopLevelDeclsInPreamble.size());
1460 ExternalASTSource &Source = *getASTContext().getExternalSource();
1461 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1462 // Resolve the declaration ID to an actual declaration, possibly
1463 // deserializing the declaration in the process.
1464 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1465 if (D)
1466 Resolved.push_back(D);
1467 }
1468 TopLevelDeclsInPreamble.clear();
1469 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1470}
1471
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001472void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1473 if (!PP)
1474 return;
1475
1476 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1477 if (!PPRec)
1478 return;
1479
1480 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1481 if (!External)
1482 return;
1483
1484 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1485 if (PreprocessedEntity *PE
Douglas Gregor46c50012011-02-11 19:46:30 +00001486 = External->ReadPreprocessedEntityAtOffset(
1487 PreprocessedEntitiesInPreamble[I]))
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001488 PreprocessedEntities.push_back(PE);
1489 }
1490
1491 if (PreprocessedEntities.empty())
1492 return;
1493
1494 PreprocessedEntities.insert(PreprocessedEntities.end(),
1495 PPRec->begin(true), PPRec->end(true));
1496}
1497
1498ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1499 if (!PreprocessedEntitiesInPreamble.empty() &&
1500 PreprocessedEntities.empty())
1501 RealizePreprocessedEntitiesFromPreamble();
1502
1503 if (PreprocessedEntities.empty())
1504 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1505 return PPRec->begin(true);
1506
1507 return PreprocessedEntities.begin();
1508}
1509
1510ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1511 if (!PreprocessedEntitiesInPreamble.empty() &&
1512 PreprocessedEntities.empty())
1513 RealizePreprocessedEntitiesFromPreamble();
1514
1515 if (PreprocessedEntities.empty())
1516 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1517 return PPRec->end(true);
1518
1519 return PreprocessedEntities.end();
1520}
1521
Douglas Gregore9db88f2010-08-03 19:06:41 +00001522unsigned ASTUnit::getMaxPCHLevel() const {
1523 if (!getOnlyLocalDecls())
1524 return Decl::MaxPCHLevel;
1525
Sebastian Redl009e7f22010-10-05 16:15:19 +00001526 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001527}
1528
Douglas Gregor16896c42010-10-28 15:44:59 +00001529llvm::StringRef ASTUnit::getMainFileName() const {
1530 return Invocation->getFrontendOpts().Inputs[0].second;
1531}
1532
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001533ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1534 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1535 llvm::OwningPtr<ASTUnit> AST;
1536 AST.reset(new ASTUnit(false));
1537 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1538 AST->Diagnostics = Diags;
1539 AST->Invocation.reset(CI);
1540 AST->FileMgr.reset(new FileManager(CI->getFileSystemOpts()));
1541 AST->SourceMgr.reset(new SourceManager(*Diags, *AST->FileMgr));
1542
1543 return AST.take();
1544}
1545
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001546bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1547 if (!Invocation)
1548 return true;
1549
1550 // We'll manage file buffers ourselves.
1551 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1552 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001553 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001554
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001555 // Save the target features.
1556 TargetFeatures = Invocation->getTargetOpts().Features;
1557
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001558 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001559 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001560 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001561 OverrideMainBuffer
1562 = getMainBufferWithPrecompiledPreamble(*Invocation);
1563 }
1564
Douglas Gregor16896c42010-10-28 15:44:59 +00001565 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001566 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001567
Douglas Gregor16896c42010-10-28 15:44:59 +00001568 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001569}
1570
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001571ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1572 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1573 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001574 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001575 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001576 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001577 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001578 // Create the AST unit.
1579 llvm::OwningPtr<ASTUnit> AST;
1580 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001581 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001582 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001583 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001584 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001585 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001586 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001587 AST->Invocation.reset(CI);
1588
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001589 // Recover resources if we crash before exiting this method.
1590 llvm::CrashRecoveryContextCleanupRegistrar
1591 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
1592 create<ASTUnit>(AST.get()));
1593
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001594 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001595}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001596
1597ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1598 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001599 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001600 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001601 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001602 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001603 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001604 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001605 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001606 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001607 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001608 bool CacheCodeCompletionResults,
1609 bool CXXPrecompilePreamble,
1610 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001611 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001612 // No diagnostics engine was provided, so create our own diagnostics object
1613 // with the default options.
1614 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001615 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1616 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001617 }
1618
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001619 llvm::SmallVector<const char *, 16> Args;
1620 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1621 Args.insert(Args.end(), ArgBegin, ArgEnd);
1622
1623 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1624 // also want to force it to use clang.
1625 Args.push_back("-fsyntax-only");
1626
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001627 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1628
1629 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001630
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001631 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001632 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001633 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001634
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001635 // FIXME: We shouldn't have to pass in the path info.
1636 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1637 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001638
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001639 // Don't check that inputs exist, they have been remapped.
1640 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001641
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001642 llvm::OwningPtr<driver::Compilation> C(
1643 TheDriver.BuildCompilation(Args.size(), Args.data()));
1644
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001645 // Just print the cc1 options if -### was present.
1646 if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) {
1647 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
1648 return 0;
1649 }
1650
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001651 // We expect to get back exactly one command job, if we didn't something
1652 // failed.
1653 const driver::JobList &Jobs = C->getJobs();
1654 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1655 llvm::SmallString<256> Msg;
1656 llvm::raw_svector_ostream OS(Msg);
1657 C->PrintJob(OS, C->getJobs(), "; ", true);
1658 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1659 return 0;
1660 }
1661
1662 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1663 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1664 Diags->Report(diag::err_fe_expected_clang_command);
1665 return 0;
1666 }
1667
1668 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1669 CI.reset(new CompilerInvocation);
1670 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001671 const_cast<const char **>(CCArgs.data()),
1672 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001673 CCArgs.size(),
1674 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001675 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001676
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001677 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001678 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1679 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1680 if (const llvm::MemoryBuffer *
1681 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1682 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1683 } else {
1684 const char *fname = fileOrBuf.get<const char *>();
1685 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1686 }
1687 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001688 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1689 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001690
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001691 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001692 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001693
Douglas Gregorf5a18542010-10-27 17:24:53 +00001694 // Check whether we should precompile the preamble and/or use chained PCH.
1695 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1696 if (CI->getLangOpts().CPlusPlus) {
1697 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1698
1699 if (PrecompilePreamble && !CXXChainedPCH &&
1700 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1701 PrecompilePreamble = false;
1702 }
1703
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001704 // Create the AST unit.
1705 llvm::OwningPtr<ASTUnit> AST;
1706 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001707 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001708 AST->Diagnostics = Diags;
Chris Lattner5159f612010-11-23 08:35:12 +00001709
1710 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001711 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001712 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001713 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1714 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1715 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1716 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1717 AST->StoredDiagnostics.swap(StoredDiagnostics);
1718 AST->Invocation.reset(CI.take());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001719
1720 // Recover resources if we crash before exiting this method.
1721 llvm::CrashRecoveryContextCleanupRegistrar
1722 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
1723 create<ASTUnit>(AST.get()));
1724
Chris Lattner5159f612010-11-23 08:35:12 +00001725 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001726}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001727
1728bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1729 if (!Invocation.get())
1730 return true;
1731
Douglas Gregor16896c42010-10-28 15:44:59 +00001732 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001733 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001734
Douglas Gregor0e119552010-07-31 00:40:00 +00001735 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001736 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001737 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001738 for (PreprocessorOptions::remapped_file_buffer_iterator
1739 R = PPOpts.remapped_file_buffer_begin(),
1740 REnd = PPOpts.remapped_file_buffer_end();
1741 R != REnd;
1742 ++R) {
1743 delete R->second;
1744 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001745 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001746 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1747 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1748 if (const llvm::MemoryBuffer *
1749 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1750 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1751 memBuf);
1752 } else {
1753 const char *fname = fileOrBuf.get<const char *>();
1754 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1755 fname);
1756 }
1757 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001758
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001759 // If we have a preamble file lying around, or if we might try to
1760 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001761 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001762 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001763 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001764
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001765 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001766 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001767 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001768 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1769 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001770
Douglas Gregor4dde7492010-07-23 23:58:40 +00001771 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001772 bool Result = Parse(OverrideMainBuffer);
1773
1774 // If we're caching global code-completion results, and the top-level
1775 // declarations have changed, clear out the code-completion cache.
1776 if (!Result && ShouldCacheCodeCompletionResults &&
1777 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1778 CacheCodeCompletionResults();
1779
Douglas Gregor4dde7492010-07-23 23:58:40 +00001780 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001781}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001782
Douglas Gregorb14904c2010-08-13 22:48:40 +00001783//----------------------------------------------------------------------------//
1784// Code completion
1785//----------------------------------------------------------------------------//
1786
1787namespace {
1788 /// \brief Code completion consumer that combines the cached code-completion
1789 /// results from an ASTUnit with the code-completion results provided to it,
1790 /// then passes the result on to
1791 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1792 unsigned NormalContexts;
1793 ASTUnit &AST;
1794 CodeCompleteConsumer &Next;
1795
1796 public:
1797 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001798 bool IncludeMacros, bool IncludeCodePatterns,
1799 bool IncludeGlobals)
1800 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001801 Next.isOutputBinary()), AST(AST), Next(Next)
1802 {
1803 // Compute the set of contexts in which we will look when we don't have
1804 // any information about the specific context.
1805 NormalContexts
1806 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1807 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1808 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1809 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1810 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1811 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1812 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1813 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001814 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001815 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1816 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001817
Douglas Gregorb14904c2010-08-13 22:48:40 +00001818 if (AST.getASTContext().getLangOptions().CPlusPlus)
1819 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1820 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1821 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1822 }
1823
1824 virtual void ProcessCodeCompleteResults(Sema &S,
1825 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001826 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001827 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001828
1829 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1830 OverloadCandidate *Candidates,
1831 unsigned NumCandidates) {
1832 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1833 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001834
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001835 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001836 return Next.getAllocator();
1837 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001838 };
1839}
Douglas Gregord46cf182010-08-16 20:01:48 +00001840
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001841/// \brief Helper function that computes which global names are hidden by the
1842/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001843static void CalculateHiddenNames(const CodeCompletionContext &Context,
1844 CodeCompletionResult *Results,
1845 unsigned NumResults,
1846 ASTContext &Ctx,
1847 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001848 bool OnlyTagNames = false;
1849 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001850 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001851 case CodeCompletionContext::CCC_TopLevel:
1852 case CodeCompletionContext::CCC_ObjCInterface:
1853 case CodeCompletionContext::CCC_ObjCImplementation:
1854 case CodeCompletionContext::CCC_ObjCIvarList:
1855 case CodeCompletionContext::CCC_ClassStructUnion:
1856 case CodeCompletionContext::CCC_Statement:
1857 case CodeCompletionContext::CCC_Expression:
1858 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1859 case CodeCompletionContext::CCC_MemberAccess:
1860 case CodeCompletionContext::CCC_Namespace:
1861 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001862 case CodeCompletionContext::CCC_Name:
1863 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001864 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001865 break;
1866
1867 case CodeCompletionContext::CCC_EnumTag:
1868 case CodeCompletionContext::CCC_UnionTag:
1869 case CodeCompletionContext::CCC_ClassOrStructTag:
1870 OnlyTagNames = true;
1871 break;
1872
1873 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001874 case CodeCompletionContext::CCC_MacroName:
1875 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001876 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001877 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001878 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001879 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001880 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001881 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001882 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001883 // We're looking for nothing, or we're looking for names that cannot
1884 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001885 return;
1886 }
1887
John McCall276321a2010-08-25 06:19:51 +00001888 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001889 for (unsigned I = 0; I != NumResults; ++I) {
1890 if (Results[I].Kind != Result::RK_Declaration)
1891 continue;
1892
1893 unsigned IDNS
1894 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1895
1896 bool Hiding = false;
1897 if (OnlyTagNames)
1898 Hiding = (IDNS & Decl::IDNS_Tag);
1899 else {
1900 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001901 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1902 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001903 if (Ctx.getLangOptions().CPlusPlus)
1904 HiddenIDNS |= Decl::IDNS_Tag;
1905 Hiding = (IDNS & HiddenIDNS);
1906 }
1907
1908 if (!Hiding)
1909 continue;
1910
1911 DeclarationName Name = Results[I].Declaration->getDeclName();
1912 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1913 HiddenNames.insert(Identifier->getName());
1914 else
1915 HiddenNames.insert(Name.getAsString());
1916 }
1917}
1918
1919
Douglas Gregord46cf182010-08-16 20:01:48 +00001920void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1921 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001922 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001923 unsigned NumResults) {
1924 // Merge the results we were given with the results we cached.
1925 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001926 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001927 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001928 : (1 << (Context.getKind() - 1)));
1929
1930 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001931 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001932 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001933 llvm::SmallVector<Result, 8> AllResults;
1934 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001935 C = AST.cached_completion_begin(),
1936 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001937 C != CEnd; ++C) {
1938 // If the context we are in matches any of the contexts we are
1939 // interested in, we'll add this result.
1940 if ((C->ShowInContexts & InContexts) == 0)
1941 continue;
1942
1943 // If we haven't added any results previously, do so now.
1944 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001945 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1946 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001947 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1948 AddedResult = true;
1949 }
1950
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001951 // Determine whether this global completion result is hidden by a local
1952 // completion result. If so, skip it.
1953 if (C->Kind != CXCursor_MacroDefinition &&
1954 HiddenNames.count(C->Completion->getTypedText()))
1955 continue;
1956
Douglas Gregord46cf182010-08-16 20:01:48 +00001957 // Adjust priority based on similar type classes.
1958 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001959 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001960 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001961 if (!Context.getPreferredType().isNull()) {
1962 if (C->Kind == CXCursor_MacroDefinition) {
1963 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001964 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001965 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001966 } else if (C->Type) {
1967 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001968 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001969 Context.getPreferredType().getUnqualifiedType());
1970 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1971 if (ExpectedSTC == C->TypeClass) {
1972 // We know this type is similar; check for an exact match.
1973 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001974 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001975 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001976 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001977 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1978 Priority /= CCF_ExactTypeMatch;
1979 else
1980 Priority /= CCF_SimilarTypeMatch;
1981 }
1982 }
1983 }
1984
Douglas Gregor12785102010-08-24 20:21:13 +00001985 // Adjust the completion string, if required.
1986 if (C->Kind == CXCursor_MacroDefinition &&
1987 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1988 // Create a new code-completion string that just contains the
1989 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001990 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1991 C->Availability);
1992 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00001993 CursorKind = CXCursor_NotImplemented;
1994 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001995 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00001996 }
1997
Douglas Gregor8850aa32010-08-25 18:03:13 +00001998 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001999 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002000 }
2001
2002 // If we did not add any cached completion results, just forward the
2003 // results we were given to the next consumer.
2004 if (!AddedResult) {
2005 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2006 return;
2007 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002008
Douglas Gregord46cf182010-08-16 20:01:48 +00002009 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2010 AllResults.size());
2011}
2012
2013
2014
Douglas Gregor8e984da2010-08-04 16:47:14 +00002015void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
2016 RemappedFile *RemappedFiles,
2017 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002018 bool IncludeMacros,
2019 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002020 CodeCompleteConsumer &Consumer,
2021 Diagnostic &Diag, LangOptions &LangOpts,
2022 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00002023 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2024 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002025 if (!Invocation.get())
2026 return;
2027
Douglas Gregor16896c42010-10-28 15:44:59 +00002028 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002029 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2030 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002031
Douglas Gregor8e984da2010-08-04 16:47:14 +00002032 CompilerInvocation CCInvocation(*Invocation);
2033 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
2034 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002035
Douglas Gregorb14904c2010-08-13 22:48:40 +00002036 FrontendOpts.ShowMacrosInCodeCompletion
2037 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002038 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002039 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2040 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002041 FrontendOpts.CodeCompletionAt.FileName = File;
2042 FrontendOpts.CodeCompletionAt.Line = Line;
2043 FrontendOpts.CodeCompletionAt.Column = Column;
2044
2045 // Set the language options appropriately.
2046 LangOpts = CCInvocation.getLangOpts();
2047
2048 CompilerInstance Clang;
2049 Clang.setInvocation(&CCInvocation);
2050 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
2051
2052 // Set up diagnostics, capturing any diagnostics produced.
2053 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002054 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002055 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002056 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002057 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002058
2059 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00002060 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002061 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
2062 Clang.getTargetOpts()));
2063 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002064 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002065 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002066 }
2067
2068 // Inform the target of the language options.
2069 //
2070 // FIXME: We shouldn't need to do this, the target should be immutable once
2071 // created. This complexity should be lifted elsewhere.
2072 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
2073
2074 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
2075 "Invocation must have exactly one source file!");
2076 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
2077 "FIXME: AST inputs not yet supported here!");
2078 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
2079 "IR inputs not support here!");
2080
2081
2082 // Use the source and file managers that we were given.
2083 Clang.setFileManager(&FileMgr);
2084 Clang.setSourceManager(&SourceMgr);
2085
2086 // Remap files.
2087 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002088 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002089 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002090 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2091 if (const llvm::MemoryBuffer *
2092 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2093 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2094 OwnedBuffers.push_back(memBuf);
2095 } else {
2096 const char *fname = fileOrBuf.get<const char *>();
2097 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2098 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002099 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002100
Douglas Gregorb14904c2010-08-13 22:48:40 +00002101 // Use the code completion consumer we were given, but adding any cached
2102 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002103 AugmentedCodeCompleteConsumer *AugmentedConsumer
2104 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2105 FrontendOpts.ShowMacrosInCodeCompletion,
2106 FrontendOpts.ShowCodePatternsInCodeCompletion,
2107 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
2108 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002109
Douglas Gregor028d3e42010-08-09 20:45:32 +00002110 // If we have a precompiled preamble, try to use it. We only allow
2111 // the use of the precompiled preamble if we're if the completion
2112 // point is within the main file, after the end of the precompiled
2113 // preamble.
2114 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2115 if (!PreambleFile.empty()) {
2116 using llvm::sys::FileStatus;
2117 llvm::sys::PathWithStatus CompleteFilePath(File);
2118 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2119 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2120 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2121 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00002122 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00002123 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
2124 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002125 }
2126
2127 // If the main file has been overridden due to the use of a preamble,
2128 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002129 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002130 StoredDiagnostics.insert(StoredDiagnostics.end(),
2131 this->StoredDiagnostics.begin(),
2132 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002133 if (OverrideMainBuffer) {
2134 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2135 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2136 PreprocessorOpts.PrecompiledPreambleBytes.second
2137 = PreambleEndsAtStartOfLine;
2138 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2139 PreprocessorOpts.DisablePCHValidation = true;
2140
2141 // The stored diagnostics have the old source manager. Copy them
2142 // to our output set of stored diagnostics, updating the source
2143 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002144 for (unsigned I = NumStoredDiagnosticsFromDriver,
2145 N = this->StoredDiagnostics.size();
2146 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002147 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
2148 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
2149 StoredDiagnostics[I].setLocation(Loc);
2150 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002151
Douglas Gregorb97b6662010-08-20 00:59:43 +00002152 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002153 } else {
2154 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2155 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002156 }
2157
Douglas Gregor8e984da2010-08-04 16:47:14 +00002158 llvm::OwningPtr<SyntaxOnlyAction> Act;
2159 Act.reset(new SyntaxOnlyAction);
2160 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
2161 Clang.getFrontendOpts().Inputs[0].first)) {
2162 Act->Execute();
2163 Act->EndSourceFile();
2164 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002165
Douglas Gregor8e984da2010-08-04 16:47:14 +00002166 // Steal back our resources.
2167 Clang.takeFileManager();
2168 Clang.takeSourceManager();
2169 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002170}
Douglas Gregore9386682010-08-13 05:36:37 +00002171
2172bool ASTUnit::Save(llvm::StringRef File) {
2173 if (getDiagnostics().hasErrorOccurred())
2174 return true;
2175
2176 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2177 // unconditionally create a stat cache when we parse the file?
2178 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00002179 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2180 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00002181 if (!ErrorInfo.empty() || Out.has_error())
2182 return true;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002183
2184 serialize(Out);
2185 Out.close();
2186 return Out.has_error();
2187}
2188
2189bool ASTUnit::serialize(llvm::raw_ostream &OS) {
2190 if (getDiagnostics().hasErrorOccurred())
2191 return true;
2192
Douglas Gregore9386682010-08-13 05:36:37 +00002193 std::vector<unsigned char> Buffer;
2194 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002195 ASTWriter Writer(Stream);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002196 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregore9386682010-08-13 05:36:37 +00002197
2198 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002199 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002200 OS.write((char *)&Buffer.front(), Buffer.size());
2201
2202 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002203}