blob: 7e144ee9a15a57645e6f712e5021a17bda4028fd [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Douglas Gregor89d99802010-11-30 06:16:57 +000032#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000048#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000049#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000050#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000051#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000052using namespace clang;
53
Douglas Gregor213f18b2010-10-28 15:44:59 +000054using llvm::TimeRecord;
55
56namespace {
57 class SimpleTimer {
58 bool WantTiming;
59 TimeRecord Start;
60 std::string Output;
61
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000063 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 }
67
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 void setOutput(const llvm::Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000070 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 }
72
Douglas Gregor213f18b2010-10-28 15:44:59 +000073 ~SimpleTimer() {
74 if (WantTiming) {
75 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 Elapsed -= Start;
77 llvm::errs() << Output << ':';
78 Elapsed.print(Elapsed, llvm::errs());
79 llvm::errs() << '\n';
80 }
81 }
82 };
83}
84
Douglas Gregoreababfb2010-08-04 05:53:38 +000085/// \brief After failing to build a precompiled preamble (due to
86/// errors in the source that occurs in the preamble), the number of
87/// reparses during which we'll skip even trying to precompile the
88/// preamble.
89const unsigned DefaultPreambleRebuildInterval = 5;
90
Douglas Gregore3c60a72010-11-17 00:13:31 +000091/// \brief Tracks the number of ASTUnit objects that are currently active.
92///
93/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000094static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000095
Douglas Gregor3687e9d2010-04-05 21:10:19 +000096ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +000097 : OnlyLocalDecls(false), CaptureDiagnostics(false),
98 MainFileIsAST(_MainFileIsAST),
Douglas Gregor213f18b2010-10-28 15:44:59 +000099 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000100 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000101 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000102 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +0000103 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000104 ShouldCacheCodeCompletionResults(false),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000105 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000106 CompletionCacheTopLevelHashValue(0),
107 PreambleTopLevelHashValue(0),
108 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000109 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000110 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000111 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000112 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
113 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000114}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000115
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000116ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000117 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000118 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000119 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000120 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000121
122 // Free the buffers associated with remapped files. We are required to
123 // perform this operation here because we explicitly request that the
124 // compiler instance *not* free these buffers for each invocation of the
125 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000126 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000127 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
128 for (PreprocessorOptions::remapped_file_buffer_iterator
129 FB = PPOpts.remapped_file_buffer_begin(),
130 FBEnd = PPOpts.remapped_file_buffer_end();
131 FB != FBEnd;
132 ++FB)
133 delete FB->second;
134 }
Douglas Gregor28233422010-07-27 14:52:07 +0000135
136 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000137 delete PreambleBuffer;
138
Douglas Gregor213f18b2010-10-28 15:44:59 +0000139 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000140
141 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000142 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000143 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
144 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000145}
146
147void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000148 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
149 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000150 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000151}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000152
Douglas Gregor8071e422010-08-15 06:18:01 +0000153/// \brief Determine the set of code-completion contexts in which this
154/// declaration should be shown.
155static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000156 const LangOptions &LangOpts,
157 bool &IsNestedNameSpecifier) {
158 IsNestedNameSpecifier = false;
159
Douglas Gregor8071e422010-08-15 06:18:01 +0000160 if (isa<UsingShadowDecl>(ND))
161 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
162 if (!ND)
163 return 0;
164
165 unsigned Contexts = 0;
166 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
167 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
168 // Types can appear in these contexts.
169 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
170 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
171 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
172 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
173 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000174 | (1 << (CodeCompletionContext::CCC_Type - 1))
175 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000176
177 // In C++, types can appear in expressions contexts (for functional casts).
178 if (LangOpts.CPlusPlus)
179 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
180
181 // In Objective-C, message sends can send interfaces. In Objective-C++,
182 // all types are available due to functional casts.
183 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
184 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000185
186 // In Objective-C, you can only be a subclass of another Objective-C class
187 if (isa<ObjCInterfaceDecl>(ND))
188 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCSuperclass - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000189
190 // Deal with tag names.
191 if (isa<EnumDecl>(ND)) {
192 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
193
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000194 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000195 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000196 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000197 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
198 if (Record->isUnion())
199 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
200 else
201 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
202
Douglas Gregor8071e422010-08-15 06:18:01 +0000203 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000204 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000205 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000206 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000207 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
208 // Values can appear in these contexts.
209 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
210 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000211 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000212 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
213 } else if (isa<ObjCProtocolDecl>(ND)) {
214 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000215 } else if (isa<ObjCCategoryDecl>(ND)) {
216 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000217 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000218 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000219
220 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000221 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000222 }
223
224 return Contexts;
225}
226
Douglas Gregor87c08a52010-08-13 22:48:40 +0000227void ASTUnit::CacheCodeCompletionResults() {
228 if (!TheSema)
229 return;
230
Douglas Gregor213f18b2010-10-28 15:44:59 +0000231 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000232 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000233
234 // Clear out the previous results.
235 ClearCachedCompletionResults();
236
237 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000238 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000239 llvm::SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000240 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
241 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000242
243 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000244 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
245
Douglas Gregor87c08a52010-08-13 22:48:40 +0000246 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
247 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000248 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000249 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000250 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000251 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000252 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000253 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000254 Ctx->getLangOptions(),
255 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000256 CachedResult.Priority = Results[I].Priority;
257 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000258 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000259
Douglas Gregorf5586f62010-08-16 18:08:11 +0000260 // Keep track of the type of this completion in an ASTContext-agnostic
261 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000262 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000263 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000264 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000265 CachedResult.Type = 0;
266 } else {
267 CanQualType CanUsageType
268 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
269 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
270
271 // Determine whether we have already seen this type. If so, we save
272 // ourselves the work of formatting the type string by using the
273 // temporary, CanQualType-based hash table to find the associated value.
274 unsigned &TypeValue = CompletionTypes[CanUsageType];
275 if (TypeValue == 0) {
276 TypeValue = CompletionTypes.size();
277 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
278 = TypeValue;
279 }
280
281 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000282 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000283
Douglas Gregor8071e422010-08-15 06:18:01 +0000284 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000285
286 /// Handle nested-name-specifiers in C++.
287 if (TheSema->Context.getLangOptions().CPlusPlus &&
288 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
289 // The contexts in which a nested-name-specifier can appear in C++.
290 unsigned NNSContexts
291 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
292 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
293 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
294 | (1 << (CodeCompletionContext::CCC_Statement - 1))
295 | (1 << (CodeCompletionContext::CCC_Expression - 1))
296 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
297 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
298 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
299 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000300 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000301 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
302 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000303
304 if (isa<NamespaceDecl>(Results[I].Declaration) ||
305 isa<NamespaceAliasDecl>(Results[I].Declaration))
306 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
307
308 if (unsigned RemainingContexts
309 = NNSContexts & ~CachedResult.ShowInContexts) {
310 // If there any contexts where this completion can be a
311 // nested-name-specifier but isn't already an option, create a
312 // nested-name-specifier completion.
313 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000314 CachedResult.Completion
315 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000316 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 CachedResult.ShowInContexts = RemainingContexts;
318 CachedResult.Priority = CCP_NestedNameSpecifier;
319 CachedResult.TypeClass = STC_Void;
320 CachedResult.Type = 0;
321 CachedCompletionResults.push_back(CachedResult);
322 }
323 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000324 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 }
326
Douglas Gregor87c08a52010-08-13 22:48:40 +0000327 case Result::RK_Keyword:
328 case Result::RK_Pattern:
329 // Ignore keywords and patterns; we don't care, since they are so
330 // easily regenerated.
331 break;
332
333 case Result::RK_Macro: {
334 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000335 CachedResult.Completion
336 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000337 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000338 CachedResult.ShowInContexts
339 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
340 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
341 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
342 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
343 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
344 | (1 << (CodeCompletionContext::CCC_Statement - 1))
345 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000346 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000347 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000348 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000349 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
350 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000351
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352 CachedResult.Priority = Results[I].Priority;
353 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000354 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000355 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000356 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000357 CachedCompletionResults.push_back(CachedResult);
358 break;
359 }
360 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000361 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000362
363 // Save the current top-level hash value.
364 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000365}
366
367void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000368 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000370 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000371}
372
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000373namespace {
374
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000375/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000376/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000377class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000378 LangOptions &LangOpt;
379 HeaderSearch &HSI;
380 std::string &TargetTriple;
381 std::string &Predefines;
382 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000384 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000386public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000387 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000388 std::string &TargetTriple, std::string &Predefines,
389 unsigned &Counter)
390 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
391 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000393 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
394 LangOpt = LangOpts;
395 return false;
396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000398 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000399 TargetTriple = Triple;
400 return false;
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000403 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000404 llvm::StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000405 std::string &SuggestedPredefines,
406 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000407 Predefines = Buffers[0].Data;
408 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
409 Predefines += Buffers[I].Data;
410 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000411 return false;
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000414 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000415 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000418 virtual void ReadCounter(unsigned Value) {
419 Counter = Value;
420 }
421};
422
Douglas Gregora88084b2010-02-18 18:08:43 +0000423class StoredDiagnosticClient : public DiagnosticClient {
424 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
425
426public:
427 explicit StoredDiagnosticClient(
428 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
429 : StoredDiags(StoredDiags) { }
430
431 virtual void HandleDiagnostic(Diagnostic::Level Level,
432 const DiagnosticInfo &Info);
433};
434
435/// \brief RAII object that optionally captures diagnostics, if
436/// there is no diagnostic client to capture them already.
437class CaptureDroppedDiagnostics {
438 Diagnostic &Diags;
439 StoredDiagnosticClient Client;
440 DiagnosticClient *PreviousClient;
441
442public:
443 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000444 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000445 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000446 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000447 if (RequestCapture || Diags.getClient() == 0) {
448 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000449 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000450 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000451 }
452
453 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000454 if (Diags.getClient() == &Client) {
455 Diags.takeClient();
456 Diags.setClient(PreviousClient);
457 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000458 }
459};
460
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000461} // anonymous namespace
462
Douglas Gregora88084b2010-02-18 18:08:43 +0000463void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
464 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000465 // Default implementation (Warnings/errors count).
466 DiagnosticClient::HandleDiagnostic(Level, Info);
467
Douglas Gregora88084b2010-02-18 18:08:43 +0000468 StoredDiags.push_back(StoredDiagnostic(Level, Info));
469}
470
Steve Naroff77accc12009-09-03 18:19:54 +0000471const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000472 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000473}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000474
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000475const std::string &ASTUnit::getASTFileName() {
476 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000477 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000478}
479
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000480llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000481 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000482 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000483 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000484}
485
Douglas Gregore47be3e2010-11-11 00:39:14 +0000486/// \brief Configure the diagnostics object for use with ASTUnit.
487void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000488 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000489 ASTUnit &AST, bool CaptureDiagnostics) {
490 if (!Diags.getPtr()) {
491 // No diagnostics engine was provided, so create our own diagnostics object
492 // with the default options.
493 DiagnosticOptions DiagOpts;
494 DiagnosticClient *Client = 0;
495 if (CaptureDiagnostics)
496 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000497 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
498 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000499 } else if (CaptureDiagnostics) {
500 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
501 }
502}
503
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000504ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000505 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000506 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000507 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000508 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000509 unsigned NumRemappedFiles,
510 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000511 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000512
513 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000514 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
515 ASTUnitCleanup(AST.get());
516 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
517 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
518 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000519
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000520 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000521
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000522 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000523 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000524 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000525 AST->FileMgr = new FileManager(FileSystemOpts);
526 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
527 AST->getFileManager());
Chris Lattner39b49bc2010-11-23 08:35:12 +0000528 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000529
Douglas Gregor4db64a42010-01-23 00:14:00 +0000530 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000531 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
532 if (const llvm::MemoryBuffer *
533 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
534 // Create the file entry for the file that we're mapping from.
535 const FileEntry *FromFile
536 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
537 memBuf->getBufferSize(),
538 0);
539 if (!FromFile) {
540 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
541 << RemappedFiles[I].first;
542 delete memBuf;
543 continue;
544 }
545
546 // Override the contents of the "from" file with the contents of
547 // the "to" file.
548 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
549
550 } else {
551 const char *fname = fileOrBuf.get<const char *>();
552 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
553 if (!ToFile) {
554 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
555 << RemappedFiles[I].first << fname;
556 continue;
557 }
558
559 // Create the file entry for the file that we're mapping from.
560 const FileEntry *FromFile
561 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
562 ToFile->getSize(),
563 0);
564 if (!FromFile) {
565 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
566 << RemappedFiles[I].first;
567 delete memBuf;
568 continue;
569 }
570
571 // Override the contents of the "from" file with the contents of
572 // the "to" file.
573 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000574 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000575 }
576
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000577 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000579 LangOptions LangInfo;
580 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
581 std::string TargetTriple;
582 std::string Predefines;
583 unsigned Counter;
584
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000585 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000586
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000587 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000588 AST->getDiagnostics()));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000589
590 // Recover resources if we crash before exiting this method.
591 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
592 ReaderCleanup(Reader.get());
593
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000594 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000595 Predefines, Counter));
596
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000597 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000598 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000599 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000601 case ASTReader::Failure:
602 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000603 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000604 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000605 }
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000607 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
608
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000609 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000611 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000612 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000613 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000614 TargetOptions TargetOpts;
615 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000616 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000617 TargetOpts.CPU = "";
618 TargetOpts.Features.clear();
619 TargetOpts.Triple = TargetTriple;
Ted Kremenek4f327862011-03-21 18:40:17 +0000620 AST->Target = TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
621 TargetOpts);
622 AST->PP = new Preprocessor(AST->getDiagnostics(), LangInfo, *AST->Target,
623 AST->getSourceManager(), HeaderInfo);
624 Preprocessor &PP = *AST->PP;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000625
Daniel Dunbard5b61262009-09-21 03:03:47 +0000626 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000627 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000628 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000630 // Create and initialize the ASTContext.
631
Ted Kremenek4f327862011-03-21 18:40:17 +0000632 AST->Ctx = new ASTContext(LangInfo,
633 AST->getSourceManager(),
634 *AST->Target,
635 PP.getIdentifierTable(),
636 PP.getSelectorTable(),
637 PP.getBuiltinInfo(),
638 /* size_reserve = */0);
639 ASTContext &Context = *AST->Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Daniel Dunbarcc318932009-09-03 05:59:35 +0000641 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000643 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000644 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000645 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000646 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000647 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000648
649 // Unregister the cleanup for ASTReader. It will get cleaned up
650 // by the ASTUnit cleanup.
651 ReaderCleanup.unregister();
652
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000653 Context.setExternalSource(Source);
654
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000655 // Create an AST consumer, even though it isn't used.
656 AST->Consumer.reset(new ASTConsumer);
657
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000658 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000659 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
660 AST->TheSema->Initialize();
661 ReaderPtr->InitializeSema(*AST->TheSema);
662
Mike Stump1eb44332009-09-09 15:08:12 +0000663 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000664}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000665
666namespace {
667
Douglas Gregor9b7db622011-02-16 18:16:54 +0000668/// \brief Preprocessor callback class that updates a hash value with the names
669/// of all macros that have been defined by the translation unit.
670class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
671 unsigned &Hash;
672
673public:
674 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
675
676 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
677 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
678 }
679};
680
681/// \brief Add the given declaration to the hash of all top-level entities.
682void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
683 if (!D)
684 return;
685
686 DeclContext *DC = D->getDeclContext();
687 if (!DC)
688 return;
689
690 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
691 return;
692
693 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
694 if (ND->getIdentifier())
695 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
696 else if (DeclarationName Name = ND->getDeclName()) {
697 std::string NameStr = Name.getAsString();
698 Hash = llvm::HashString(NameStr, Hash);
699 }
700 return;
701 }
702
703 if (ObjCForwardProtocolDecl *Forward
704 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
705 for (ObjCForwardProtocolDecl::protocol_iterator
706 P = Forward->protocol_begin(),
707 PEnd = Forward->protocol_end();
708 P != PEnd; ++P)
709 AddTopLevelDeclarationToHash(*P, Hash);
710 return;
711 }
712
713 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) {
714 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
715 I != IEnd; ++I)
716 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
717 return;
718 }
719}
720
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000721class TopLevelDeclTrackerConsumer : public ASTConsumer {
722 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000723 unsigned &Hash;
724
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000725public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000726 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
727 : Unit(_Unit), Hash(Hash) {
728 Hash = 0;
729 }
730
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000731 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000732 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
733 Decl *D = *it;
734 // FIXME: Currently ObjC method declarations are incorrectly being
735 // reported as top-level declarations, even though their DeclContext
736 // is the containing ObjC @interface/@implementation. This is a
737 // fundamental problem in the parser right now.
738 if (isa<ObjCMethodDecl>(D))
739 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000740
741 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000742 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000743 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000744 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000745
746 // We're not interested in "interesting" decls.
747 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000748};
749
750class TopLevelDeclTrackerAction : public ASTFrontendAction {
751public:
752 ASTUnit &Unit;
753
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000754 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
755 llvm::StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000756 CI.getPreprocessor().addPPCallbacks(
757 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
758 return new TopLevelDeclTrackerConsumer(Unit,
759 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000760 }
761
762public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000763 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
764
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000765 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000766 virtual bool usesCompleteTranslationUnit() {
767 return Unit.isCompleteTranslationUnit();
768 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000769};
770
Douglas Gregor89d99802010-11-30 06:16:57 +0000771class PrecompilePreambleConsumer : public PCHGenerator,
772 public ASTSerializationListener {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000773 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000774 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000775 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000776
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000777public:
778 PrecompilePreambleConsumer(ASTUnit &Unit,
779 const Preprocessor &PP, bool Chaining,
780 const char *isysroot, llvm::raw_ostream *Out)
Douglas Gregor9b7db622011-02-16 18:16:54 +0000781 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
782 Hash(Unit.getCurrentTopLevelHashValue()) {
783 Hash = 0;
784 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000785
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000786 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000787 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
788 Decl *D = *it;
789 // FIXME: Currently ObjC method declarations are incorrectly being
790 // reported as top-level declarations, even though their DeclContext
791 // is the containing ObjC @interface/@implementation. This is a
792 // fundamental problem in the parser right now.
793 if (isa<ObjCMethodDecl>(D))
794 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000795 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000796 TopLevelDecls.push_back(D);
797 }
798 }
799
800 virtual void HandleTranslationUnit(ASTContext &Ctx) {
801 PCHGenerator::HandleTranslationUnit(Ctx);
802 if (!Unit.getDiagnostics().hasErrorOccurred()) {
803 // Translate the top-level declarations we captured during
804 // parsing into declaration IDs in the precompiled
805 // preamble. This will allow us to deserialize those top-level
806 // declarations when requested.
807 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
808 Unit.addTopLevelDeclFromPreamble(
809 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000810 }
811 }
Douglas Gregor89d99802010-11-30 06:16:57 +0000812
813 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
814 uint64_t Offset) {
815 Unit.addPreprocessedEntityFromPreamble(Offset);
816 }
817
818 virtual ASTSerializationListener *GetASTSerializationListener() {
819 return this;
820 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000821};
822
823class PrecompilePreambleAction : public ASTFrontendAction {
824 ASTUnit &Unit;
825
826public:
827 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
828
829 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
830 llvm::StringRef InFile) {
831 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000832 std::string OutputFile;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000833 llvm::raw_ostream *OS = 0;
834 bool Chaining;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000835 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
836 OutputFile,
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000837 OS, Chaining))
838 return 0;
839
840 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
841 Sysroot.c_str() : 0;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000842 CI.getPreprocessor().addPPCallbacks(
843 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000844 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
845 isysroot, OS);
846 }
847
848 virtual bool hasCodeCompletionSupport() const { return false; }
849 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000850 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000851};
852
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000853}
854
Douglas Gregorabc563f2010-07-19 21:46:24 +0000855/// Parse the source file into a translation unit using the given compiler
856/// invocation, replacing the current translation unit.
857///
858/// \returns True if a failure occurred that causes the ASTUnit not to
859/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000860bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000861 delete SavedMainFileBuffer;
862 SavedMainFileBuffer = 0;
863
Ted Kremenek4f327862011-03-21 18:40:17 +0000864 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000865 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000866 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000867 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000868
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000869 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000870 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
871
872 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000873 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
874 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000875
Ted Kremenek4f327862011-03-21 18:40:17 +0000876 Clang->setInvocation(&*Invocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +0000877 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000878
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000879 // Set up diagnostics, capturing any diagnostics that would
880 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000881 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000882
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000883 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000884 Clang->getTargetOpts().Features = TargetFeatures;
885 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000886 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +0000887 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000888 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000889 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000890 }
891
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000892 // Inform the target of the language options.
893 //
894 // FIXME: We shouldn't need to do this, the target should be immutable once
895 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000896 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000897
Ted Kremenek03201fb2011-03-21 18:40:07 +0000898 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000899 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000900 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000901 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000902 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000903 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000904
Douglas Gregorabc563f2010-07-19 21:46:24 +0000905 // Configure the various subsystems.
906 // FIXME: Should we retain the previous file manager?
Ted Kremenek03201fb2011-03-21 18:40:07 +0000907 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +0000908 FileMgr = new FileManager(FileSystemOpts);
909 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000910 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +0000911 Ctx = 0;
912 PP = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000913
914 // Clear out old caches and data.
915 TopLevelDecls.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000916 PreprocessedEntities.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000917 CleanTemporaryFiles();
918 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000919
Douglas Gregorf128fed2010-08-20 00:02:33 +0000920 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000921 StoredDiagnostics.erase(
922 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
923 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000924 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000925 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000926 }
927
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000928 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000929 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000930
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000931 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000932 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000933
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000934 // If the main file has been overridden due to the use of a preamble,
935 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000936 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +0000937 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
938 = NestedMacroExpansions;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000939 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000940 if (OverrideMainBuffer) {
941 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
942 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
943 PreprocessorOpts.PrecompiledPreambleBytes.second
944 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000945 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000946 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000947 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000948
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000949 // The stored diagnostic has the old source manager in it; update
950 // the locations to refer into the new source manager. Since we've
951 // been careful to make sure that the source manager's state
952 // before and after are identical, so that we can reuse the source
953 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000954 for (unsigned I = NumStoredDiagnosticsFromDriver,
955 N = StoredDiagnostics.size();
956 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000957 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
958 getSourceManager());
959 StoredDiagnostics[I].setLocation(Loc);
960 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000961
962 // Keep track of the override buffer;
963 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000964 } else {
965 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
966 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000967 }
968
Ted Kremenek25a11e12011-03-22 01:15:24 +0000969 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
970 new TopLevelDeclTrackerAction(*this));
971
972 // Recover resources if we crash before exiting this method.
973 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
974 ActCleanup(Act.get());
975
Ted Kremenek03201fb2011-03-21 18:40:07 +0000976 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
977 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000978 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000979
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000980 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000981
Ted Kremenek4f327862011-03-21 18:40:17 +0000982 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000983 TheSema.reset(Clang->takeSema());
984 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +0000985 Ctx = &Clang->getASTContext();
986 PP = &Clang->getPreprocessor();
987 Clang->setSourceManager(0);
988 Clang->setFileManager(0);
989 Target = &Clang->getTarget();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000990
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000991 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000992
993 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000994 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000995 PreprocessorOpts.eraseRemappedFile(
996 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000997 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
998 }
999
Douglas Gregorabc563f2010-07-19 21:46:24 +00001000 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001001
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001002error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001003 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001004 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001005 PreprocessorOpts.eraseRemappedFile(
1006 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001007 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +00001008 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001009 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001010 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001011
Douglas Gregord54eb442010-10-12 16:25:54 +00001012 StoredDiagnostics.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001013 return true;
1014}
1015
Douglas Gregor44c181a2010-07-23 00:33:23 +00001016/// \brief Simple function to retrieve a path for a preamble precompiled header.
1017static std::string GetPreamblePCHPath() {
1018 // FIXME: This is lame; sys::Path should provide this function (in particular,
1019 // it should know how to find the temporary files dir).
1020 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001021 // FIXME: This is a hack so that we can override the preamble file during
1022 // crash-recovery testing, which is the only case where the preamble files
1023 // are not necessarily cleaned up.
1024 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1025 if (TmpFile)
1026 return TmpFile;
1027
Douglas Gregor44c181a2010-07-23 00:33:23 +00001028 std::string Error;
1029 const char *TmpDir = ::getenv("TMPDIR");
1030 if (!TmpDir)
1031 TmpDir = ::getenv("TEMP");
1032 if (!TmpDir)
1033 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001034#ifdef LLVM_ON_WIN32
1035 if (!TmpDir)
1036 TmpDir = ::getenv("USERPROFILE");
1037#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001038 if (!TmpDir)
1039 TmpDir = "/tmp";
1040 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001041 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001042 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001043 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001044 if (P.createTemporaryFileOnDisk())
1045 return std::string();
1046
Douglas Gregor44c181a2010-07-23 00:33:23 +00001047 return P.str();
1048}
1049
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001050/// \brief Compute the preamble for the main file, providing the source buffer
1051/// that corresponds to the main file along with a pair (bytes, start-of-line)
1052/// that describes the preamble.
1053std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001054ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1055 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001056 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001057 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001058 CreatedBuffer = false;
1059
Douglas Gregor44c181a2010-07-23 00:33:23 +00001060 // Try to determine if the main file has been remapped, either from the
1061 // command line (to another file) or directly through the compiler invocation
1062 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001063 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001064 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1065 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1066 // Check whether there is a file-file remapping of the main file
1067 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001068 M = PreprocessorOpts.remapped_file_begin(),
1069 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001070 M != E;
1071 ++M) {
1072 llvm::sys::PathWithStatus MPath(M->first);
1073 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1074 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1075 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001076 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001077 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001078 CreatedBuffer = false;
1079 }
1080
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001081 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001082 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001083 return std::make_pair((llvm::MemoryBuffer*)0,
1084 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001085 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001086 }
1087 }
1088 }
1089
1090 // Check whether there is a file-buffer remapping. It supercedes the
1091 // file-file remapping.
1092 for (PreprocessorOptions::remapped_file_buffer_iterator
1093 M = PreprocessorOpts.remapped_file_buffer_begin(),
1094 E = PreprocessorOpts.remapped_file_buffer_end();
1095 M != E;
1096 ++M) {
1097 llvm::sys::PathWithStatus MPath(M->first);
1098 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1099 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1100 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001101 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001102 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001103 CreatedBuffer = false;
1104 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001105
Douglas Gregor175c4a92010-07-23 23:58:40 +00001106 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001107 }
1108 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001109 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001110 }
1111
1112 // If the main source file was not remapped, load it now.
1113 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001114 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001115 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001116 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001117
1118 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001119 }
1120
Douglas Gregordf95a132010-08-09 20:45:32 +00001121 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001122}
1123
Douglas Gregor754f3492010-07-24 00:38:13 +00001124static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001125 unsigned NewSize,
1126 llvm::StringRef NewName) {
1127 llvm::MemoryBuffer *Result
1128 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1129 memcpy(const_cast<char*>(Result->getBufferStart()),
1130 Old->getBufferStart(), Old->getBufferSize());
1131 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001132 ' ', NewSize - Old->getBufferSize() - 1);
1133 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001134
Douglas Gregor754f3492010-07-24 00:38:13 +00001135 return Result;
1136}
1137
Douglas Gregor175c4a92010-07-23 23:58:40 +00001138/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1139/// the source file.
1140///
1141/// This routine will compute the preamble of the main source file. If a
1142/// non-trivial preamble is found, it will precompile that preamble into a
1143/// precompiled header so that the precompiled preamble can be used to reduce
1144/// reparsing time. If a precompiled preamble has already been constructed,
1145/// this routine will determine if it is still valid and, if so, avoid
1146/// rebuilding the precompiled preamble.
1147///
Douglas Gregordf95a132010-08-09 20:45:32 +00001148/// \param AllowRebuild When true (the default), this routine is
1149/// allowed to rebuild the precompiled preamble if it is found to be
1150/// out-of-date.
1151///
1152/// \param MaxLines When non-zero, the maximum number of lines that
1153/// can occur within the preamble.
1154///
Douglas Gregor754f3492010-07-24 00:38:13 +00001155/// \returns If the precompiled preamble can be used, returns a newly-allocated
1156/// buffer that should be used in place of the main file when doing so.
1157/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001158llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001159 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001160 bool AllowRebuild,
1161 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001162
1163 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1164 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1165 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001166 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001167 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001168
1169 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001170 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001171 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001172
Douglas Gregor73fc9122010-11-16 20:45:51 +00001173 // If ComputePreamble() Take ownership of the
1174 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1175 if (CreatedPreambleBuffer)
1176 OwnedPreambleBuffer.reset(NewPreamble.first);
1177
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001178 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001179 // We couldn't find a preamble in the main source. Clear out the current
1180 // preamble, if we have one. It's obviously no good any more.
1181 Preamble.clear();
1182 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001183 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001184 PreambleFile.clear();
1185 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001186
1187 // The next time we actually see a preamble, precompile it.
1188 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001189 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001190 }
1191
1192 if (!Preamble.empty()) {
1193 // We've previously computed a preamble. Check whether we have the same
1194 // preamble now that we did before, and that there's enough space in
1195 // the main-file buffer within the precompiled preamble to fit the
1196 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001197 if (Preamble.size() == NewPreamble.second.first &&
1198 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001199 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001200 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001201 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001202 // The preamble has not changed. We may be able to re-use the precompiled
1203 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001204
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001205 // Check that none of the files used by the preamble have changed.
1206 bool AnyFileChanged = false;
1207
1208 // First, make a record of those files that have been overridden via
1209 // remapping or unsaved_files.
1210 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1211 for (PreprocessorOptions::remapped_file_iterator
1212 R = PreprocessorOpts.remapped_file_begin(),
1213 REnd = PreprocessorOpts.remapped_file_end();
1214 !AnyFileChanged && R != REnd;
1215 ++R) {
1216 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001217 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001218 // If we can't stat the file we're remapping to, assume that something
1219 // horrible happened.
1220 AnyFileChanged = true;
1221 break;
1222 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001223
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001224 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1225 StatBuf.st_mtime);
1226 }
1227 for (PreprocessorOptions::remapped_file_buffer_iterator
1228 R = PreprocessorOpts.remapped_file_buffer_begin(),
1229 REnd = PreprocessorOpts.remapped_file_buffer_end();
1230 !AnyFileChanged && R != REnd;
1231 ++R) {
1232 // FIXME: Should we actually compare the contents of file->buffer
1233 // remappings?
1234 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1235 0);
1236 }
1237
1238 // Check whether anything has changed.
1239 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1240 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1241 !AnyFileChanged && F != FEnd;
1242 ++F) {
1243 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1244 = OverriddenFiles.find(F->first());
1245 if (Overridden != OverriddenFiles.end()) {
1246 // This file was remapped; check whether the newly-mapped file
1247 // matches up with the previous mapping.
1248 if (Overridden->second != F->second)
1249 AnyFileChanged = true;
1250 continue;
1251 }
1252
1253 // The file was not remapped; check whether it has changed on disk.
1254 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001255 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001256 // If we can't stat the file, assume that something horrible happened.
1257 AnyFileChanged = true;
1258 } else if (StatBuf.st_size != F->second.first ||
1259 StatBuf.st_mtime != F->second.second)
1260 AnyFileChanged = true;
1261 }
1262
1263 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001264 // Okay! We can re-use the precompiled preamble.
1265
1266 // Set the state of the diagnostic object to mimic its state
1267 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001268 // FIXME: This won't catch any #pragma push warning changes that
1269 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001270 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001271 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001272 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001273 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1274 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1275 StoredDiagnostics.erase(
1276 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1277 StoredDiagnostics.end());
1278
1279 // Create a version of the main file buffer that is padded to
1280 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001281 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001282 PreambleReservedSize,
1283 FrontendOpts.Inputs[0].second);
1284 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001285 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001286
1287 // If we aren't allowed to rebuild the precompiled preamble, just
1288 // return now.
1289 if (!AllowRebuild)
1290 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001291
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292 // We can't reuse the previously-computed preamble. Build a new one.
1293 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001294 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001295 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001296 } else if (!AllowRebuild) {
1297 // We aren't allowed to rebuild the precompiled preamble; just
1298 // return now.
1299 return 0;
1300 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001301
1302 // If the preamble rebuild counter > 1, it's because we previously
1303 // failed to build a preamble and we're not yet ready to try
1304 // again. Decrement the counter and return a failure.
1305 if (PreambleRebuildCounter > 1) {
1306 --PreambleRebuildCounter;
1307 return 0;
1308 }
1309
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001310 // Create a temporary file for the precompiled preamble. In rare
1311 // circumstances, this can fail.
1312 std::string PreamblePCHPath = GetPreamblePCHPath();
1313 if (PreamblePCHPath.empty()) {
1314 // Try again next time.
1315 PreambleRebuildCounter = 1;
1316 return 0;
1317 }
1318
Douglas Gregor175c4a92010-07-23 23:58:40 +00001319 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001320 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001321 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001322
1323 // Create a new buffer that stores the preamble. The buffer also contains
1324 // extra space for the original contents of the file (which will be present
1325 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001326 // grows.
1327 PreambleReservedSize = NewPreamble.first->getBufferSize();
1328 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001329 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001330 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001331 PreambleReservedSize *= 2;
1332
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001333 // Save the preamble text for later; we'll need to compare against it for
1334 // subsequent reparses.
1335 Preamble.assign(NewPreamble.first->getBufferStart(),
1336 NewPreamble.first->getBufferStart()
1337 + NewPreamble.second.first);
1338 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1339
Douglas Gregor671947b2010-08-19 01:33:06 +00001340 delete PreambleBuffer;
1341 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001342 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001343 FrontendOpts.Inputs[0].second);
1344 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001345 NewPreamble.first->getBufferStart(), Preamble.size());
1346 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001347 ' ', PreambleReservedSize - Preamble.size() - 1);
1348 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001349
1350 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001351 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001352 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1353
1354 // Tell the compiler invocation to generate a temporary precompiled header.
1355 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001356 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001357 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001358 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001359 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1360 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001361
1362 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001363 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1364
1365 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001366 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1367 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001368
Douglas Gregor01b6e312011-07-01 18:22:13 +00001369 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001370 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001371
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001372 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001373 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001374
1375 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001376 Clang->getTargetOpts().Features = TargetFeatures;
1377 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1378 Clang->getTargetOpts()));
1379 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001380 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1381 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001382 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001383 PreprocessorOpts.eraseRemappedFile(
1384 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001385 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001386 }
1387
1388 // Inform the target of the language options.
1389 //
1390 // FIXME: We shouldn't need to do this, the target should be immutable once
1391 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001392 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001393
Ted Kremenek03201fb2011-03-21 18:40:07 +00001394 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001395 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001396 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001397 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001398 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001399 "IR inputs not support here!");
1400
1401 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001402 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001403 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001404 StoredDiagnostics.erase(
1405 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1406 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001407 TopLevelDecls.clear();
1408 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001409 PreprocessedEntities.clear();
1410 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001411
1412 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001413 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001414
1415 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001416 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001417 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001418
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001419 llvm::OwningPtr<PrecompilePreambleAction> Act;
1420 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001421 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1422 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001423 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1424 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001425 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001426 PreprocessorOpts.eraseRemappedFile(
1427 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001428 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001429 }
1430
1431 Act->Execute();
1432 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001433
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001434 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001435 // There were errors parsing the preamble, so no precompiled header was
1436 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001437 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001438 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1439 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001440 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001441 PreprocessedEntities.clear();
1442 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001443 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001444 PreprocessorOpts.eraseRemappedFile(
1445 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001446 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001447 }
1448
1449 // Keep track of the preamble we precompiled.
1450 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001451 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1452 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001453
1454 // Keep track of all of the files that the source manager knows about,
1455 // so we can verify whether they have changed or not.
1456 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001457 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001458 const llvm::MemoryBuffer *MainFileBuffer
1459 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1460 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1461 FEnd = SourceMgr.fileinfo_end();
1462 F != FEnd;
1463 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001464 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001465 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1466 continue;
1467
1468 FilesInPreamble[File->getName()]
1469 = std::make_pair(F->second->getSize(), File->getModificationTime());
1470 }
1471
Douglas Gregoreababfb2010-08-04 05:53:38 +00001472 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001473 PreprocessorOpts.eraseRemappedFile(
1474 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001475
1476 // If the hash of top-level entities differs from the hash of the top-level
1477 // entities the last time we rebuilt the preamble, clear out the completion
1478 // cache.
1479 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1480 CompletionCacheTopLevelHashValue = 0;
1481 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1482 }
1483
Douglas Gregor754f3492010-07-24 00:38:13 +00001484 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001485 PreambleReservedSize,
1486 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001487}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001488
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001489void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1490 std::vector<Decl *> Resolved;
1491 Resolved.reserve(TopLevelDeclsInPreamble.size());
1492 ExternalASTSource &Source = *getASTContext().getExternalSource();
1493 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1494 // Resolve the declaration ID to an actual declaration, possibly
1495 // deserializing the declaration in the process.
1496 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1497 if (D)
1498 Resolved.push_back(D);
1499 }
1500 TopLevelDeclsInPreamble.clear();
1501 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1502}
1503
Douglas Gregor89d99802010-11-30 06:16:57 +00001504void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1505 if (!PP)
1506 return;
1507
1508 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1509 if (!PPRec)
1510 return;
1511
1512 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1513 if (!External)
1514 return;
1515
1516 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1517 if (PreprocessedEntity *PE
Douglas Gregor0a480292011-02-11 19:46:30 +00001518 = External->ReadPreprocessedEntityAtOffset(
1519 PreprocessedEntitiesInPreamble[I]))
Douglas Gregor89d99802010-11-30 06:16:57 +00001520 PreprocessedEntities.push_back(PE);
1521 }
1522
1523 if (PreprocessedEntities.empty())
1524 return;
1525
1526 PreprocessedEntities.insert(PreprocessedEntities.end(),
1527 PPRec->begin(true), PPRec->end(true));
1528}
1529
1530ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1531 if (!PreprocessedEntitiesInPreamble.empty() &&
1532 PreprocessedEntities.empty())
1533 RealizePreprocessedEntitiesFromPreamble();
1534
1535 if (PreprocessedEntities.empty())
1536 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1537 return PPRec->begin(true);
1538
1539 return PreprocessedEntities.begin();
1540}
1541
1542ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1543 if (!PreprocessedEntitiesInPreamble.empty() &&
1544 PreprocessedEntities.empty())
1545 RealizePreprocessedEntitiesFromPreamble();
1546
1547 if (PreprocessedEntities.empty())
1548 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1549 return PPRec->end(true);
1550
1551 return PreprocessedEntities.end();
1552}
1553
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001554unsigned ASTUnit::getMaxPCHLevel() const {
1555 if (!getOnlyLocalDecls())
1556 return Decl::MaxPCHLevel;
1557
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001558 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001559}
1560
Douglas Gregor213f18b2010-10-28 15:44:59 +00001561llvm::StringRef ASTUnit::getMainFileName() const {
1562 return Invocation->getFrontendOpts().Inputs[0].second;
1563}
1564
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001565ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1566 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1567 llvm::OwningPtr<ASTUnit> AST;
1568 AST.reset(new ASTUnit(false));
1569 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1570 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001571 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001572 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001573 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1574 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001575
1576 return AST.take();
1577}
1578
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001579ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1580 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1581 ASTFrontendAction *Action) {
1582 assert(CI && "A CompilerInvocation is required");
1583
1584 // Create the AST unit.
1585 llvm::OwningPtr<ASTUnit> AST;
1586 AST.reset(new ASTUnit(false));
1587 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1588 AST->Diagnostics = Diags;
1589 AST->OnlyLocalDecls = false;
1590 AST->CaptureDiagnostics = false;
1591 AST->CompleteTranslationUnit = Action ? Action->usesCompleteTranslationUnit()
1592 : true;
1593 AST->ShouldCacheCodeCompletionResults = false;
1594 AST->Invocation = CI;
1595
1596 // Recover resources if we crash before exiting this method.
1597 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1598 ASTUnitCleanup(AST.get());
1599 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1600 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1601 DiagCleanup(Diags.getPtr());
1602
1603 // We'll manage file buffers ourselves.
1604 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1605 CI->getFrontendOpts().DisableFree = false;
1606 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1607
1608 // Save the target features.
1609 AST->TargetFeatures = CI->getTargetOpts().Features;
1610
1611 // Create the compiler instance to use for building the AST.
1612 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1613
1614 // Recover resources if we crash before exiting this method.
1615 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1616 CICleanup(Clang.get());
1617
1618 Clang->setInvocation(CI);
1619 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1620
1621 // Set up diagnostics, capturing any diagnostics that would
1622 // otherwise be dropped.
1623 Clang->setDiagnostics(&AST->getDiagnostics());
1624
1625 // Create the target instance.
1626 Clang->getTargetOpts().Features = AST->TargetFeatures;
1627 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1628 Clang->getTargetOpts()));
1629 if (!Clang->hasTarget())
1630 return 0;
1631
1632 // Inform the target of the language options.
1633 //
1634 // FIXME: We shouldn't need to do this, the target should be immutable once
1635 // created. This complexity should be lifted elsewhere.
1636 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1637
1638 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1639 "Invocation must have exactly one source file!");
1640 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1641 "FIXME: AST inputs not yet supported here!");
1642 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1643 "IR inputs not supported here!");
1644
1645 // Configure the various subsystems.
1646 AST->FileSystemOpts = Clang->getFileSystemOpts();
1647 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1648 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1649 AST->TheSema.reset();
1650 AST->Ctx = 0;
1651 AST->PP = 0;
1652
1653 // Create a file manager object to provide access to and cache the filesystem.
1654 Clang->setFileManager(&AST->getFileManager());
1655
1656 // Create the source manager.
1657 Clang->setSourceManager(&AST->getSourceManager());
1658
1659 ASTFrontendAction *Act = Action;
1660
1661 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1662 if (!Act) {
1663 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1664 Act = TrackerAct.get();
1665 }
1666
1667 // Recover resources if we crash before exiting this method.
1668 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1669 ActCleanup(TrackerAct.get());
1670
1671 if (!Act->BeginSourceFile(*Clang.get(),
1672 Clang->getFrontendOpts().Inputs[0].second,
1673 Clang->getFrontendOpts().Inputs[0].first))
1674 return 0;
1675
1676 Act->Execute();
1677
1678 // Steal the created target, context, and preprocessor.
1679 AST->TheSema.reset(Clang->takeSema());
1680 AST->Consumer.reset(Clang->takeASTConsumer());
1681 AST->Ctx = &Clang->getASTContext();
1682 AST->PP = &Clang->getPreprocessor();
1683 Clang->setSourceManager(0);
1684 Clang->setFileManager(0);
1685 AST->Target = &Clang->getTarget();
1686
1687 Act->EndSourceFile();
1688
1689 return AST.take();
1690}
1691
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001692bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1693 if (!Invocation)
1694 return true;
1695
1696 // We'll manage file buffers ourselves.
1697 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1698 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001699 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001700
Douglas Gregor1aa27302011-01-27 18:02:58 +00001701 // Save the target features.
1702 TargetFeatures = Invocation->getTargetOpts().Features;
1703
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001704 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001705 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001706 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001707 OverrideMainBuffer
1708 = getMainBufferWithPrecompiledPreamble(*Invocation);
1709 }
1710
Douglas Gregor213f18b2010-10-28 15:44:59 +00001711 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001712 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001713
Ted Kremenek25a11e12011-03-22 01:15:24 +00001714 // Recover resources if we crash before exiting this method.
1715 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1716 MemBufferCleanup(OverrideMainBuffer);
1717
Douglas Gregor213f18b2010-10-28 15:44:59 +00001718 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001719}
1720
Douglas Gregorabc563f2010-07-19 21:46:24 +00001721ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1722 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1723 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001724 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001725 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001726 bool CompleteTranslationUnit,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001727 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001728 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001729 // Create the AST unit.
1730 llvm::OwningPtr<ASTUnit> AST;
1731 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001732 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001733 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001734 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001735 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001736 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001737 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001738 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001739 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001740
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001741 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001742 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1743 ASTUnitCleanup(AST.get());
1744 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1745 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1746 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001747
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001748 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001749}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001750
1751ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1752 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001753 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001754 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001755 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001756 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001757 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001758 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001759 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001760 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001761 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001762 bool CacheCodeCompletionResults,
1763 bool CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001764 bool CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001765 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001766 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001767 // No diagnostics engine was provided, so create our own diagnostics object
1768 // with the default options.
1769 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001770 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1771 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001772 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001773
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001774 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1775
Ted Kremenek4f327862011-03-21 18:40:17 +00001776 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001777
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001778 {
Douglas Gregore47be3e2010-11-11 00:39:14 +00001779 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001780 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001781
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001782 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001783 llvm::makeArrayRef(ArgBegin, ArgEnd),
1784 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001785 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001786 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001787 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001788
Douglas Gregor4db64a42010-01-23 00:14:00 +00001789 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001790 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1791 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1792 if (const llvm::MemoryBuffer *
1793 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1794 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1795 } else {
1796 const char *fname = fileOrBuf.get<const char *>();
1797 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1798 }
1799 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001800 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1801 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001802
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001803 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001804 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001805
Douglas Gregor99ba2022010-10-27 17:24:53 +00001806 // Check whether we should precompile the preamble and/or use chained PCH.
1807 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1808 if (CI->getLangOpts().CPlusPlus) {
1809 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1810
1811 if (PrecompilePreamble && !CXXChainedPCH &&
1812 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1813 PrecompilePreamble = false;
1814 }
1815
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001816 // Create the AST unit.
1817 llvm::OwningPtr<ASTUnit> AST;
1818 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001819 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001820 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001821
1822 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001823 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001824 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001825 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001826 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1827 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1828 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1829 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1830 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001831 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001832 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001833
1834 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001835 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1836 ASTUnitCleanup(AST.get());
1837 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1838 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1839 CICleanup(CI.getPtr());
1840 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1841 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1842 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001843
Chris Lattner39b49bc2010-11-23 08:35:12 +00001844 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001845}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001846
1847bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001848 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001849 return true;
1850
Douglas Gregor213f18b2010-10-28 15:44:59 +00001851 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001852 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001853
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001854 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001855 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001856 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001857 for (PreprocessorOptions::remapped_file_buffer_iterator
1858 R = PPOpts.remapped_file_buffer_begin(),
1859 REnd = PPOpts.remapped_file_buffer_end();
1860 R != REnd;
1861 ++R) {
1862 delete R->second;
1863 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001864 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001865 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1866 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1867 if (const llvm::MemoryBuffer *
1868 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1869 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1870 memBuf);
1871 } else {
1872 const char *fname = fileOrBuf.get<const char *>();
1873 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1874 fname);
1875 }
1876 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001877
Douglas Gregoreababfb2010-08-04 05:53:38 +00001878 // If we have a preamble file lying around, or if we might try to
1879 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001880 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001881 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001882 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001883
Douglas Gregorabc563f2010-07-19 21:46:24 +00001884 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001885 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001886 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001887 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1888 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001889
Douglas Gregor175c4a92010-07-23 23:58:40 +00001890 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001891 bool Result = Parse(OverrideMainBuffer);
1892
1893 // If we're caching global code-completion results, and the top-level
1894 // declarations have changed, clear out the code-completion cache.
1895 if (!Result && ShouldCacheCodeCompletionResults &&
1896 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1897 CacheCodeCompletionResults();
1898
Douglas Gregor175c4a92010-07-23 23:58:40 +00001899 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001900}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001901
Douglas Gregor87c08a52010-08-13 22:48:40 +00001902//----------------------------------------------------------------------------//
1903// Code completion
1904//----------------------------------------------------------------------------//
1905
1906namespace {
1907 /// \brief Code completion consumer that combines the cached code-completion
1908 /// results from an ASTUnit with the code-completion results provided to it,
1909 /// then passes the result on to
1910 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001911 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001912 ASTUnit &AST;
1913 CodeCompleteConsumer &Next;
1914
1915 public:
1916 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001917 bool IncludeMacros, bool IncludeCodePatterns,
1918 bool IncludeGlobals)
1919 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001920 Next.isOutputBinary()), AST(AST), Next(Next)
1921 {
1922 // Compute the set of contexts in which we will look when we don't have
1923 // any information about the specific context.
1924 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00001925 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1926 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1927 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1928 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1929 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1930 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1931 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1932 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1933 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1934 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1935 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1936 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1937 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001938
Douglas Gregor87c08a52010-08-13 22:48:40 +00001939 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00001940 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1941 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1942 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00001943 }
1944
1945 virtual void ProcessCodeCompleteResults(Sema &S,
1946 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001947 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001948 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001949
1950 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1951 OverloadCandidate *Candidates,
1952 unsigned NumCandidates) {
1953 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1954 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001955
Douglas Gregordae68752011-02-01 22:57:45 +00001956 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00001957 return Next.getAllocator();
1958 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00001959 };
1960}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001961
Douglas Gregor5f808c22010-08-16 21:18:39 +00001962/// \brief Helper function that computes which global names are hidden by the
1963/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001964static void CalculateHiddenNames(const CodeCompletionContext &Context,
1965 CodeCompletionResult *Results,
1966 unsigned NumResults,
1967 ASTContext &Ctx,
1968 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001969 bool OnlyTagNames = false;
1970 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001971 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001972 case CodeCompletionContext::CCC_TopLevel:
1973 case CodeCompletionContext::CCC_ObjCInterface:
1974 case CodeCompletionContext::CCC_ObjCImplementation:
1975 case CodeCompletionContext::CCC_ObjCIvarList:
1976 case CodeCompletionContext::CCC_ClassStructUnion:
1977 case CodeCompletionContext::CCC_Statement:
1978 case CodeCompletionContext::CCC_Expression:
1979 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001980 case CodeCompletionContext::CCC_DotMemberAccess:
1981 case CodeCompletionContext::CCC_ArrowMemberAccess:
1982 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001983 case CodeCompletionContext::CCC_Namespace:
1984 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001985 case CodeCompletionContext::CCC_Name:
1986 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001987 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001988 case CodeCompletionContext::CCC_ObjCSuperclass:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001989 break;
1990
1991 case CodeCompletionContext::CCC_EnumTag:
1992 case CodeCompletionContext::CCC_UnionTag:
1993 case CodeCompletionContext::CCC_ClassOrStructTag:
1994 OnlyTagNames = true;
1995 break;
1996
1997 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001998 case CodeCompletionContext::CCC_MacroName:
1999 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002000 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002001 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002002 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002003 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002004 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002005 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002006 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002007 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2008 case CodeCompletionContext::CCC_ObjCClassMessage:
2009 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002010 // We're looking for nothing, or we're looking for names that cannot
2011 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002012 return;
2013 }
2014
John McCall0a2c5e22010-08-25 06:19:51 +00002015 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002016 for (unsigned I = 0; I != NumResults; ++I) {
2017 if (Results[I].Kind != Result::RK_Declaration)
2018 continue;
2019
2020 unsigned IDNS
2021 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2022
2023 bool Hiding = false;
2024 if (OnlyTagNames)
2025 Hiding = (IDNS & Decl::IDNS_Tag);
2026 else {
2027 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002028 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2029 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002030 if (Ctx.getLangOptions().CPlusPlus)
2031 HiddenIDNS |= Decl::IDNS_Tag;
2032 Hiding = (IDNS & HiddenIDNS);
2033 }
2034
2035 if (!Hiding)
2036 continue;
2037
2038 DeclarationName Name = Results[I].Declaration->getDeclName();
2039 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2040 HiddenNames.insert(Identifier->getName());
2041 else
2042 HiddenNames.insert(Name.getAsString());
2043 }
2044}
2045
2046
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002047void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2048 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002049 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002050 unsigned NumResults) {
2051 // Merge the results we were given with the results we cached.
2052 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002053 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002054 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00002055 : (1 << (Context.getKind() - 1)));
2056
2057 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002058 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002059 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002060 llvm::SmallVector<Result, 8> AllResults;
2061 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002062 C = AST.cached_completion_begin(),
2063 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002064 C != CEnd; ++C) {
2065 // If the context we are in matches any of the contexts we are
2066 // interested in, we'll add this result.
2067 if ((C->ShowInContexts & InContexts) == 0)
2068 continue;
2069
2070 // If we haven't added any results previously, do so now.
2071 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002072 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2073 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002074 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2075 AddedResult = true;
2076 }
2077
Douglas Gregor5f808c22010-08-16 21:18:39 +00002078 // Determine whether this global completion result is hidden by a local
2079 // completion result. If so, skip it.
2080 if (C->Kind != CXCursor_MacroDefinition &&
2081 HiddenNames.count(C->Completion->getTypedText()))
2082 continue;
2083
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002084 // Adjust priority based on similar type classes.
2085 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002086 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002087 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002088 if (!Context.getPreferredType().isNull()) {
2089 if (C->Kind == CXCursor_MacroDefinition) {
2090 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002091 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002092 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002093 } else if (C->Type) {
2094 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002095 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002096 Context.getPreferredType().getUnqualifiedType());
2097 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2098 if (ExpectedSTC == C->TypeClass) {
2099 // We know this type is similar; check for an exact match.
2100 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002101 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002102 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002103 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002104 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2105 Priority /= CCF_ExactTypeMatch;
2106 else
2107 Priority /= CCF_SimilarTypeMatch;
2108 }
2109 }
2110 }
2111
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002112 // Adjust the completion string, if required.
2113 if (C->Kind == CXCursor_MacroDefinition &&
2114 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2115 // Create a new code-completion string that just contains the
2116 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002117 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2118 C->Availability);
2119 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002120 CursorKind = CXCursor_NotImplemented;
2121 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002122 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002123 }
2124
Douglas Gregor4125c372010-08-25 18:03:13 +00002125 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002126 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002127 }
2128
2129 // If we did not add any cached completion results, just forward the
2130 // results we were given to the next consumer.
2131 if (!AddedResult) {
2132 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2133 return;
2134 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002135
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002136 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2137 AllResults.size());
2138}
2139
2140
2141
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002142void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
2143 RemappedFile *RemappedFiles,
2144 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002145 bool IncludeMacros,
2146 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002147 CodeCompleteConsumer &Consumer,
2148 Diagnostic &Diag, LangOptions &LangOpts,
2149 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00002150 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2151 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002152 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002153 return;
2154
Douglas Gregor213f18b2010-10-28 15:44:59 +00002155 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002156 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2157 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002158
Ted Kremenek4f327862011-03-21 18:40:17 +00002159 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2160 CCInvocation(new CompilerInvocation(*Invocation));
2161
2162 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2163 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002164
Douglas Gregor87c08a52010-08-13 22:48:40 +00002165 FrontendOpts.ShowMacrosInCodeCompletion
2166 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002167 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002168 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2169 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002170 FrontendOpts.CodeCompletionAt.FileName = File;
2171 FrontendOpts.CodeCompletionAt.Line = Line;
2172 FrontendOpts.CodeCompletionAt.Column = Column;
2173
2174 // Set the language options appropriately.
Ted Kremenek4f327862011-03-21 18:40:17 +00002175 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002176
Ted Kremenek03201fb2011-03-21 18:40:07 +00002177 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2178
2179 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002180 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2181 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002182
Ted Kremenek4f327862011-03-21 18:40:17 +00002183 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002184 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002185
2186 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002187 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002188 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002189 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002190 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002191 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002192
2193 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002194 Clang->getTargetOpts().Features = TargetFeatures;
2195 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2196 Clang->getTargetOpts()));
2197 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002198 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002199 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002200 }
2201
2202 // Inform the target of the language options.
2203 //
2204 // FIXME: We shouldn't need to do this, the target should be immutable once
2205 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002206 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002207
Ted Kremenek03201fb2011-03-21 18:40:07 +00002208 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002209 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002210 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002211 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002212 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002213 "IR inputs not support here!");
2214
2215
2216 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002217 Clang->setFileManager(&FileMgr);
2218 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002219
2220 // Remap files.
2221 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002222 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002223 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002224 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2225 if (const llvm::MemoryBuffer *
2226 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2227 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2228 OwnedBuffers.push_back(memBuf);
2229 } else {
2230 const char *fname = fileOrBuf.get<const char *>();
2231 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2232 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002233 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002234
Douglas Gregor87c08a52010-08-13 22:48:40 +00002235 // Use the code completion consumer we were given, but adding any cached
2236 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002237 AugmentedCodeCompleteConsumer *AugmentedConsumer
2238 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2239 FrontendOpts.ShowMacrosInCodeCompletion,
2240 FrontendOpts.ShowCodePatternsInCodeCompletion,
2241 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002242 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002243
Douglas Gregordf95a132010-08-09 20:45:32 +00002244 // If we have a precompiled preamble, try to use it. We only allow
2245 // the use of the precompiled preamble if we're if the completion
2246 // point is within the main file, after the end of the precompiled
2247 // preamble.
2248 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2249 if (!PreambleFile.empty()) {
2250 using llvm::sys::FileStatus;
2251 llvm::sys::PathWithStatus CompleteFilePath(File);
2252 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2253 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2254 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2255 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00002256 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002257 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002258 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002259 }
2260
2261 // If the main file has been overridden due to the use of a preamble,
2262 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002263 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002264 StoredDiagnostics.insert(StoredDiagnostics.end(),
2265 this->StoredDiagnostics.begin(),
2266 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00002267 if (OverrideMainBuffer) {
2268 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2269 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2270 PreprocessorOpts.PrecompiledPreambleBytes.second
2271 = PreambleEndsAtStartOfLine;
2272 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2273 PreprocessorOpts.DisablePCHValidation = true;
2274
2275 // The stored diagnostics have the old source manager. Copy them
2276 // to our output set of stored diagnostics, updating the source
2277 // manager to the one we were given.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002278 for (unsigned I = NumStoredDiagnosticsFromDriver,
2279 N = this->StoredDiagnostics.size();
2280 I < N; ++I) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002281 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
2282 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
2283 StoredDiagnostics[I].setLocation(Loc);
2284 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002285
Douglas Gregor2283d792010-08-20 00:59:43 +00002286 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002287 } else {
2288 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2289 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002290 }
2291
Douglas Gregordca8ee82011-05-06 16:33:08 +00002292 // Disable the preprocessing record
2293 PreprocessorOpts.DetailedRecord = false;
2294
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002295 llvm::OwningPtr<SyntaxOnlyAction> Act;
2296 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002297 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2298 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002299 Act->Execute();
2300 Act->EndSourceFile();
2301 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002302}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002303
Douglas Gregor39c411f2011-07-06 16:43:36 +00002304CXSaveError ASTUnit::Save(llvm::StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002305 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002306 return CXSaveError_TranslationErrors;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002307
2308 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2309 // unconditionally create a stat cache when we parse the file?
2310 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00002311 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2312 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002313 if (!ErrorInfo.empty() || Out.has_error())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002314 return CXSaveError_Unknown;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002315
2316 serialize(Out);
2317 Out.close();
Douglas Gregor39c411f2011-07-06 16:43:36 +00002318 return Out.has_error()? CXSaveError_Unknown : CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002319}
2320
2321bool ASTUnit::serialize(llvm::raw_ostream &OS) {
2322 if (getDiagnostics().hasErrorOccurred())
2323 return true;
2324
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002325 std::vector<unsigned char> Buffer;
2326 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002327 ASTWriter Writer(Stream);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00002328 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002329
2330 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002331 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002332 OS.write((char *)&Buffer.front(), Buffer.size());
2333
2334 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002335}