blob: 4a3b5f9f622c0a906cffe8891fa501803f2634bf [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.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000124 if (Invocation.getPtr() && 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;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000515 AST->FileMgr = new FileManager(FileSystemOpts);
516 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
517 AST->getFileManager());
Chris Lattner5159f612010-11-23 08:35:12 +0000518 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;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000605 AST->Target = TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
606 TargetOpts);
607 AST->PP = new Preprocessor(AST->getDiagnostics(), LangInfo, *AST->Target,
608 AST->getSourceManager(), HeaderInfo);
609 Preprocessor &PP = *AST->PP;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000610
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000611 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000612 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000613 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000614
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000615 // Create and initialize the ASTContext.
616
Ted Kremenek5e14d392011-03-21 18:40:17 +0000617 AST->Ctx = new ASTContext(LangInfo,
618 AST->getSourceManager(),
619 *AST->Target,
620 PP.getIdentifierTable(),
621 PP.getSelectorTable(),
622 PP.getBuiltinInfo(),
623 /* size_reserve = */0);
624 ASTContext &Context = *AST->Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000625
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000626 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000627
Sebastian Redl2c499f62010-08-18 23:56:43 +0000628 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000629 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000630 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000631 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000632 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000633 Context.setExternalSource(Source);
634
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000635 // Create an AST consumer, even though it isn't used.
636 AST->Consumer.reset(new ASTConsumer);
637
Sebastian Redl2c499f62010-08-18 23:56:43 +0000638 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000639 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
640 AST->TheSema->Initialize();
641 ReaderPtr->InitializeSema(*AST->TheSema);
642
Mike Stump11289f42009-09-09 15:08:12 +0000643 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000644}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000645
646namespace {
647
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000648/// \brief Preprocessor callback class that updates a hash value with the names
649/// of all macros that have been defined by the translation unit.
650class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
651 unsigned &Hash;
652
653public:
654 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
655
656 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
657 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
658 }
659};
660
661/// \brief Add the given declaration to the hash of all top-level entities.
662void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
663 if (!D)
664 return;
665
666 DeclContext *DC = D->getDeclContext();
667 if (!DC)
668 return;
669
670 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
671 return;
672
673 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
674 if (ND->getIdentifier())
675 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
676 else if (DeclarationName Name = ND->getDeclName()) {
677 std::string NameStr = Name.getAsString();
678 Hash = llvm::HashString(NameStr, Hash);
679 }
680 return;
681 }
682
683 if (ObjCForwardProtocolDecl *Forward
684 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
685 for (ObjCForwardProtocolDecl::protocol_iterator
686 P = Forward->protocol_begin(),
687 PEnd = Forward->protocol_end();
688 P != PEnd; ++P)
689 AddTopLevelDeclarationToHash(*P, Hash);
690 return;
691 }
692
693 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) {
694 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
695 I != IEnd; ++I)
696 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
697 return;
698 }
699}
700
Daniel Dunbar644dca02009-12-04 08:17:33 +0000701class TopLevelDeclTrackerConsumer : public ASTConsumer {
702 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000703 unsigned &Hash;
704
Daniel Dunbar644dca02009-12-04 08:17:33 +0000705public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000706 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
707 : Unit(_Unit), Hash(Hash) {
708 Hash = 0;
709 }
710
Daniel Dunbar644dca02009-12-04 08:17:33 +0000711 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000712 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
713 Decl *D = *it;
714 // FIXME: Currently ObjC method declarations are incorrectly being
715 // reported as top-level declarations, even though their DeclContext
716 // is the containing ObjC @interface/@implementation. This is a
717 // fundamental problem in the parser right now.
718 if (isa<ObjCMethodDecl>(D))
719 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000720
721 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000722 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000723 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000724 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000725
726 // We're not interested in "interesting" decls.
727 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000728};
729
730class TopLevelDeclTrackerAction : public ASTFrontendAction {
731public:
732 ASTUnit &Unit;
733
Daniel Dunbar764c0822009-12-01 09:51:01 +0000734 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
735 llvm::StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000736 CI.getPreprocessor().addPPCallbacks(
737 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
738 return new TopLevelDeclTrackerConsumer(Unit,
739 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000740 }
741
742public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000743 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
744
Daniel Dunbar764c0822009-12-01 09:51:01 +0000745 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000746 virtual bool usesCompleteTranslationUnit() {
747 return Unit.isCompleteTranslationUnit();
748 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000749};
750
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000751class PrecompilePreambleConsumer : public PCHGenerator,
752 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000753 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000754 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000755 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000756
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000757public:
758 PrecompilePreambleConsumer(ASTUnit &Unit,
759 const Preprocessor &PP, bool Chaining,
760 const char *isysroot, llvm::raw_ostream *Out)
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000761 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
762 Hash(Unit.getCurrentTopLevelHashValue()) {
763 Hash = 0;
764 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000765
Douglas Gregore9db88f2010-08-03 19:06:41 +0000766 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000767 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
768 Decl *D = *it;
769 // FIXME: Currently ObjC method declarations are incorrectly being
770 // reported as top-level declarations, even though their DeclContext
771 // is the containing ObjC @interface/@implementation. This is a
772 // fundamental problem in the parser right now.
773 if (isa<ObjCMethodDecl>(D))
774 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000775 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000776 TopLevelDecls.push_back(D);
777 }
778 }
779
780 virtual void HandleTranslationUnit(ASTContext &Ctx) {
781 PCHGenerator::HandleTranslationUnit(Ctx);
782 if (!Unit.getDiagnostics().hasErrorOccurred()) {
783 // Translate the top-level declarations we captured during
784 // parsing into declaration IDs in the precompiled
785 // preamble. This will allow us to deserialize those top-level
786 // declarations when requested.
787 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
788 Unit.addTopLevelDeclFromPreamble(
789 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000790 }
791 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000792
793 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
794 uint64_t Offset) {
795 Unit.addPreprocessedEntityFromPreamble(Offset);
796 }
797
798 virtual ASTSerializationListener *GetASTSerializationListener() {
799 return this;
800 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000801};
802
803class PrecompilePreambleAction : public ASTFrontendAction {
804 ASTUnit &Unit;
805
806public:
807 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
808
809 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
810 llvm::StringRef InFile) {
811 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000812 std::string OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000813 llvm::raw_ostream *OS = 0;
814 bool Chaining;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000815 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
816 OutputFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000817 OS, Chaining))
818 return 0;
819
820 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
821 Sysroot.c_str() : 0;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000822 CI.getPreprocessor().addPPCallbacks(
823 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000824 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
825 isysroot, OS);
826 }
827
828 virtual bool hasCodeCompletionSupport() const { return false; }
829 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000830 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000831};
832
Daniel Dunbar764c0822009-12-01 09:51:01 +0000833}
834
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000835/// Parse the source file into a translation unit using the given compiler
836/// invocation, replacing the current translation unit.
837///
838/// \returns True if a failure occurred that causes the ASTUnit not to
839/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000840bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000841 delete SavedMainFileBuffer;
842 SavedMainFileBuffer = 0;
843
Ted Kremenek5e14d392011-03-21 18:40:17 +0000844 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000845 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000846 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000847 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000848
Daniel Dunbar764c0822009-12-01 09:51:01 +0000849 // Create the compiler instance to use for building the AST.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000850 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
851
852 // Recover resources if we crash before exiting this method.
853 llvm::CrashRecoveryContextCleanupRegistrar
854 CICleanup(llvm::CrashRecoveryContextCleanup::
855 create<CompilerInstance>(Clang.get()));
856
Ted Kremenek5e14d392011-03-21 18:40:17 +0000857 Clang->setInvocation(&*Invocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +0000858 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000859
Douglas Gregor8e984da2010-08-04 16:47:14 +0000860 // Set up diagnostics, capturing any diagnostics that would
861 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000862 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000863
Daniel Dunbar764c0822009-12-01 09:51:01 +0000864 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000865 Clang->getTargetOpts().Features = TargetFeatures;
866 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +0000867 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +0000868 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000869 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000870 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000871 }
872
Daniel Dunbar764c0822009-12-01 09:51:01 +0000873 // Inform the target of the language options.
874 //
875 // FIXME: We shouldn't need to do this, the target should be immutable once
876 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000877 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000878
Ted Kremenek84de4a12011-03-21 18:40:07 +0000879 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000880 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000881 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000882 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000883 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000884 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000885
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000886 // Configure the various subsystems.
887 // FIXME: Should we retain the previous file manager?
Ted Kremenek84de4a12011-03-21 18:40:07 +0000888 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000889 FileMgr = new FileManager(FileSystemOpts);
890 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000891 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000892 Ctx = 0;
893 PP = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000894
895 // Clear out old caches and data.
896 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000897 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000898 CleanTemporaryFiles();
899 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000900
Douglas Gregor7b02b582010-08-20 00:02:33 +0000901 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000902 StoredDiagnostics.erase(
903 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
904 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000905 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000906 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000907 }
908
Daniel Dunbar764c0822009-12-01 09:51:01 +0000909 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000910 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000911
Daniel Dunbar764c0822009-12-01 09:51:01 +0000912 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000913 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000914
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000915 // If the main file has been overridden due to the use of a preamble,
916 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000917 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000918 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000919 if (OverrideMainBuffer) {
920 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
921 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
922 PreprocessorOpts.PrecompiledPreambleBytes.second
923 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000924 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000925 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000926 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000927
Douglas Gregord9a30af2010-08-02 20:51:39 +0000928 // The stored diagnostic has the old source manager in it; update
929 // the locations to refer into the new source manager. Since we've
930 // been careful to make sure that the source manager's state
931 // before and after are identical, so that we can reuse the source
932 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000933 for (unsigned I = NumStoredDiagnosticsFromDriver,
934 N = StoredDiagnostics.size();
935 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000936 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
937 getSourceManager());
938 StoredDiagnostics[I].setLocation(Loc);
939 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000940
941 // Keep track of the override buffer;
942 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000943 } else {
944 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
945 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000946 }
947
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000948 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
949 Act.reset(new TopLevelDeclTrackerAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +0000950 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
951 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000952 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000953
Daniel Dunbar644dca02009-12-04 08:17:33 +0000954 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000955
Ted Kremenek5e14d392011-03-21 18:40:17 +0000956 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000957 TheSema.reset(Clang->takeSema());
958 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +0000959 Ctx = &Clang->getASTContext();
960 PP = &Clang->getPreprocessor();
961 Clang->setSourceManager(0);
962 Clang->setFileManager(0);
963 Target = &Clang->getTarget();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000964
Daniel Dunbar644dca02009-12-04 08:17:33 +0000965 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000966
967 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000968 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000969 PreprocessorOpts.eraseRemappedFile(
970 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000971 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
972 }
973
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000974 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000975
Daniel Dunbar764c0822009-12-01 09:51:01 +0000976error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000977 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000978 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000979 PreprocessorOpts.eraseRemappedFile(
980 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000981 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000982 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000983 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000984 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000985
Douglas Gregorefc46952010-10-12 16:25:54 +0000986 StoredDiagnostics.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000987 return true;
988}
989
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000990/// \brief Simple function to retrieve a path for a preamble precompiled header.
991static std::string GetPreamblePCHPath() {
992 // FIXME: This is lame; sys::Path should provide this function (in particular,
993 // it should know how to find the temporary files dir).
994 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000995 // FIXME: This is a hack so that we can override the preamble file during
996 // crash-recovery testing, which is the only case where the preamble files
997 // are not necessarily cleaned up.
998 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
999 if (TmpFile)
1000 return TmpFile;
1001
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001002 std::string Error;
1003 const char *TmpDir = ::getenv("TMPDIR");
1004 if (!TmpDir)
1005 TmpDir = ::getenv("TEMP");
1006 if (!TmpDir)
1007 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001008#ifdef LLVM_ON_WIN32
1009 if (!TmpDir)
1010 TmpDir = ::getenv("USERPROFILE");
1011#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001012 if (!TmpDir)
1013 TmpDir = "/tmp";
1014 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001015 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001016 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001017 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001018 if (P.createTemporaryFileOnDisk())
1019 return std::string();
1020
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001021 return P.str();
1022}
1023
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001024/// \brief Compute the preamble for the main file, providing the source buffer
1025/// that corresponds to the main file along with a pair (bytes, start-of-line)
1026/// that describes the preamble.
1027std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001028ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1029 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001030 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001031 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001032 CreatedBuffer = false;
1033
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001034 // Try to determine if the main file has been remapped, either from the
1035 // command line (to another file) or directly through the compiler invocation
1036 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001037 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001038 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1039 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1040 // Check whether there is a file-file remapping of the main file
1041 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001042 M = PreprocessorOpts.remapped_file_begin(),
1043 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001044 M != E;
1045 ++M) {
1046 llvm::sys::PathWithStatus MPath(M->first);
1047 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1048 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1049 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001050 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001051 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001052 CreatedBuffer = false;
1053 }
1054
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001055 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001056 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001057 return std::make_pair((llvm::MemoryBuffer*)0,
1058 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001059 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001060 }
1061 }
1062 }
1063
1064 // Check whether there is a file-buffer remapping. It supercedes the
1065 // file-file remapping.
1066 for (PreprocessorOptions::remapped_file_buffer_iterator
1067 M = PreprocessorOpts.remapped_file_buffer_begin(),
1068 E = PreprocessorOpts.remapped_file_buffer_end();
1069 M != E;
1070 ++M) {
1071 llvm::sys::PathWithStatus MPath(M->first);
1072 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1073 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1074 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001075 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001076 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001077 CreatedBuffer = false;
1078 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001079
Douglas Gregor4dde7492010-07-23 23:58:40 +00001080 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001081 }
1082 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001083 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001084 }
1085
1086 // If the main source file was not remapped, load it now.
1087 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001088 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001089 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001090 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001091
1092 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001093 }
1094
Douglas Gregor028d3e42010-08-09 20:45:32 +00001095 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001096}
1097
Douglas Gregor6481ef12010-07-24 00:38:13 +00001098static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001099 unsigned NewSize,
1100 llvm::StringRef NewName) {
1101 llvm::MemoryBuffer *Result
1102 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1103 memcpy(const_cast<char*>(Result->getBufferStart()),
1104 Old->getBufferStart(), Old->getBufferSize());
1105 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001106 ' ', NewSize - Old->getBufferSize() - 1);
1107 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001108
Douglas Gregor6481ef12010-07-24 00:38:13 +00001109 return Result;
1110}
1111
Douglas Gregor4dde7492010-07-23 23:58:40 +00001112/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1113/// the source file.
1114///
1115/// This routine will compute the preamble of the main source file. If a
1116/// non-trivial preamble is found, it will precompile that preamble into a
1117/// precompiled header so that the precompiled preamble can be used to reduce
1118/// reparsing time. If a precompiled preamble has already been constructed,
1119/// this routine will determine if it is still valid and, if so, avoid
1120/// rebuilding the precompiled preamble.
1121///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001122/// \param AllowRebuild When true (the default), this routine is
1123/// allowed to rebuild the precompiled preamble if it is found to be
1124/// out-of-date.
1125///
1126/// \param MaxLines When non-zero, the maximum number of lines that
1127/// can occur within the preamble.
1128///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001129/// \returns If the precompiled preamble can be used, returns a newly-allocated
1130/// buffer that should be used in place of the main file when doing so.
1131/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001132llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001133 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001134 bool AllowRebuild,
1135 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001136 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1137 PreprocessorOptions &PreprocessorOpts
1138 = PreambleInvocation.getPreprocessorOpts();
1139
1140 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001141 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001142 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001143
Douglas Gregor3edb1672010-11-16 20:45:51 +00001144 // If ComputePreamble() Take ownership of the
1145 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1146 if (CreatedPreambleBuffer)
1147 OwnedPreambleBuffer.reset(NewPreamble.first);
1148
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001149 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001150 // We couldn't find a preamble in the main source. Clear out the current
1151 // preamble, if we have one. It's obviously no good any more.
1152 Preamble.clear();
1153 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001154 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001155 PreambleFile.clear();
1156 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001157
1158 // The next time we actually see a preamble, precompile it.
1159 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001160 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001161 }
1162
1163 if (!Preamble.empty()) {
1164 // We've previously computed a preamble. Check whether we have the same
1165 // preamble now that we did before, and that there's enough space in
1166 // the main-file buffer within the precompiled preamble to fit the
1167 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001168 if (Preamble.size() == NewPreamble.second.first &&
1169 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001170 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001171 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001172 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001173 // The preamble has not changed. We may be able to re-use the precompiled
1174 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001175
Douglas Gregor0e119552010-07-31 00:40:00 +00001176 // Check that none of the files used by the preamble have changed.
1177 bool AnyFileChanged = false;
1178
1179 // First, make a record of those files that have been overridden via
1180 // remapping or unsaved_files.
1181 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1182 for (PreprocessorOptions::remapped_file_iterator
1183 R = PreprocessorOpts.remapped_file_begin(),
1184 REnd = PreprocessorOpts.remapped_file_end();
1185 !AnyFileChanged && R != REnd;
1186 ++R) {
1187 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001188 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001189 // If we can't stat the file we're remapping to, assume that something
1190 // horrible happened.
1191 AnyFileChanged = true;
1192 break;
1193 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001194
Douglas Gregor0e119552010-07-31 00:40:00 +00001195 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1196 StatBuf.st_mtime);
1197 }
1198 for (PreprocessorOptions::remapped_file_buffer_iterator
1199 R = PreprocessorOpts.remapped_file_buffer_begin(),
1200 REnd = PreprocessorOpts.remapped_file_buffer_end();
1201 !AnyFileChanged && R != REnd;
1202 ++R) {
1203 // FIXME: Should we actually compare the contents of file->buffer
1204 // remappings?
1205 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1206 0);
1207 }
1208
1209 // Check whether anything has changed.
1210 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1211 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1212 !AnyFileChanged && F != FEnd;
1213 ++F) {
1214 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1215 = OverriddenFiles.find(F->first());
1216 if (Overridden != OverriddenFiles.end()) {
1217 // This file was remapped; check whether the newly-mapped file
1218 // matches up with the previous mapping.
1219 if (Overridden->second != F->second)
1220 AnyFileChanged = true;
1221 continue;
1222 }
1223
1224 // The file was not remapped; check whether it has changed on disk.
1225 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001226 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001227 // If we can't stat the file, assume that something horrible happened.
1228 AnyFileChanged = true;
1229 } else if (StatBuf.st_size != F->second.first ||
1230 StatBuf.st_mtime != F->second.second)
1231 AnyFileChanged = true;
1232 }
1233
1234 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001235 // Okay! We can re-use the precompiled preamble.
1236
1237 // Set the state of the diagnostic object to mimic its state
1238 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001239 // FIXME: This won't catch any #pragma push warning changes that
1240 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001241 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001242 ProcessWarningOptions(getDiagnostics(),
1243 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001244 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1245 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1246 StoredDiagnostics.erase(
1247 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1248 StoredDiagnostics.end());
1249
1250 // Create a version of the main file buffer that is padded to
1251 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001252 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001253 PreambleReservedSize,
1254 FrontendOpts.Inputs[0].second);
1255 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001256 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001257
1258 // If we aren't allowed to rebuild the precompiled preamble, just
1259 // return now.
1260 if (!AllowRebuild)
1261 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001262
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 // We can't reuse the previously-computed preamble. Build a new one.
1264 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001265 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001266 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001267 } else if (!AllowRebuild) {
1268 // We aren't allowed to rebuild the precompiled preamble; just
1269 // return now.
1270 return 0;
1271 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001272
1273 // If the preamble rebuild counter > 1, it's because we previously
1274 // failed to build a preamble and we're not yet ready to try
1275 // again. Decrement the counter and return a failure.
1276 if (PreambleRebuildCounter > 1) {
1277 --PreambleRebuildCounter;
1278 return 0;
1279 }
1280
Douglas Gregore10f0e52010-09-11 17:56:52 +00001281 // Create a temporary file for the precompiled preamble. In rare
1282 // circumstances, this can fail.
1283 std::string PreamblePCHPath = GetPreamblePCHPath();
1284 if (PreamblePCHPath.empty()) {
1285 // Try again next time.
1286 PreambleRebuildCounter = 1;
1287 return 0;
1288 }
1289
Douglas Gregor4dde7492010-07-23 23:58:40 +00001290 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001291 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001292 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001293
1294 // Create a new buffer that stores the preamble. The buffer also contains
1295 // extra space for the original contents of the file (which will be present
1296 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001297 // grows.
1298 PreambleReservedSize = NewPreamble.first->getBufferSize();
1299 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001300 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001301 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001302 PreambleReservedSize *= 2;
1303
Douglas Gregord9a30af2010-08-02 20:51:39 +00001304 // Save the preamble text for later; we'll need to compare against it for
1305 // subsequent reparses.
1306 Preamble.assign(NewPreamble.first->getBufferStart(),
1307 NewPreamble.first->getBufferStart()
1308 + NewPreamble.second.first);
1309 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1310
Douglas Gregora0734c52010-08-19 01:33:06 +00001311 delete PreambleBuffer;
1312 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001313 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001314 FrontendOpts.Inputs[0].second);
1315 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001316 NewPreamble.first->getBufferStart(), Preamble.size());
1317 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001318 ' ', PreambleReservedSize - Preamble.size() - 1);
1319 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001320
1321 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001323 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1324
1325 // Tell the compiler invocation to generate a temporary precompiled header.
1326 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001327 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001328 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001329 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001330 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1331 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001332
1333 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001334 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1335
1336 // Recover resources if we crash before exiting this method.
1337 llvm::CrashRecoveryContextCleanupRegistrar
1338 CICleanup(llvm::CrashRecoveryContextCleanup::
1339 create<CompilerInstance>(Clang.get()));
1340
1341 Clang->setInvocation(&PreambleInvocation);
1342 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001343
Douglas Gregor8e984da2010-08-04 16:47:14 +00001344 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001345 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001346
1347 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001348 Clang->getTargetOpts().Features = TargetFeatures;
1349 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1350 Clang->getTargetOpts()));
1351 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001352 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1353 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001354 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001355 PreprocessorOpts.eraseRemappedFile(
1356 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001357 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001358 }
1359
1360 // Inform the target of the language options.
1361 //
1362 // FIXME: We shouldn't need to do this, the target should be immutable once
1363 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001364 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001365
Ted Kremenek84de4a12011-03-21 18:40:07 +00001366 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001367 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001368 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001369 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001370 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001371 "IR inputs not support here!");
1372
1373 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001374 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001375 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001376 StoredDiagnostics.erase(
1377 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1378 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001379 TopLevelDecls.clear();
1380 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001381 PreprocessedEntities.clear();
1382 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001383
1384 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001385 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001386
1387 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001388 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001389 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001390
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001391 llvm::OwningPtr<PrecompilePreambleAction> Act;
1392 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001393 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1394 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001395 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1396 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001397 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001398 PreprocessorOpts.eraseRemappedFile(
1399 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001400 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001401 }
1402
1403 Act->Execute();
1404 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001405
Douglas Gregore9db88f2010-08-03 19:06:41 +00001406 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001407 // There were errors parsing the preamble, so no precompiled header was
1408 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001409 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001410 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1411 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001412 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001413 PreprocessedEntities.clear();
1414 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001415 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001416 PreprocessorOpts.eraseRemappedFile(
1417 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001418 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001419 }
1420
1421 // Keep track of the preamble we precompiled.
1422 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001423 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1424 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001425
1426 // Keep track of all of the files that the source manager knows about,
1427 // so we can verify whether they have changed or not.
1428 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001429 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001430 const llvm::MemoryBuffer *MainFileBuffer
1431 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1432 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1433 FEnd = SourceMgr.fileinfo_end();
1434 F != FEnd;
1435 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001436 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001437 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1438 continue;
1439
1440 FilesInPreamble[File->getName()]
1441 = std::make_pair(F->second->getSize(), File->getModificationTime());
1442 }
1443
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001444 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001445 PreprocessorOpts.eraseRemappedFile(
1446 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001447
1448 // If the hash of top-level entities differs from the hash of the top-level
1449 // entities the last time we rebuilt the preamble, clear out the completion
1450 // cache.
1451 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1452 CompletionCacheTopLevelHashValue = 0;
1453 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1454 }
1455
Douglas Gregor6481ef12010-07-24 00:38:13 +00001456 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001457 PreambleReservedSize,
1458 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001459}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001460
Douglas Gregore9db88f2010-08-03 19:06:41 +00001461void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1462 std::vector<Decl *> Resolved;
1463 Resolved.reserve(TopLevelDeclsInPreamble.size());
1464 ExternalASTSource &Source = *getASTContext().getExternalSource();
1465 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1466 // Resolve the declaration ID to an actual declaration, possibly
1467 // deserializing the declaration in the process.
1468 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1469 if (D)
1470 Resolved.push_back(D);
1471 }
1472 TopLevelDeclsInPreamble.clear();
1473 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1474}
1475
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001476void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1477 if (!PP)
1478 return;
1479
1480 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1481 if (!PPRec)
1482 return;
1483
1484 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1485 if (!External)
1486 return;
1487
1488 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1489 if (PreprocessedEntity *PE
Douglas Gregor46c50012011-02-11 19:46:30 +00001490 = External->ReadPreprocessedEntityAtOffset(
1491 PreprocessedEntitiesInPreamble[I]))
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001492 PreprocessedEntities.push_back(PE);
1493 }
1494
1495 if (PreprocessedEntities.empty())
1496 return;
1497
1498 PreprocessedEntities.insert(PreprocessedEntities.end(),
1499 PPRec->begin(true), PPRec->end(true));
1500}
1501
1502ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1503 if (!PreprocessedEntitiesInPreamble.empty() &&
1504 PreprocessedEntities.empty())
1505 RealizePreprocessedEntitiesFromPreamble();
1506
1507 if (PreprocessedEntities.empty())
1508 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1509 return PPRec->begin(true);
1510
1511 return PreprocessedEntities.begin();
1512}
1513
1514ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1515 if (!PreprocessedEntitiesInPreamble.empty() &&
1516 PreprocessedEntities.empty())
1517 RealizePreprocessedEntitiesFromPreamble();
1518
1519 if (PreprocessedEntities.empty())
1520 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1521 return PPRec->end(true);
1522
1523 return PreprocessedEntities.end();
1524}
1525
Douglas Gregore9db88f2010-08-03 19:06:41 +00001526unsigned ASTUnit::getMaxPCHLevel() const {
1527 if (!getOnlyLocalDecls())
1528 return Decl::MaxPCHLevel;
1529
Sebastian Redl009e7f22010-10-05 16:15:19 +00001530 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001531}
1532
Douglas Gregor16896c42010-10-28 15:44:59 +00001533llvm::StringRef ASTUnit::getMainFileName() const {
1534 return Invocation->getFrontendOpts().Inputs[0].second;
1535}
1536
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001537ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1538 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1539 llvm::OwningPtr<ASTUnit> AST;
1540 AST.reset(new ASTUnit(false));
1541 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1542 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001543 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001544 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001545 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1546 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001547
1548 return AST.take();
1549}
1550
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001551bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1552 if (!Invocation)
1553 return true;
1554
1555 // We'll manage file buffers ourselves.
1556 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1557 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001558 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001559
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001560 // Save the target features.
1561 TargetFeatures = Invocation->getTargetOpts().Features;
1562
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001563 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001564 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001565 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001566 OverrideMainBuffer
1567 = getMainBufferWithPrecompiledPreamble(*Invocation);
1568 }
1569
Douglas Gregor16896c42010-10-28 15:44:59 +00001570 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001571 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001572
Douglas Gregor16896c42010-10-28 15:44:59 +00001573 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001574}
1575
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001576ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1577 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1578 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001579 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001580 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001581 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001582 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001583 // Create the AST unit.
1584 llvm::OwningPtr<ASTUnit> AST;
1585 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001586 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001587 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001588 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001589 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001590 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001591 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001592 AST->Invocation = CI;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001593
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001594 // Recover resources if we crash before exiting this method.
1595 llvm::CrashRecoveryContextCleanupRegistrar
1596 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
1597 create<ASTUnit>(AST.get()));
1598
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001599 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001600}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001601
1602ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1603 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001604 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001605 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001606 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001607 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001608 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001609 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001610 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001611 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001612 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001613 bool CacheCodeCompletionResults,
1614 bool CXXPrecompilePreamble,
1615 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001616 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001617 // No diagnostics engine was provided, so create our own diagnostics object
1618 // with the default options.
1619 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001620 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1621 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001622 }
1623
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001624 llvm::SmallVector<const char *, 16> Args;
1625 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1626 Args.insert(Args.end(), ArgBegin, ArgEnd);
1627
1628 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1629 // also want to force it to use clang.
1630 Args.push_back("-fsyntax-only");
1631
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001632 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1633
Ted Kremenek5e14d392011-03-21 18:40:17 +00001634 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001635
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001636 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001637 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001638 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001639
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001640 // FIXME: We shouldn't have to pass in the path info.
1641 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1642 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001643
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001644 // Don't check that inputs exist, they have been remapped.
1645 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001646
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001647 llvm::OwningPtr<driver::Compilation> C(
1648 TheDriver.BuildCompilation(Args.size(), Args.data()));
1649
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001650 // Just print the cc1 options if -### was present.
1651 if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) {
1652 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
1653 return 0;
1654 }
1655
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001656 // We expect to get back exactly one command job, if we didn't something
1657 // failed.
1658 const driver::JobList &Jobs = C->getJobs();
1659 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1660 llvm::SmallString<256> Msg;
1661 llvm::raw_svector_ostream OS(Msg);
1662 C->PrintJob(OS, C->getJobs(), "; ", true);
1663 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1664 return 0;
1665 }
1666
1667 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1668 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1669 Diags->Report(diag::err_fe_expected_clang_command);
1670 return 0;
1671 }
1672
1673 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001674 CI = new CompilerInvocation();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001675 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001676 const_cast<const char **>(CCArgs.data()),
1677 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001678 CCArgs.size(),
1679 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001680 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001681
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001682 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001683 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1684 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1685 if (const llvm::MemoryBuffer *
1686 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1687 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1688 } else {
1689 const char *fname = fileOrBuf.get<const char *>();
1690 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1691 }
1692 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001693 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1694 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001695
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001696 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001697 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001698
Douglas Gregorf5a18542010-10-27 17:24:53 +00001699 // Check whether we should precompile the preamble and/or use chained PCH.
1700 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1701 if (CI->getLangOpts().CPlusPlus) {
1702 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1703
1704 if (PrecompilePreamble && !CXXChainedPCH &&
1705 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1706 PrecompilePreamble = false;
1707 }
1708
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001709 // Create the AST unit.
1710 llvm::OwningPtr<ASTUnit> AST;
1711 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001712 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001713 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001714
1715 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001716 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001717 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001718 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001719 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1720 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1721 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1722 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1723 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001724 AST->Invocation = CI;
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001725
1726 // Recover resources if we crash before exiting this method.
1727 llvm::CrashRecoveryContextCleanupRegistrar
1728 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup::
1729 create<ASTUnit>(AST.get()));
1730
Chris Lattner5159f612010-11-23 08:35:12 +00001731 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001732}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001733
1734bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001735 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001736 return true;
1737
Douglas Gregor16896c42010-10-28 15:44:59 +00001738 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001739 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001740
Douglas Gregor0e119552010-07-31 00:40:00 +00001741 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001742 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001743 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001744 for (PreprocessorOptions::remapped_file_buffer_iterator
1745 R = PPOpts.remapped_file_buffer_begin(),
1746 REnd = PPOpts.remapped_file_buffer_end();
1747 R != REnd;
1748 ++R) {
1749 delete R->second;
1750 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001751 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001752 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1753 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1754 if (const llvm::MemoryBuffer *
1755 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1756 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1757 memBuf);
1758 } else {
1759 const char *fname = fileOrBuf.get<const char *>();
1760 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1761 fname);
1762 }
1763 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001764
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001765 // If we have a preamble file lying around, or if we might try to
1766 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001767 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001768 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001769 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001770
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001771 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001772 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001773 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001774 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1775 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001776
Douglas Gregor4dde7492010-07-23 23:58:40 +00001777 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001778 bool Result = Parse(OverrideMainBuffer);
1779
1780 // If we're caching global code-completion results, and the top-level
1781 // declarations have changed, clear out the code-completion cache.
1782 if (!Result && ShouldCacheCodeCompletionResults &&
1783 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1784 CacheCodeCompletionResults();
1785
Douglas Gregor4dde7492010-07-23 23:58:40 +00001786 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001787}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001788
Douglas Gregorb14904c2010-08-13 22:48:40 +00001789//----------------------------------------------------------------------------//
1790// Code completion
1791//----------------------------------------------------------------------------//
1792
1793namespace {
1794 /// \brief Code completion consumer that combines the cached code-completion
1795 /// results from an ASTUnit with the code-completion results provided to it,
1796 /// then passes the result on to
1797 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1798 unsigned NormalContexts;
1799 ASTUnit &AST;
1800 CodeCompleteConsumer &Next;
1801
1802 public:
1803 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001804 bool IncludeMacros, bool IncludeCodePatterns,
1805 bool IncludeGlobals)
1806 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001807 Next.isOutputBinary()), AST(AST), Next(Next)
1808 {
1809 // Compute the set of contexts in which we will look when we don't have
1810 // any information about the specific context.
1811 NormalContexts
1812 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1813 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1814 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1815 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1816 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1817 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1818 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1819 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001820 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001821 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1822 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001823
Douglas Gregorb14904c2010-08-13 22:48:40 +00001824 if (AST.getASTContext().getLangOptions().CPlusPlus)
1825 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1826 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1827 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1828 }
1829
1830 virtual void ProcessCodeCompleteResults(Sema &S,
1831 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001832 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001833 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001834
1835 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1836 OverloadCandidate *Candidates,
1837 unsigned NumCandidates) {
1838 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1839 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001840
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001841 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001842 return Next.getAllocator();
1843 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001844 };
1845}
Douglas Gregord46cf182010-08-16 20:01:48 +00001846
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001847/// \brief Helper function that computes which global names are hidden by the
1848/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001849static void CalculateHiddenNames(const CodeCompletionContext &Context,
1850 CodeCompletionResult *Results,
1851 unsigned NumResults,
1852 ASTContext &Ctx,
1853 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001854 bool OnlyTagNames = false;
1855 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001856 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001857 case CodeCompletionContext::CCC_TopLevel:
1858 case CodeCompletionContext::CCC_ObjCInterface:
1859 case CodeCompletionContext::CCC_ObjCImplementation:
1860 case CodeCompletionContext::CCC_ObjCIvarList:
1861 case CodeCompletionContext::CCC_ClassStructUnion:
1862 case CodeCompletionContext::CCC_Statement:
1863 case CodeCompletionContext::CCC_Expression:
1864 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1865 case CodeCompletionContext::CCC_MemberAccess:
1866 case CodeCompletionContext::CCC_Namespace:
1867 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001868 case CodeCompletionContext::CCC_Name:
1869 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001870 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001871 break;
1872
1873 case CodeCompletionContext::CCC_EnumTag:
1874 case CodeCompletionContext::CCC_UnionTag:
1875 case CodeCompletionContext::CCC_ClassOrStructTag:
1876 OnlyTagNames = true;
1877 break;
1878
1879 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001880 case CodeCompletionContext::CCC_MacroName:
1881 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001882 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001883 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001884 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001885 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001886 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001887 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001888 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001889 // We're looking for nothing, or we're looking for names that cannot
1890 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001891 return;
1892 }
1893
John McCall276321a2010-08-25 06:19:51 +00001894 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001895 for (unsigned I = 0; I != NumResults; ++I) {
1896 if (Results[I].Kind != Result::RK_Declaration)
1897 continue;
1898
1899 unsigned IDNS
1900 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1901
1902 bool Hiding = false;
1903 if (OnlyTagNames)
1904 Hiding = (IDNS & Decl::IDNS_Tag);
1905 else {
1906 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001907 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1908 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001909 if (Ctx.getLangOptions().CPlusPlus)
1910 HiddenIDNS |= Decl::IDNS_Tag;
1911 Hiding = (IDNS & HiddenIDNS);
1912 }
1913
1914 if (!Hiding)
1915 continue;
1916
1917 DeclarationName Name = Results[I].Declaration->getDeclName();
1918 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1919 HiddenNames.insert(Identifier->getName());
1920 else
1921 HiddenNames.insert(Name.getAsString());
1922 }
1923}
1924
1925
Douglas Gregord46cf182010-08-16 20:01:48 +00001926void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1927 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001928 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001929 unsigned NumResults) {
1930 // Merge the results we were given with the results we cached.
1931 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001932 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001933 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001934 : (1 << (Context.getKind() - 1)));
1935
1936 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001937 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001938 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001939 llvm::SmallVector<Result, 8> AllResults;
1940 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001941 C = AST.cached_completion_begin(),
1942 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001943 C != CEnd; ++C) {
1944 // If the context we are in matches any of the contexts we are
1945 // interested in, we'll add this result.
1946 if ((C->ShowInContexts & InContexts) == 0)
1947 continue;
1948
1949 // If we haven't added any results previously, do so now.
1950 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001951 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1952 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001953 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1954 AddedResult = true;
1955 }
1956
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001957 // Determine whether this global completion result is hidden by a local
1958 // completion result. If so, skip it.
1959 if (C->Kind != CXCursor_MacroDefinition &&
1960 HiddenNames.count(C->Completion->getTypedText()))
1961 continue;
1962
Douglas Gregord46cf182010-08-16 20:01:48 +00001963 // Adjust priority based on similar type classes.
1964 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001965 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001966 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001967 if (!Context.getPreferredType().isNull()) {
1968 if (C->Kind == CXCursor_MacroDefinition) {
1969 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001970 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001971 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001972 } else if (C->Type) {
1973 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001974 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001975 Context.getPreferredType().getUnqualifiedType());
1976 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1977 if (ExpectedSTC == C->TypeClass) {
1978 // We know this type is similar; check for an exact match.
1979 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001980 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001981 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001982 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001983 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1984 Priority /= CCF_ExactTypeMatch;
1985 else
1986 Priority /= CCF_SimilarTypeMatch;
1987 }
1988 }
1989 }
1990
Douglas Gregor12785102010-08-24 20:21:13 +00001991 // Adjust the completion string, if required.
1992 if (C->Kind == CXCursor_MacroDefinition &&
1993 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1994 // Create a new code-completion string that just contains the
1995 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001996 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1997 C->Availability);
1998 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00001999 CursorKind = CXCursor_NotImplemented;
2000 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002001 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002002 }
2003
Douglas Gregor8850aa32010-08-25 18:03:13 +00002004 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002005 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002006 }
2007
2008 // If we did not add any cached completion results, just forward the
2009 // results we were given to the next consumer.
2010 if (!AddedResult) {
2011 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2012 return;
2013 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002014
Douglas Gregord46cf182010-08-16 20:01:48 +00002015 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2016 AllResults.size());
2017}
2018
2019
2020
Douglas Gregor8e984da2010-08-04 16:47:14 +00002021void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
2022 RemappedFile *RemappedFiles,
2023 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002024 bool IncludeMacros,
2025 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002026 CodeCompleteConsumer &Consumer,
2027 Diagnostic &Diag, LangOptions &LangOpts,
2028 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00002029 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2030 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002031 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002032 return;
2033
Douglas Gregor16896c42010-10-28 15:44:59 +00002034 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002035 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2036 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002037
Ted Kremenek5e14d392011-03-21 18:40:17 +00002038 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2039 CCInvocation(new CompilerInvocation(*Invocation));
2040
2041 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2042 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002043
Douglas Gregorb14904c2010-08-13 22:48:40 +00002044 FrontendOpts.ShowMacrosInCodeCompletion
2045 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002046 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002047 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2048 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002049 FrontendOpts.CodeCompletionAt.FileName = File;
2050 FrontendOpts.CodeCompletionAt.Line = Line;
2051 FrontendOpts.CodeCompletionAt.Column = Column;
2052
2053 // Set the language options appropriately.
Ted Kremenek5e14d392011-03-21 18:40:17 +00002054 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002055
Ted Kremenek84de4a12011-03-21 18:40:07 +00002056 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2057
2058 // Recover resources if we crash before exiting this method.
2059 llvm::CrashRecoveryContextCleanupRegistrar
2060 CICleanup(llvm::CrashRecoveryContextCleanup::
2061 create<CompilerInstance>(Clang.get()));
2062
Ted Kremenek5e14d392011-03-21 18:40:17 +00002063 Clang->setInvocation(&*CCInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002064 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002065
2066 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002067 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002068 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002069 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002070 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002071 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002072
2073 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002074 Clang->getTargetOpts().Features = TargetFeatures;
2075 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2076 Clang->getTargetOpts()));
2077 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002078 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002079 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002080 }
2081
2082 // Inform the target of the language options.
2083 //
2084 // FIXME: We shouldn't need to do this, the target should be immutable once
2085 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002086 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002087
Ted Kremenek84de4a12011-03-21 18:40:07 +00002088 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002089 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002090 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002091 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002092 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002093 "IR inputs not support here!");
2094
2095
2096 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002097 Clang->setFileManager(&FileMgr);
2098 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002099
2100 // Remap files.
2101 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002102 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002103 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002104 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2105 if (const llvm::MemoryBuffer *
2106 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2107 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2108 OwnedBuffers.push_back(memBuf);
2109 } else {
2110 const char *fname = fileOrBuf.get<const char *>();
2111 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2112 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002113 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002114
Douglas Gregorb14904c2010-08-13 22:48:40 +00002115 // Use the code completion consumer we were given, but adding any cached
2116 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002117 AugmentedCodeCompleteConsumer *AugmentedConsumer
2118 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2119 FrontendOpts.ShowMacrosInCodeCompletion,
2120 FrontendOpts.ShowCodePatternsInCodeCompletion,
2121 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002122 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002123
Douglas Gregor028d3e42010-08-09 20:45:32 +00002124 // If we have a precompiled preamble, try to use it. We only allow
2125 // the use of the precompiled preamble if we're if the completion
2126 // point is within the main file, after the end of the precompiled
2127 // preamble.
2128 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2129 if (!PreambleFile.empty()) {
2130 using llvm::sys::FileStatus;
2131 llvm::sys::PathWithStatus CompleteFilePath(File);
2132 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2133 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2134 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2135 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00002136 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002137 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002138 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002139 }
2140
2141 // If the main file has been overridden due to the use of a preamble,
2142 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002143 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002144 StoredDiagnostics.insert(StoredDiagnostics.end(),
2145 this->StoredDiagnostics.begin(),
2146 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002147 if (OverrideMainBuffer) {
2148 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2149 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2150 PreprocessorOpts.PrecompiledPreambleBytes.second
2151 = PreambleEndsAtStartOfLine;
2152 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2153 PreprocessorOpts.DisablePCHValidation = true;
2154
2155 // The stored diagnostics have the old source manager. Copy them
2156 // to our output set of stored diagnostics, updating the source
2157 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002158 for (unsigned I = NumStoredDiagnosticsFromDriver,
2159 N = this->StoredDiagnostics.size();
2160 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002161 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
2162 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
2163 StoredDiagnostics[I].setLocation(Loc);
2164 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002165
Douglas Gregorb97b6662010-08-20 00:59:43 +00002166 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002167 } else {
2168 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2169 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002170 }
2171
Douglas Gregor8e984da2010-08-04 16:47:14 +00002172 llvm::OwningPtr<SyntaxOnlyAction> Act;
2173 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002174 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2175 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002176 Act->Execute();
2177 Act->EndSourceFile();
2178 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002179}
Douglas Gregore9386682010-08-13 05:36:37 +00002180
2181bool ASTUnit::Save(llvm::StringRef File) {
2182 if (getDiagnostics().hasErrorOccurred())
2183 return true;
2184
2185 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2186 // unconditionally create a stat cache when we parse the file?
2187 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00002188 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2189 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00002190 if (!ErrorInfo.empty() || Out.has_error())
2191 return true;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002192
2193 serialize(Out);
2194 Out.close();
2195 return Out.has_error();
2196}
2197
2198bool ASTUnit::serialize(llvm::raw_ostream &OS) {
2199 if (getDiagnostics().hasErrorOccurred())
2200 return true;
2201
Douglas Gregore9386682010-08-13 05:36:37 +00002202 std::vector<unsigned char> Buffer;
2203 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002204 ASTWriter Writer(Stream);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002205 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregore9386682010-08-13 05:36:37 +00002206
2207 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002208 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002209 OS.write((char *)&Buffer.front(), Buffer.size());
2210
2211 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002212}