blob: afae18f7d949eea90b36fbc88c80d4c42796d48a [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.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000851 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
852
853 // Recover resources if we crash before exiting this method.
854 llvm::CrashRecoveryContextCleanupRegistrar
855 CICleanup(llvm::CrashRecoveryContextCleanup::
856 create<CompilerInstance>(Clang.get()));
857
858 Clang->setInvocation(Invocation.take());
859 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000860
Douglas Gregor8e984da2010-08-04 16:47:14 +0000861 // Set up diagnostics, capturing any diagnostics that would
862 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000863 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000864
Daniel Dunbar764c0822009-12-01 09:51:01 +0000865 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000866 Clang->getTargetOpts().Features = TargetFeatures;
867 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
868 Clang->getTargetOpts()));
869 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000870 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000871 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000872 }
873
Daniel Dunbar764c0822009-12-01 09:51:01 +0000874 // Inform the target of the language options.
875 //
876 // FIXME: We shouldn't need to do this, the target should be immutable once
877 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000878 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000879
Ted Kremenek84de4a12011-03-21 18:40:07 +0000880 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000881 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000882 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000883 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000884 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000885 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000886
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000887 // Configure the various subsystems.
888 // FIXME: Should we retain the previous file manager?
Ted Kremenek84de4a12011-03-21 18:40:07 +0000889 FileSystemOpts = Clang->getFileSystemOpts();
Anders Carlssonc30dcec2011-03-18 18:22:40 +0000890 FileMgr.reset(new FileManager(FileSystemOpts));
Chris Lattner5159f612010-11-23 08:35:12 +0000891 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000892 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000893 Ctx.reset();
894 PP.reset();
895
896 // Clear out old caches and data.
897 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000898 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000899 CleanTemporaryFiles();
900 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000901
Douglas Gregor7b02b582010-08-20 00:02:33 +0000902 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000903 StoredDiagnostics.erase(
904 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
905 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000906 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000907 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000908 }
909
Daniel Dunbar764c0822009-12-01 09:51:01 +0000910 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000911 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000912
Daniel Dunbar764c0822009-12-01 09:51:01 +0000913 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000914 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000915
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000916 // If the main file has been overridden due to the use of a preamble,
917 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000918 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000919 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000920 if (OverrideMainBuffer) {
921 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
922 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
923 PreprocessorOpts.PrecompiledPreambleBytes.second
924 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000925 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000926 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000927 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000928
Douglas Gregord9a30af2010-08-02 20:51:39 +0000929 // The stored diagnostic has the old source manager in it; update
930 // the locations to refer into the new source manager. Since we've
931 // been careful to make sure that the source manager's state
932 // before and after are identical, so that we can reuse the source
933 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000934 for (unsigned I = NumStoredDiagnosticsFromDriver,
935 N = StoredDiagnostics.size();
936 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000937 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
938 getSourceManager());
939 StoredDiagnostics[I].setLocation(Loc);
940 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000941
942 // Keep track of the override buffer;
943 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000944 } else {
945 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
946 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000947 }
948
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000949 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
950 Act.reset(new TopLevelDeclTrackerAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +0000951 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
952 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000953 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000954
Daniel Dunbar644dca02009-12-04 08:17:33 +0000955 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000956
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000957 // Steal the created target, context, and preprocessor, and take back the
958 // source and file managers.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000959 TheSema.reset(Clang->takeSema());
960 Consumer.reset(Clang->takeASTConsumer());
961 Ctx.reset(Clang->takeASTContext());
962 PP.reset(Clang->takePreprocessor());
963 Clang->takeSourceManager();
964 Clang->takeFileManager();
965 Target.reset(Clang->takeTarget());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000966
Daniel Dunbar644dca02009-12-04 08:17:33 +0000967 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000968
969 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000970 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000971 PreprocessorOpts.eraseRemappedFile(
972 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000973 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
974 }
975
Ted Kremenek84de4a12011-03-21 18:40:07 +0000976 Invocation.reset(Clang->takeInvocation());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000977 return false;
978
Daniel Dunbar764c0822009-12-01 09:51:01 +0000979error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000980 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000981 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000982 PreprocessorOpts.eraseRemappedFile(
983 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000984 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000985 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000986 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000987 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000988
Douglas Gregorefc46952010-10-12 16:25:54 +0000989 StoredDiagnostics.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +0000990 Clang->takeSourceManager();
991 Clang->takeFileManager();
992 Invocation.reset(Clang->takeInvocation());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000993 return true;
994}
995
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000996/// \brief Simple function to retrieve a path for a preamble precompiled header.
997static std::string GetPreamblePCHPath() {
998 // FIXME: This is lame; sys::Path should provide this function (in particular,
999 // it should know how to find the temporary files dir).
1000 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001001 // FIXME: This is a hack so that we can override the preamble file during
1002 // crash-recovery testing, which is the only case where the preamble files
1003 // are not necessarily cleaned up.
1004 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1005 if (TmpFile)
1006 return TmpFile;
1007
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001008 std::string Error;
1009 const char *TmpDir = ::getenv("TMPDIR");
1010 if (!TmpDir)
1011 TmpDir = ::getenv("TEMP");
1012 if (!TmpDir)
1013 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001014#ifdef LLVM_ON_WIN32
1015 if (!TmpDir)
1016 TmpDir = ::getenv("USERPROFILE");
1017#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001018 if (!TmpDir)
1019 TmpDir = "/tmp";
1020 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001021 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001022 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001023 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001024 if (P.createTemporaryFileOnDisk())
1025 return std::string();
1026
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001027 return P.str();
1028}
1029
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001030/// \brief Compute the preamble for the main file, providing the source buffer
1031/// that corresponds to the main file along with a pair (bytes, start-of-line)
1032/// that describes the preamble.
1033std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001034ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1035 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001036 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001037 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001038 CreatedBuffer = false;
1039
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001040 // Try to determine if the main file has been remapped, either from the
1041 // command line (to another file) or directly through the compiler invocation
1042 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001043 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001044 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1045 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1046 // Check whether there is a file-file remapping of the main file
1047 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001048 M = PreprocessorOpts.remapped_file_begin(),
1049 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001050 M != E;
1051 ++M) {
1052 llvm::sys::PathWithStatus MPath(M->first);
1053 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1054 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1055 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001056 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001057 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001058 CreatedBuffer = false;
1059 }
1060
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001061 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001062 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001063 return std::make_pair((llvm::MemoryBuffer*)0,
1064 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001065 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001066 }
1067 }
1068 }
1069
1070 // Check whether there is a file-buffer remapping. It supercedes the
1071 // file-file remapping.
1072 for (PreprocessorOptions::remapped_file_buffer_iterator
1073 M = PreprocessorOpts.remapped_file_buffer_begin(),
1074 E = PreprocessorOpts.remapped_file_buffer_end();
1075 M != E;
1076 ++M) {
1077 llvm::sys::PathWithStatus MPath(M->first);
1078 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1079 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1080 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001081 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001082 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001083 CreatedBuffer = false;
1084 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001085
Douglas Gregor4dde7492010-07-23 23:58:40 +00001086 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001087 }
1088 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001089 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001090 }
1091
1092 // If the main source file was not remapped, load it now.
1093 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001094 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001095 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001096 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001097
1098 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001099 }
1100
Douglas Gregor028d3e42010-08-09 20:45:32 +00001101 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001102}
1103
Douglas Gregor6481ef12010-07-24 00:38:13 +00001104static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001105 unsigned NewSize,
1106 llvm::StringRef NewName) {
1107 llvm::MemoryBuffer *Result
1108 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1109 memcpy(const_cast<char*>(Result->getBufferStart()),
1110 Old->getBufferStart(), Old->getBufferSize());
1111 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001112 ' ', NewSize - Old->getBufferSize() - 1);
1113 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001114
Douglas Gregor6481ef12010-07-24 00:38:13 +00001115 return Result;
1116}
1117
Douglas Gregor4dde7492010-07-23 23:58:40 +00001118/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1119/// the source file.
1120///
1121/// This routine will compute the preamble of the main source file. If a
1122/// non-trivial preamble is found, it will precompile that preamble into a
1123/// precompiled header so that the precompiled preamble can be used to reduce
1124/// reparsing time. If a precompiled preamble has already been constructed,
1125/// this routine will determine if it is still valid and, if so, avoid
1126/// rebuilding the precompiled preamble.
1127///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001128/// \param AllowRebuild When true (the default), this routine is
1129/// allowed to rebuild the precompiled preamble if it is found to be
1130/// out-of-date.
1131///
1132/// \param MaxLines When non-zero, the maximum number of lines that
1133/// can occur within the preamble.
1134///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001135/// \returns If the precompiled preamble can be used, returns a newly-allocated
1136/// buffer that should be used in place of the main file when doing so.
1137/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001138llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001139 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001140 bool AllowRebuild,
1141 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001142 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1143 PreprocessorOptions &PreprocessorOpts
1144 = PreambleInvocation.getPreprocessorOpts();
1145
1146 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001147 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001148 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001149
Douglas Gregor3edb1672010-11-16 20:45:51 +00001150 // If ComputePreamble() Take ownership of the
1151 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1152 if (CreatedPreambleBuffer)
1153 OwnedPreambleBuffer.reset(NewPreamble.first);
1154
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001155 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001156 // We couldn't find a preamble in the main source. Clear out the current
1157 // preamble, if we have one. It's obviously no good any more.
1158 Preamble.clear();
1159 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001160 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001161 PreambleFile.clear();
1162 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001163
1164 // The next time we actually see a preamble, precompile it.
1165 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001166 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001167 }
1168
1169 if (!Preamble.empty()) {
1170 // We've previously computed a preamble. Check whether we have the same
1171 // preamble now that we did before, and that there's enough space in
1172 // the main-file buffer within the precompiled preamble to fit the
1173 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001174 if (Preamble.size() == NewPreamble.second.first &&
1175 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001176 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001177 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001178 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001179 // The preamble has not changed. We may be able to re-use the precompiled
1180 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001181
Douglas Gregor0e119552010-07-31 00:40:00 +00001182 // Check that none of the files used by the preamble have changed.
1183 bool AnyFileChanged = false;
1184
1185 // First, make a record of those files that have been overridden via
1186 // remapping or unsaved_files.
1187 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1188 for (PreprocessorOptions::remapped_file_iterator
1189 R = PreprocessorOpts.remapped_file_begin(),
1190 REnd = PreprocessorOpts.remapped_file_end();
1191 !AnyFileChanged && R != REnd;
1192 ++R) {
1193 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001194 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001195 // If we can't stat the file we're remapping to, assume that something
1196 // horrible happened.
1197 AnyFileChanged = true;
1198 break;
1199 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001200
Douglas Gregor0e119552010-07-31 00:40:00 +00001201 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1202 StatBuf.st_mtime);
1203 }
1204 for (PreprocessorOptions::remapped_file_buffer_iterator
1205 R = PreprocessorOpts.remapped_file_buffer_begin(),
1206 REnd = PreprocessorOpts.remapped_file_buffer_end();
1207 !AnyFileChanged && R != REnd;
1208 ++R) {
1209 // FIXME: Should we actually compare the contents of file->buffer
1210 // remappings?
1211 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1212 0);
1213 }
1214
1215 // Check whether anything has changed.
1216 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1217 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1218 !AnyFileChanged && F != FEnd;
1219 ++F) {
1220 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1221 = OverriddenFiles.find(F->first());
1222 if (Overridden != OverriddenFiles.end()) {
1223 // This file was remapped; check whether the newly-mapped file
1224 // matches up with the previous mapping.
1225 if (Overridden->second != F->second)
1226 AnyFileChanged = true;
1227 continue;
1228 }
1229
1230 // The file was not remapped; check whether it has changed on disk.
1231 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001232 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001233 // If we can't stat the file, assume that something horrible happened.
1234 AnyFileChanged = true;
1235 } else if (StatBuf.st_size != F->second.first ||
1236 StatBuf.st_mtime != F->second.second)
1237 AnyFileChanged = true;
1238 }
1239
1240 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001241 // Okay! We can re-use the precompiled preamble.
1242
1243 // Set the state of the diagnostic object to mimic its state
1244 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001245 // FIXME: This won't catch any #pragma push warning changes that
1246 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001247 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001248 ProcessWarningOptions(getDiagnostics(),
1249 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001250 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1251 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1252 StoredDiagnostics.erase(
1253 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1254 StoredDiagnostics.end());
1255
1256 // Create a version of the main file buffer that is padded to
1257 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001258 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001259 PreambleReservedSize,
1260 FrontendOpts.Inputs[0].second);
1261 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001262 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001263
1264 // If we aren't allowed to rebuild the precompiled preamble, just
1265 // return now.
1266 if (!AllowRebuild)
1267 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001268
Douglas Gregor4dde7492010-07-23 23:58:40 +00001269 // We can't reuse the previously-computed preamble. Build a new one.
1270 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001271 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001272 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001273 } else if (!AllowRebuild) {
1274 // We aren't allowed to rebuild the precompiled preamble; just
1275 // return now.
1276 return 0;
1277 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001278
1279 // If the preamble rebuild counter > 1, it's because we previously
1280 // failed to build a preamble and we're not yet ready to try
1281 // again. Decrement the counter and return a failure.
1282 if (PreambleRebuildCounter > 1) {
1283 --PreambleRebuildCounter;
1284 return 0;
1285 }
1286
Douglas Gregore10f0e52010-09-11 17:56:52 +00001287 // Create a temporary file for the precompiled preamble. In rare
1288 // circumstances, this can fail.
1289 std::string PreamblePCHPath = GetPreamblePCHPath();
1290 if (PreamblePCHPath.empty()) {
1291 // Try again next time.
1292 PreambleRebuildCounter = 1;
1293 return 0;
1294 }
1295
Douglas Gregor4dde7492010-07-23 23:58:40 +00001296 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001297 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001298 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001299
1300 // Create a new buffer that stores the preamble. The buffer also contains
1301 // extra space for the original contents of the file (which will be present
1302 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001303 // grows.
1304 PreambleReservedSize = NewPreamble.first->getBufferSize();
1305 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001306 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001307 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001308 PreambleReservedSize *= 2;
1309
Douglas Gregord9a30af2010-08-02 20:51:39 +00001310 // Save the preamble text for later; we'll need to compare against it for
1311 // subsequent reparses.
1312 Preamble.assign(NewPreamble.first->getBufferStart(),
1313 NewPreamble.first->getBufferStart()
1314 + NewPreamble.second.first);
1315 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1316
Douglas Gregora0734c52010-08-19 01:33:06 +00001317 delete PreambleBuffer;
1318 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001319 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001320 FrontendOpts.Inputs[0].second);
1321 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322 NewPreamble.first->getBufferStart(), Preamble.size());
1323 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001324 ' ', PreambleReservedSize - Preamble.size() - 1);
1325 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001326
1327 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001328 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001329 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1330
1331 // Tell the compiler invocation to generate a temporary precompiled header.
1332 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001333 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001334 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001335 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001336 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1337 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001338
1339 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001340 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1341
1342 // Recover resources if we crash before exiting this method.
1343 llvm::CrashRecoveryContextCleanupRegistrar
1344 CICleanup(llvm::CrashRecoveryContextCleanup::
1345 create<CompilerInstance>(Clang.get()));
1346
1347 Clang->setInvocation(&PreambleInvocation);
1348 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001349
Douglas Gregor8e984da2010-08-04 16:47:14 +00001350 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001351 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001352
1353 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001354 Clang->getTargetOpts().Features = TargetFeatures;
1355 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1356 Clang->getTargetOpts()));
1357 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001358 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1359 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001360 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001361 PreprocessorOpts.eraseRemappedFile(
1362 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001363 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001364 }
1365
1366 // Inform the target of the language options.
1367 //
1368 // FIXME: We shouldn't need to do this, the target should be immutable once
1369 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001370 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001371
Ted Kremenek84de4a12011-03-21 18:40:07 +00001372 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001373 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001374 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001375 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001376 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001377 "IR inputs not support here!");
1378
1379 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001380 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001381 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001382 StoredDiagnostics.erase(
1383 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1384 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001385 TopLevelDecls.clear();
1386 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001387 PreprocessedEntities.clear();
1388 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001389
1390 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001391 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001392
1393 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001394 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1395 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001396
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001397 llvm::OwningPtr<PrecompilePreambleAction> Act;
1398 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001399 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1400 Clang->getFrontendOpts().Inputs[0].first)) {
1401 Clang->takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001402 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1403 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001404 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001405 PreprocessorOpts.eraseRemappedFile(
1406 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001407 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001408 }
1409
1410 Act->Execute();
1411 Act->EndSourceFile();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001412 Clang->takeInvocation();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001413
Douglas Gregore9db88f2010-08-03 19:06:41 +00001414 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001415 // There were errors parsing the preamble, so no precompiled header was
1416 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001417 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001418 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1419 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001420 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001421 PreprocessedEntities.clear();
1422 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001423 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001424 PreprocessorOpts.eraseRemappedFile(
1425 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001426 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001427 }
1428
1429 // Keep track of the preamble we precompiled.
1430 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001431 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1432 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001433
1434 // Keep track of all of the files that the source manager knows about,
1435 // so we can verify whether they have changed or not.
1436 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001437 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001438 const llvm::MemoryBuffer *MainFileBuffer
1439 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1440 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1441 FEnd = SourceMgr.fileinfo_end();
1442 F != FEnd;
1443 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001444 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001445 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1446 continue;
1447
1448 FilesInPreamble[File->getName()]
1449 = std::make_pair(F->second->getSize(), File->getModificationTime());
1450 }
1451
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001452 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001453 PreprocessorOpts.eraseRemappedFile(
1454 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001455
1456 // If the hash of top-level entities differs from the hash of the top-level
1457 // entities the last time we rebuilt the preamble, clear out the completion
1458 // cache.
1459 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1460 CompletionCacheTopLevelHashValue = 0;
1461 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1462 }
1463
Douglas Gregor6481ef12010-07-24 00:38:13 +00001464 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001465 PreambleReservedSize,
1466 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001467}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001468
Douglas Gregore9db88f2010-08-03 19:06:41 +00001469void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1470 std::vector<Decl *> Resolved;
1471 Resolved.reserve(TopLevelDeclsInPreamble.size());
1472 ExternalASTSource &Source = *getASTContext().getExternalSource();
1473 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1474 // Resolve the declaration ID to an actual declaration, possibly
1475 // deserializing the declaration in the process.
1476 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1477 if (D)
1478 Resolved.push_back(D);
1479 }
1480 TopLevelDeclsInPreamble.clear();
1481 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1482}
1483
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001484void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1485 if (!PP)
1486 return;
1487
1488 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1489 if (!PPRec)
1490 return;
1491
1492 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1493 if (!External)
1494 return;
1495
1496 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1497 if (PreprocessedEntity *PE
Douglas Gregor46c50012011-02-11 19:46:30 +00001498 = External->ReadPreprocessedEntityAtOffset(
1499 PreprocessedEntitiesInPreamble[I]))
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001500 PreprocessedEntities.push_back(PE);
1501 }
1502
1503 if (PreprocessedEntities.empty())
1504 return;
1505
1506 PreprocessedEntities.insert(PreprocessedEntities.end(),
1507 PPRec->begin(true), PPRec->end(true));
1508}
1509
1510ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1511 if (!PreprocessedEntitiesInPreamble.empty() &&
1512 PreprocessedEntities.empty())
1513 RealizePreprocessedEntitiesFromPreamble();
1514
1515 if (PreprocessedEntities.empty())
1516 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1517 return PPRec->begin(true);
1518
1519 return PreprocessedEntities.begin();
1520}
1521
1522ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1523 if (!PreprocessedEntitiesInPreamble.empty() &&
1524 PreprocessedEntities.empty())
1525 RealizePreprocessedEntitiesFromPreamble();
1526
1527 if (PreprocessedEntities.empty())
1528 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1529 return PPRec->end(true);
1530
1531 return PreprocessedEntities.end();
1532}
1533
Douglas Gregore9db88f2010-08-03 19:06:41 +00001534unsigned ASTUnit::getMaxPCHLevel() const {
1535 if (!getOnlyLocalDecls())
1536 return Decl::MaxPCHLevel;
1537
Sebastian Redl009e7f22010-10-05 16:15:19 +00001538 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001539}
1540
Douglas Gregor16896c42010-10-28 15:44:59 +00001541llvm::StringRef ASTUnit::getMainFileName() const {
1542 return Invocation->getFrontendOpts().Inputs[0].second;
1543}
1544
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001545ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1546 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1547 llvm::OwningPtr<ASTUnit> AST;
1548 AST.reset(new ASTUnit(false));
1549 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1550 AST->Diagnostics = Diags;
1551 AST->Invocation.reset(CI);
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001552 AST->FileSystemOpts = CI->getFileSystemOpts();
1553 AST->FileMgr.reset(new FileManager(AST->FileSystemOpts));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001554 AST->SourceMgr.reset(new SourceManager(*Diags, *AST->FileMgr));
1555
1556 return AST.take();
1557}
1558
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001559bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1560 if (!Invocation)
1561 return true;
1562
1563 // We'll manage file buffers ourselves.
1564 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1565 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001566 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001567
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001568 // Save the target features.
1569 TargetFeatures = Invocation->getTargetOpts().Features;
1570
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001571 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001572 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001573 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001574 OverrideMainBuffer
1575 = getMainBufferWithPrecompiledPreamble(*Invocation);
1576 }
1577
Douglas Gregor16896c42010-10-28 15:44:59 +00001578 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001579 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001580
Douglas Gregor16896c42010-10-28 15:44:59 +00001581 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001582}
1583
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001584ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1585 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1586 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001587 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001588 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001589 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001590 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001591 // Create the AST unit.
1592 llvm::OwningPtr<ASTUnit> AST;
1593 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001594 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001595 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001596 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001597 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001598 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001599 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001600 AST->Invocation.reset(CI);
1601
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001602 // Recover resources if we crash before exiting this method.
1603 llvm::CrashRecoveryContextCleanupRegistrar
1604 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
1605 create<ASTUnit>(AST.get()));
1606
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001607 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001608}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001609
1610ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1611 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001612 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001613 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001614 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001615 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001616 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001617 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001618 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001619 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001620 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001621 bool CacheCodeCompletionResults,
1622 bool CXXPrecompilePreamble,
1623 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001624 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001625 // No diagnostics engine was provided, so create our own diagnostics object
1626 // with the default options.
1627 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001628 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1629 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001630 }
1631
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001632 llvm::SmallVector<const char *, 16> Args;
1633 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1634 Args.insert(Args.end(), ArgBegin, ArgEnd);
1635
1636 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1637 // also want to force it to use clang.
1638 Args.push_back("-fsyntax-only");
1639
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001640 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1641
1642 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001643
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001644 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001645 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001646 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001647
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001648 // FIXME: We shouldn't have to pass in the path info.
1649 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1650 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001651
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001652 // Don't check that inputs exist, they have been remapped.
1653 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001654
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001655 llvm::OwningPtr<driver::Compilation> C(
1656 TheDriver.BuildCompilation(Args.size(), Args.data()));
1657
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001658 // Just print the cc1 options if -### was present.
1659 if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) {
1660 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
1661 return 0;
1662 }
1663
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001664 // We expect to get back exactly one command job, if we didn't something
1665 // failed.
1666 const driver::JobList &Jobs = C->getJobs();
1667 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1668 llvm::SmallString<256> Msg;
1669 llvm::raw_svector_ostream OS(Msg);
1670 C->PrintJob(OS, C->getJobs(), "; ", true);
1671 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1672 return 0;
1673 }
1674
1675 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1676 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1677 Diags->Report(diag::err_fe_expected_clang_command);
1678 return 0;
1679 }
1680
1681 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1682 CI.reset(new CompilerInvocation);
1683 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001684 const_cast<const char **>(CCArgs.data()),
1685 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001686 CCArgs.size(),
1687 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001688 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001689
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001690 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001691 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1692 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1693 if (const llvm::MemoryBuffer *
1694 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1695 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1696 } else {
1697 const char *fname = fileOrBuf.get<const char *>();
1698 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1699 }
1700 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001701 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1702 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001703
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001704 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001705 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001706
Douglas Gregorf5a18542010-10-27 17:24:53 +00001707 // Check whether we should precompile the preamble and/or use chained PCH.
1708 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1709 if (CI->getLangOpts().CPlusPlus) {
1710 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1711
1712 if (PrecompilePreamble && !CXXChainedPCH &&
1713 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1714 PrecompilePreamble = false;
1715 }
1716
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001717 // Create the AST unit.
1718 llvm::OwningPtr<ASTUnit> AST;
1719 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001720 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001721 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001722
1723 AST->FileSystemOpts = CI->getFileSystemOpts();
1724 AST->FileMgr.reset(new FileManager(AST->FileSystemOpts));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001725 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001726 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001727 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1728 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1729 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1730 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1731 AST->StoredDiagnostics.swap(StoredDiagnostics);
1732 AST->Invocation.reset(CI.take());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001733
1734 // Recover resources if we crash before exiting this method.
1735 llvm::CrashRecoveryContextCleanupRegistrar
1736 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
1737 create<ASTUnit>(AST.get()));
1738
Chris Lattner5159f612010-11-23 08:35:12 +00001739 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001740}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001741
1742bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1743 if (!Invocation.get())
1744 return true;
1745
Douglas Gregor16896c42010-10-28 15:44:59 +00001746 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001747 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001748
Douglas Gregor0e119552010-07-31 00:40:00 +00001749 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001750 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001751 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001752 for (PreprocessorOptions::remapped_file_buffer_iterator
1753 R = PPOpts.remapped_file_buffer_begin(),
1754 REnd = PPOpts.remapped_file_buffer_end();
1755 R != REnd;
1756 ++R) {
1757 delete R->second;
1758 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001759 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001760 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1761 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1762 if (const llvm::MemoryBuffer *
1763 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1764 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1765 memBuf);
1766 } else {
1767 const char *fname = fileOrBuf.get<const char *>();
1768 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1769 fname);
1770 }
1771 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001772
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001773 // If we have a preamble file lying around, or if we might try to
1774 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001775 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001776 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001777 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001778
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001779 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001780 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001781 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001782 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1783 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001784
Douglas Gregor4dde7492010-07-23 23:58:40 +00001785 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001786 bool Result = Parse(OverrideMainBuffer);
1787
1788 // If we're caching global code-completion results, and the top-level
1789 // declarations have changed, clear out the code-completion cache.
1790 if (!Result && ShouldCacheCodeCompletionResults &&
1791 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1792 CacheCodeCompletionResults();
1793
Douglas Gregor4dde7492010-07-23 23:58:40 +00001794 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001795}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001796
Douglas Gregorb14904c2010-08-13 22:48:40 +00001797//----------------------------------------------------------------------------//
1798// Code completion
1799//----------------------------------------------------------------------------//
1800
1801namespace {
1802 /// \brief Code completion consumer that combines the cached code-completion
1803 /// results from an ASTUnit with the code-completion results provided to it,
1804 /// then passes the result on to
1805 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1806 unsigned NormalContexts;
1807 ASTUnit &AST;
1808 CodeCompleteConsumer &Next;
1809
1810 public:
1811 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001812 bool IncludeMacros, bool IncludeCodePatterns,
1813 bool IncludeGlobals)
1814 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001815 Next.isOutputBinary()), AST(AST), Next(Next)
1816 {
1817 // Compute the set of contexts in which we will look when we don't have
1818 // any information about the specific context.
1819 NormalContexts
1820 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1821 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1822 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1823 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1824 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1825 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1826 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1827 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001828 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001829 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1830 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001831
Douglas Gregorb14904c2010-08-13 22:48:40 +00001832 if (AST.getASTContext().getLangOptions().CPlusPlus)
1833 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1834 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1835 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1836 }
1837
1838 virtual void ProcessCodeCompleteResults(Sema &S,
1839 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001840 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001841 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001842
1843 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1844 OverloadCandidate *Candidates,
1845 unsigned NumCandidates) {
1846 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1847 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001848
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001849 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001850 return Next.getAllocator();
1851 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001852 };
1853}
Douglas Gregord46cf182010-08-16 20:01:48 +00001854
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001855/// \brief Helper function that computes which global names are hidden by the
1856/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001857static void CalculateHiddenNames(const CodeCompletionContext &Context,
1858 CodeCompletionResult *Results,
1859 unsigned NumResults,
1860 ASTContext &Ctx,
1861 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001862 bool OnlyTagNames = false;
1863 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001864 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001865 case CodeCompletionContext::CCC_TopLevel:
1866 case CodeCompletionContext::CCC_ObjCInterface:
1867 case CodeCompletionContext::CCC_ObjCImplementation:
1868 case CodeCompletionContext::CCC_ObjCIvarList:
1869 case CodeCompletionContext::CCC_ClassStructUnion:
1870 case CodeCompletionContext::CCC_Statement:
1871 case CodeCompletionContext::CCC_Expression:
1872 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1873 case CodeCompletionContext::CCC_MemberAccess:
1874 case CodeCompletionContext::CCC_Namespace:
1875 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001876 case CodeCompletionContext::CCC_Name:
1877 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001878 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001879 break;
1880
1881 case CodeCompletionContext::CCC_EnumTag:
1882 case CodeCompletionContext::CCC_UnionTag:
1883 case CodeCompletionContext::CCC_ClassOrStructTag:
1884 OnlyTagNames = true;
1885 break;
1886
1887 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001888 case CodeCompletionContext::CCC_MacroName:
1889 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001890 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001891 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001892 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001893 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001894 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001895 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001896 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001897 // We're looking for nothing, or we're looking for names that cannot
1898 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001899 return;
1900 }
1901
John McCall276321a2010-08-25 06:19:51 +00001902 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001903 for (unsigned I = 0; I != NumResults; ++I) {
1904 if (Results[I].Kind != Result::RK_Declaration)
1905 continue;
1906
1907 unsigned IDNS
1908 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1909
1910 bool Hiding = false;
1911 if (OnlyTagNames)
1912 Hiding = (IDNS & Decl::IDNS_Tag);
1913 else {
1914 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001915 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1916 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001917 if (Ctx.getLangOptions().CPlusPlus)
1918 HiddenIDNS |= Decl::IDNS_Tag;
1919 Hiding = (IDNS & HiddenIDNS);
1920 }
1921
1922 if (!Hiding)
1923 continue;
1924
1925 DeclarationName Name = Results[I].Declaration->getDeclName();
1926 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1927 HiddenNames.insert(Identifier->getName());
1928 else
1929 HiddenNames.insert(Name.getAsString());
1930 }
1931}
1932
1933
Douglas Gregord46cf182010-08-16 20:01:48 +00001934void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1935 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001936 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001937 unsigned NumResults) {
1938 // Merge the results we were given with the results we cached.
1939 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001940 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001941 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001942 : (1 << (Context.getKind() - 1)));
1943
1944 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001945 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001946 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001947 llvm::SmallVector<Result, 8> AllResults;
1948 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001949 C = AST.cached_completion_begin(),
1950 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001951 C != CEnd; ++C) {
1952 // If the context we are in matches any of the contexts we are
1953 // interested in, we'll add this result.
1954 if ((C->ShowInContexts & InContexts) == 0)
1955 continue;
1956
1957 // If we haven't added any results previously, do so now.
1958 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001959 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1960 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001961 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1962 AddedResult = true;
1963 }
1964
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001965 // Determine whether this global completion result is hidden by a local
1966 // completion result. If so, skip it.
1967 if (C->Kind != CXCursor_MacroDefinition &&
1968 HiddenNames.count(C->Completion->getTypedText()))
1969 continue;
1970
Douglas Gregord46cf182010-08-16 20:01:48 +00001971 // Adjust priority based on similar type classes.
1972 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001973 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001974 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001975 if (!Context.getPreferredType().isNull()) {
1976 if (C->Kind == CXCursor_MacroDefinition) {
1977 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001978 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001979 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001980 } else if (C->Type) {
1981 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001982 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001983 Context.getPreferredType().getUnqualifiedType());
1984 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1985 if (ExpectedSTC == C->TypeClass) {
1986 // We know this type is similar; check for an exact match.
1987 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001988 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001989 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001990 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001991 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1992 Priority /= CCF_ExactTypeMatch;
1993 else
1994 Priority /= CCF_SimilarTypeMatch;
1995 }
1996 }
1997 }
1998
Douglas Gregor12785102010-08-24 20:21:13 +00001999 // Adjust the completion string, if required.
2000 if (C->Kind == CXCursor_MacroDefinition &&
2001 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2002 // Create a new code-completion string that just contains the
2003 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002004 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2005 C->Availability);
2006 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002007 CursorKind = CXCursor_NotImplemented;
2008 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002009 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002010 }
2011
Douglas Gregor8850aa32010-08-25 18:03:13 +00002012 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002013 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002014 }
2015
2016 // If we did not add any cached completion results, just forward the
2017 // results we were given to the next consumer.
2018 if (!AddedResult) {
2019 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2020 return;
2021 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002022
Douglas Gregord46cf182010-08-16 20:01:48 +00002023 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2024 AllResults.size());
2025}
2026
2027
2028
Douglas Gregor8e984da2010-08-04 16:47:14 +00002029void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
2030 RemappedFile *RemappedFiles,
2031 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002032 bool IncludeMacros,
2033 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002034 CodeCompleteConsumer &Consumer,
2035 Diagnostic &Diag, LangOptions &LangOpts,
2036 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00002037 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2038 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002039 if (!Invocation.get())
2040 return;
2041
Douglas Gregor16896c42010-10-28 15:44:59 +00002042 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002043 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2044 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002045
Douglas Gregor8e984da2010-08-04 16:47:14 +00002046 CompilerInvocation CCInvocation(*Invocation);
2047 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
2048 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002049
Douglas Gregorb14904c2010-08-13 22:48:40 +00002050 FrontendOpts.ShowMacrosInCodeCompletion
2051 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002052 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002053 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2054 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002055 FrontendOpts.CodeCompletionAt.FileName = File;
2056 FrontendOpts.CodeCompletionAt.Line = Line;
2057 FrontendOpts.CodeCompletionAt.Column = Column;
2058
2059 // Set the language options appropriately.
2060 LangOpts = CCInvocation.getLangOpts();
2061
Ted Kremenek84de4a12011-03-21 18:40:07 +00002062 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2063
2064 // Recover resources if we crash before exiting this method.
2065 llvm::CrashRecoveryContextCleanupRegistrar
2066 CICleanup(llvm::CrashRecoveryContextCleanup::
2067 create<CompilerInstance>(Clang.get()));
2068
2069 Clang->setInvocation(&CCInvocation);
2070 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002071
2072 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002073 Clang->setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002074 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002075 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002076 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002077 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002078
2079 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002080 Clang->getTargetOpts().Features = TargetFeatures;
2081 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2082 Clang->getTargetOpts()));
2083 if (!Clang->hasTarget()) {
2084 Clang->takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002085 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002086 }
2087
2088 // Inform the target of the language options.
2089 //
2090 // FIXME: We shouldn't need to do this, the target should be immutable once
2091 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002092 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002093
Ted Kremenek84de4a12011-03-21 18:40:07 +00002094 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002095 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002096 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002097 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002098 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002099 "IR inputs not support here!");
2100
2101
2102 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002103 Clang->setFileManager(&FileMgr);
2104 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002105
2106 // Remap files.
2107 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002108 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002109 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002110 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2111 if (const llvm::MemoryBuffer *
2112 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2113 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2114 OwnedBuffers.push_back(memBuf);
2115 } else {
2116 const char *fname = fileOrBuf.get<const char *>();
2117 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2118 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002119 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002120
Douglas Gregorb14904c2010-08-13 22:48:40 +00002121 // Use the code completion consumer we were given, but adding any cached
2122 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002123 AugmentedCodeCompleteConsumer *AugmentedConsumer
2124 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2125 FrontendOpts.ShowMacrosInCodeCompletion,
2126 FrontendOpts.ShowCodePatternsInCodeCompletion,
2127 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002128 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002129
Douglas Gregor028d3e42010-08-09 20:45:32 +00002130 // If we have a precompiled preamble, try to use it. We only allow
2131 // the use of the precompiled preamble if we're if the completion
2132 // point is within the main file, after the end of the precompiled
2133 // preamble.
2134 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2135 if (!PreambleFile.empty()) {
2136 using llvm::sys::FileStatus;
2137 llvm::sys::PathWithStatus CompleteFilePath(File);
2138 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2139 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2140 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2141 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00002142 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00002143 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
2144 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002145 }
2146
2147 // If the main file has been overridden due to the use of a preamble,
2148 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002149 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002150 StoredDiagnostics.insert(StoredDiagnostics.end(),
2151 this->StoredDiagnostics.begin(),
2152 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002153 if (OverrideMainBuffer) {
2154 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2155 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2156 PreprocessorOpts.PrecompiledPreambleBytes.second
2157 = PreambleEndsAtStartOfLine;
2158 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2159 PreprocessorOpts.DisablePCHValidation = true;
2160
2161 // The stored diagnostics have the old source manager. Copy them
2162 // to our output set of stored diagnostics, updating the source
2163 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002164 for (unsigned I = NumStoredDiagnosticsFromDriver,
2165 N = this->StoredDiagnostics.size();
2166 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002167 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
2168 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
2169 StoredDiagnostics[I].setLocation(Loc);
2170 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002171
Douglas Gregorb97b6662010-08-20 00:59:43 +00002172 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002173 } else {
2174 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2175 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002176 }
2177
Douglas Gregor8e984da2010-08-04 16:47:14 +00002178 llvm::OwningPtr<SyntaxOnlyAction> Act;
2179 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002180 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2181 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002182 Act->Execute();
2183 Act->EndSourceFile();
2184 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002185
Douglas Gregor8e984da2010-08-04 16:47:14 +00002186 // Steal back our resources.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002187 Clang->takeFileManager();
2188 Clang->takeSourceManager();
2189 Clang->takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002190}
Douglas Gregore9386682010-08-13 05:36:37 +00002191
2192bool ASTUnit::Save(llvm::StringRef File) {
2193 if (getDiagnostics().hasErrorOccurred())
2194 return true;
2195
2196 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2197 // unconditionally create a stat cache when we parse the file?
2198 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00002199 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2200 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00002201 if (!ErrorInfo.empty() || Out.has_error())
2202 return true;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002203
2204 serialize(Out);
2205 Out.close();
2206 return Out.has_error();
2207}
2208
2209bool ASTUnit::serialize(llvm::raw_ostream &OS) {
2210 if (getDiagnostics().hasErrorOccurred())
2211 return true;
2212
Douglas Gregore9386682010-08-13 05:36:37 +00002213 std::vector<unsigned char> Buffer;
2214 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002215 ASTWriter Writer(Stream);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002216 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregore9386682010-08-13 05:36:37 +00002217
2218 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002219 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002220 OS.write((char *)&Buffer.front(), Buffer.size());
2221
2222 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002223}