blob: 97e03266ebe06d1efb48cc91d4ee6443986c39c7 [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"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Douglas Gregor89d99802010-11-30 06:16:57 +000030#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000031#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000034#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000035#include "clang/Basic/TargetInfo.h"
36#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000037#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000038#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000043#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000044#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000045#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000046#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000047using namespace clang;
48
Douglas Gregor213f18b2010-10-28 15:44:59 +000049using llvm::TimeRecord;
50
51namespace {
52 class SimpleTimer {
53 bool WantTiming;
54 TimeRecord Start;
55 std::string Output;
56
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000057 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000058 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000059 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 }
62
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 void setOutput(const llvm::Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 }
67
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 ~SimpleTimer() {
69 if (WantTiming) {
70 TimeRecord Elapsed = TimeRecord::getCurrentTime();
71 Elapsed -= Start;
72 llvm::errs() << Output << ':';
73 Elapsed.print(Elapsed, llvm::errs());
74 llvm::errs() << '\n';
75 }
76 }
77 };
78}
79
Douglas Gregoreababfb2010-08-04 05:53:38 +000080/// \brief After failing to build a precompiled preamble (due to
81/// errors in the source that occurs in the preamble), the number of
82/// reparses during which we'll skip even trying to precompile the
83/// preamble.
84const unsigned DefaultPreambleRebuildInterval = 5;
85
Douglas Gregore3c60a72010-11-17 00:13:31 +000086/// \brief Tracks the number of ASTUnit objects that are currently active.
87///
88/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000089static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000090
Douglas Gregor3687e9d2010-04-05 21:10:19 +000091ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000092 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor213f18b2010-10-28 15:44:59 +000093 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
94 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +000095 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000096 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000097 ShouldCacheCodeCompletionResults(false),
98 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000099 CacheCodeCompletionCoolDown(0),
100 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000101 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000102 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000103 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
104 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000105}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000106
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000107ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000108 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000109 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000110 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000111 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000112
113 // Free the buffers associated with remapped files. We are required to
114 // perform this operation here because we explicitly request that the
115 // compiler instance *not* free these buffers for each invocation of the
116 // parser.
117 if (Invocation.get()) {
118 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
119 for (PreprocessorOptions::remapped_file_buffer_iterator
120 FB = PPOpts.remapped_file_buffer_begin(),
121 FBEnd = PPOpts.remapped_file_buffer_end();
122 FB != FBEnd;
123 ++FB)
124 delete FB->second;
125 }
Douglas Gregor28233422010-07-27 14:52:07 +0000126
127 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000128 delete PreambleBuffer;
129
Douglas Gregor213f18b2010-10-28 15:44:59 +0000130 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000131
132 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000133 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000134 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
135 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000136}
137
138void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000139 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
140 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000141 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000142}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000143
Douglas Gregor8071e422010-08-15 06:18:01 +0000144/// \brief Determine the set of code-completion contexts in which this
145/// declaration should be shown.
146static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000147 const LangOptions &LangOpts,
148 bool &IsNestedNameSpecifier) {
149 IsNestedNameSpecifier = false;
150
Douglas Gregor8071e422010-08-15 06:18:01 +0000151 if (isa<UsingShadowDecl>(ND))
152 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
153 if (!ND)
154 return 0;
155
156 unsigned Contexts = 0;
157 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
158 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
159 // Types can appear in these contexts.
160 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
161 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
162 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
163 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
164 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000165 | (1 << (CodeCompletionContext::CCC_Type - 1))
166 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000167
168 // In C++, types can appear in expressions contexts (for functional casts).
169 if (LangOpts.CPlusPlus)
170 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
171
172 // In Objective-C, message sends can send interfaces. In Objective-C++,
173 // all types are available due to functional casts.
174 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
175 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
176
177 // Deal with tag names.
178 if (isa<EnumDecl>(ND)) {
179 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
180
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000181 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000182 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000183 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000184 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
185 if (Record->isUnion())
186 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
187 else
188 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
189
Douglas Gregor8071e422010-08-15 06:18:01 +0000190 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000192 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000193 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000194 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
195 // Values can appear in these contexts.
196 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
197 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000198 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000199 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
200 } else if (isa<ObjCProtocolDecl>(ND)) {
201 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
202 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000203 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000204
205 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000206 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000207 }
208
209 return Contexts;
210}
211
Douglas Gregor87c08a52010-08-13 22:48:40 +0000212void ASTUnit::CacheCodeCompletionResults() {
213 if (!TheSema)
214 return;
215
Douglas Gregor213f18b2010-10-28 15:44:59 +0000216 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000217 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000218
219 // Clear out the previous results.
220 ClearCachedCompletionResults();
221
222 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000223 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000224 llvm::SmallVector<Result, 8> Results;
225 TheSema->GatherGlobalCodeCompletions(Results);
226
227 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000228 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
229
Douglas Gregor87c08a52010-08-13 22:48:40 +0000230 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
231 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000232 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000233 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000234 CachedCodeCompletionResult CachedResult;
235 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
236 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000237 Ctx->getLangOptions(),
238 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000239 CachedResult.Priority = Results[I].Priority;
240 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000241 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000242
Douglas Gregorf5586f62010-08-16 18:08:11 +0000243 // Keep track of the type of this completion in an ASTContext-agnostic
244 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000245 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000246 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000247 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000248 CachedResult.Type = 0;
249 } else {
250 CanQualType CanUsageType
251 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
252 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
253
254 // Determine whether we have already seen this type. If so, we save
255 // ourselves the work of formatting the type string by using the
256 // temporary, CanQualType-based hash table to find the associated value.
257 unsigned &TypeValue = CompletionTypes[CanUsageType];
258 if (TypeValue == 0) {
259 TypeValue = CompletionTypes.size();
260 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
261 = TypeValue;
262 }
263
264 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000265 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000266
Douglas Gregor8071e422010-08-15 06:18:01 +0000267 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000268
269 /// Handle nested-name-specifiers in C++.
270 if (TheSema->Context.getLangOptions().CPlusPlus &&
271 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
272 // The contexts in which a nested-name-specifier can appear in C++.
273 unsigned NNSContexts
274 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
275 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
276 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
277 | (1 << (CodeCompletionContext::CCC_Statement - 1))
278 | (1 << (CodeCompletionContext::CCC_Expression - 1))
279 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
280 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
281 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
282 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000283 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000284 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
285 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000286
287 if (isa<NamespaceDecl>(Results[I].Declaration) ||
288 isa<NamespaceAliasDecl>(Results[I].Declaration))
289 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
290
291 if (unsigned RemainingContexts
292 = NNSContexts & ~CachedResult.ShowInContexts) {
293 // If there any contexts where this completion can be a
294 // nested-name-specifier but isn't already an option, create a
295 // nested-name-specifier completion.
296 Results[I].StartsNestedNameSpecifier = true;
297 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
298 CachedResult.ShowInContexts = RemainingContexts;
299 CachedResult.Priority = CCP_NestedNameSpecifier;
300 CachedResult.TypeClass = STC_Void;
301 CachedResult.Type = 0;
302 CachedCompletionResults.push_back(CachedResult);
303 }
304 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000305 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000306 }
307
Douglas Gregor87c08a52010-08-13 22:48:40 +0000308 case Result::RK_Keyword:
309 case Result::RK_Pattern:
310 // Ignore keywords and patterns; we don't care, since they are so
311 // easily regenerated.
312 break;
313
314 case Result::RK_Macro: {
315 CachedCodeCompletionResult CachedResult;
316 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
317 CachedResult.ShowInContexts
318 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
319 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
320 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
321 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
322 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
323 | (1 << (CodeCompletionContext::CCC_Statement - 1))
324 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000325 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000326 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000327 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
328 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
329
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000330
Douglas Gregor87c08a52010-08-13 22:48:40 +0000331 CachedResult.Priority = Results[I].Priority;
332 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000333 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000334 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000335 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000336 CachedCompletionResults.push_back(CachedResult);
337 break;
338 }
339 }
340 Results[I].Destroy();
341 }
342
Douglas Gregor727d93e2010-08-17 00:40:40 +0000343 // Make a note of the state when we performed this caching.
344 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345}
346
347void ASTUnit::ClearCachedCompletionResults() {
348 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
349 delete CachedCompletionResults[I].Completion;
350 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000351 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352}
353
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000354namespace {
355
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000356/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000357/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000358class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000359 LangOptions &LangOpt;
360 HeaderSearch &HSI;
361 std::string &TargetTriple;
362 std::string &Predefines;
363 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000365 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000367public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000368 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000369 std::string &TargetTriple, std::string &Predefines,
370 unsigned &Counter)
371 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
372 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000374 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
375 LangOpt = LangOpts;
376 return false;
377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000379 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000380 TargetTriple = Triple;
381 return false;
382 }
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000384 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000385 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000386 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000387 Predefines = Buffers[0].Data;
388 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
389 Predefines += Buffers[I].Data;
390 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000391 return false;
392 }
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000394 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000395 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000398 virtual void ReadCounter(unsigned Value) {
399 Counter = Value;
400 }
401};
402
Douglas Gregora88084b2010-02-18 18:08:43 +0000403class StoredDiagnosticClient : public DiagnosticClient {
404 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
405
406public:
407 explicit StoredDiagnosticClient(
408 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
409 : StoredDiags(StoredDiags) { }
410
411 virtual void HandleDiagnostic(Diagnostic::Level Level,
412 const DiagnosticInfo &Info);
413};
414
415/// \brief RAII object that optionally captures diagnostics, if
416/// there is no diagnostic client to capture them already.
417class CaptureDroppedDiagnostics {
418 Diagnostic &Diags;
419 StoredDiagnosticClient Client;
420 DiagnosticClient *PreviousClient;
421
422public:
423 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000424 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000425 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000426 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000427 if (RequestCapture || Diags.getClient() == 0) {
428 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000429 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000430 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000431 }
432
433 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000434 if (Diags.getClient() == &Client) {
435 Diags.takeClient();
436 Diags.setClient(PreviousClient);
437 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000438 }
439};
440
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000441} // anonymous namespace
442
Douglas Gregora88084b2010-02-18 18:08:43 +0000443void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
444 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000445 // Default implementation (Warnings/errors count).
446 DiagnosticClient::HandleDiagnostic(Level, Info);
447
Douglas Gregora88084b2010-02-18 18:08:43 +0000448 StoredDiags.push_back(StoredDiagnostic(Level, Info));
449}
450
Steve Naroff77accc12009-09-03 18:19:54 +0000451const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000452 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000453}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000454
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000455const std::string &ASTUnit::getASTFileName() {
456 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000457 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000458}
459
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000460llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000461 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000462 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000463 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000464}
465
Douglas Gregore47be3e2010-11-11 00:39:14 +0000466/// \brief Configure the diagnostics object for use with ASTUnit.
467void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
468 ASTUnit &AST, bool CaptureDiagnostics) {
469 if (!Diags.getPtr()) {
470 // No diagnostics engine was provided, so create our own diagnostics object
471 // with the default options.
472 DiagnosticOptions DiagOpts;
473 DiagnosticClient *Client = 0;
474 if (CaptureDiagnostics)
475 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
476 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0, Client);
477 } else if (CaptureDiagnostics) {
478 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
479 }
480}
481
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000482ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000483 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000484 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000485 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000486 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000487 unsigned NumRemappedFiles,
488 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000489 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000490 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000491
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000492 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000493 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000494 AST->Diagnostics = Diags;
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000495 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000496 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000497 AST->getFileManager()));
498 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000499
Douglas Gregor4db64a42010-01-23 00:14:00 +0000500 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
501 // Create the file entry for the file that we're mapping from.
502 const FileEntry *FromFile
503 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
504 RemappedFiles[I].second->getBufferSize(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000505 0);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000506 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000507 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000508 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000509 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000510 continue;
511 }
512
513 // Override the contents of the "from" file with the contents of
514 // the "to" file.
515 AST->getSourceManager().overrideFileContents(FromFile,
516 RemappedFiles[I].second);
517 }
518
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000521 LangOptions LangInfo;
522 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
523 std::string TargetTriple;
524 std::string Predefines;
525 unsigned Counter;
526
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000527 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000528
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000529 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000530 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000531 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000532 Predefines, Counter));
533
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000534 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000535 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000536 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000538 case ASTReader::Failure:
539 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000540 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000541 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000542 }
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000544 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
545
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000546 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000548 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000549 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000550 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000551 TargetOptions TargetOpts;
552 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000553 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000554 TargetOpts.CPU = "";
555 TargetOpts.Features.clear();
556 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000557 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
558 TargetOpts));
559 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
560 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000561 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000562 Preprocessor &PP = *AST->PP.get();
563
Daniel Dunbard5b61262009-09-21 03:03:47 +0000564 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000565 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000566 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000568 // Create and initialize the ASTContext.
569
570 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000571 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000572 *AST->Target.get(),
573 PP.getIdentifierTable(),
574 PP.getSelectorTable(),
575 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000576 /* size_reserve = */0));
577 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Daniel Dunbarcc318932009-09-03 05:59:35 +0000579 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000581 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000582 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000583 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000584 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000585 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000586 Context.setExternalSource(Source);
587
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000588 // Create an AST consumer, even though it isn't used.
589 AST->Consumer.reset(new ASTConsumer);
590
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000591 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000592 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
593 AST->TheSema->Initialize();
594 ReaderPtr->InitializeSema(*AST->TheSema);
595
Mike Stump1eb44332009-09-09 15:08:12 +0000596 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000597}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000598
599namespace {
600
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000601class TopLevelDeclTrackerConsumer : public ASTConsumer {
602 ASTUnit &Unit;
603
604public:
605 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
606
607 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000608 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
609 Decl *D = *it;
610 // FIXME: Currently ObjC method declarations are incorrectly being
611 // reported as top-level declarations, even though their DeclContext
612 // is the containing ObjC @interface/@implementation. This is a
613 // fundamental problem in the parser right now.
614 if (isa<ObjCMethodDecl>(D))
615 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000616 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000617 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000618 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000619
620 // We're not interested in "interesting" decls.
621 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000622};
623
624class TopLevelDeclTrackerAction : public ASTFrontendAction {
625public:
626 ASTUnit &Unit;
627
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000628 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
629 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000630 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000631 }
632
633public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000634 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
635
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000636 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000637 virtual bool usesCompleteTranslationUnit() {
638 return Unit.isCompleteTranslationUnit();
639 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000640};
641
Douglas Gregor89d99802010-11-30 06:16:57 +0000642class PrecompilePreambleConsumer : public PCHGenerator,
643 public ASTSerializationListener {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000644 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000645 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000646
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000647public:
648 PrecompilePreambleConsumer(ASTUnit &Unit,
649 const Preprocessor &PP, bool Chaining,
650 const char *isysroot, llvm::raw_ostream *Out)
651 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
652
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000653 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000654 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
655 Decl *D = *it;
656 // FIXME: Currently ObjC method declarations are incorrectly being
657 // reported as top-level declarations, even though their DeclContext
658 // is the containing ObjC @interface/@implementation. This is a
659 // fundamental problem in the parser right now.
660 if (isa<ObjCMethodDecl>(D))
661 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000662 TopLevelDecls.push_back(D);
663 }
664 }
665
666 virtual void HandleTranslationUnit(ASTContext &Ctx) {
667 PCHGenerator::HandleTranslationUnit(Ctx);
668 if (!Unit.getDiagnostics().hasErrorOccurred()) {
669 // Translate the top-level declarations we captured during
670 // parsing into declaration IDs in the precompiled
671 // preamble. This will allow us to deserialize those top-level
672 // declarations when requested.
673 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
674 Unit.addTopLevelDeclFromPreamble(
675 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000676 }
677 }
Douglas Gregor89d99802010-11-30 06:16:57 +0000678
679 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
680 uint64_t Offset) {
681 Unit.addPreprocessedEntityFromPreamble(Offset);
682 }
683
684 virtual ASTSerializationListener *GetASTSerializationListener() {
685 return this;
686 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000687};
688
689class PrecompilePreambleAction : public ASTFrontendAction {
690 ASTUnit &Unit;
691
692public:
693 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
694
695 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
696 llvm::StringRef InFile) {
697 std::string Sysroot;
698 llvm::raw_ostream *OS = 0;
699 bool Chaining;
700 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
701 OS, Chaining))
702 return 0;
703
704 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
705 Sysroot.c_str() : 0;
706 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
707 isysroot, OS);
708 }
709
710 virtual bool hasCodeCompletionSupport() const { return false; }
711 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000712 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000713};
714
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000715}
716
Douglas Gregorabc563f2010-07-19 21:46:24 +0000717/// Parse the source file into a translation unit using the given compiler
718/// invocation, replacing the current translation unit.
719///
720/// \returns True if a failure occurred that causes the ASTUnit not to
721/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000722bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000723 delete SavedMainFileBuffer;
724 SavedMainFileBuffer = 0;
725
Douglas Gregor671947b2010-08-19 01:33:06 +0000726 if (!Invocation.get()) {
727 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000728 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000729 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000730
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000731 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000732 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000733 Clang.setInvocation(Invocation.take());
734 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
735
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000736 // Set up diagnostics, capturing any diagnostics that would
737 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000738 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000739
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000740 // Create the target instance.
741 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
742 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000743 if (!Clang.hasTarget()) {
744 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000745 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000746 }
747
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000748 // Inform the target of the language options.
749 //
750 // FIXME: We shouldn't need to do this, the target should be immutable once
751 // created. This complexity should be lifted elsewhere.
752 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000753
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000754 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
755 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000756 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000757 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000758 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
759 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000760
Douglas Gregorabc563f2010-07-19 21:46:24 +0000761 // Configure the various subsystems.
762 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000763 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +0000764 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
765 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000766 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000767 Ctx.reset();
768 PP.reset();
769
770 // Clear out old caches and data.
771 TopLevelDecls.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000772 PreprocessedEntities.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000773 CleanTemporaryFiles();
774 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000775
Douglas Gregorf128fed2010-08-20 00:02:33 +0000776 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000777 StoredDiagnostics.erase(
778 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
779 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000780 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000781 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000782 }
783
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000784 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000785 Clang.setFileManager(&getFileManager());
786
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000787 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000788 Clang.setSourceManager(&getSourceManager());
789
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000790 // If the main file has been overridden due to the use of a preamble,
791 // make that override happen and introduce the preamble.
792 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000793 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000794 if (OverrideMainBuffer) {
795 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
796 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
797 PreprocessorOpts.PrecompiledPreambleBytes.second
798 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000799 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000800 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000801 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000802
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000803 // The stored diagnostic has the old source manager in it; update
804 // the locations to refer into the new source manager. Since we've
805 // been careful to make sure that the source manager's state
806 // before and after are identical, so that we can reuse the source
807 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000808 for (unsigned I = NumStoredDiagnosticsFromDriver,
809 N = StoredDiagnostics.size();
810 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000811 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
812 getSourceManager());
813 StoredDiagnostics[I].setLocation(Loc);
814 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000815
816 // Keep track of the override buffer;
817 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000818 } else {
819 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
820 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000821 }
822
Douglas Gregorabc563f2010-07-19 21:46:24 +0000823 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
824 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000825 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000826 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000827 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000828
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000829 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000830
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000831 // Steal the created target, context, and preprocessor, and take back the
832 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000833 TheSema.reset(Clang.takeSema());
834 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000835 Ctx.reset(Clang.takeASTContext());
836 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000837 Clang.takeSourceManager();
838 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000839 Target.reset(Clang.takeTarget());
840
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000841 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000842
843 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000844 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000845 PreprocessorOpts.eraseRemappedFile(
846 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000847 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
848 }
849
Douglas Gregorabc563f2010-07-19 21:46:24 +0000850 Invocation.reset(Clang.takeInvocation());
851 return false;
852
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000853error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000854 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000855 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000856 PreprocessorOpts.eraseRemappedFile(
857 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000858 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000859 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000860 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000861 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000862
Douglas Gregord54eb442010-10-12 16:25:54 +0000863 StoredDiagnostics.clear();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000864 Clang.takeSourceManager();
865 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000866 Invocation.reset(Clang.takeInvocation());
867 return true;
868}
869
Douglas Gregor44c181a2010-07-23 00:33:23 +0000870/// \brief Simple function to retrieve a path for a preamble precompiled header.
871static std::string GetPreamblePCHPath() {
872 // FIXME: This is lame; sys::Path should provide this function (in particular,
873 // it should know how to find the temporary files dir).
874 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000875 // FIXME: This is a hack so that we can override the preamble file during
876 // crash-recovery testing, which is the only case where the preamble files
877 // are not necessarily cleaned up.
878 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
879 if (TmpFile)
880 return TmpFile;
881
Douglas Gregor44c181a2010-07-23 00:33:23 +0000882 std::string Error;
883 const char *TmpDir = ::getenv("TMPDIR");
884 if (!TmpDir)
885 TmpDir = ::getenv("TEMP");
886 if (!TmpDir)
887 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000888#ifdef LLVM_ON_WIN32
889 if (!TmpDir)
890 TmpDir = ::getenv("USERPROFILE");
891#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000892 if (!TmpDir)
893 TmpDir = "/tmp";
894 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000895 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000896 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000897 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000898 if (P.createTemporaryFileOnDisk())
899 return std::string();
900
Douglas Gregor44c181a2010-07-23 00:33:23 +0000901 return P.str();
902}
903
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000904/// \brief Compute the preamble for the main file, providing the source buffer
905/// that corresponds to the main file along with a pair (bytes, start-of-line)
906/// that describes the preamble.
907std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000908ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
909 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000910 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +0000911 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000912 CreatedBuffer = false;
913
Douglas Gregor44c181a2010-07-23 00:33:23 +0000914 // Try to determine if the main file has been remapped, either from the
915 // command line (to another file) or directly through the compiler invocation
916 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000917 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000918 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
919 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
920 // Check whether there is a file-file remapping of the main file
921 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000922 M = PreprocessorOpts.remapped_file_begin(),
923 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000924 M != E;
925 ++M) {
926 llvm::sys::PathWithStatus MPath(M->first);
927 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
928 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
929 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000930 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000931 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000932 CreatedBuffer = false;
933 }
934
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000935 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000936 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000937 return std::make_pair((llvm::MemoryBuffer*)0,
938 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000939 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000940 }
941 }
942 }
943
944 // Check whether there is a file-buffer remapping. It supercedes the
945 // file-file remapping.
946 for (PreprocessorOptions::remapped_file_buffer_iterator
947 M = PreprocessorOpts.remapped_file_buffer_begin(),
948 E = PreprocessorOpts.remapped_file_buffer_end();
949 M != E;
950 ++M) {
951 llvm::sys::PathWithStatus MPath(M->first);
952 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
953 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
954 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000955 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000956 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000957 CreatedBuffer = false;
958 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000959
Douglas Gregor175c4a92010-07-23 23:58:40 +0000960 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000961 }
962 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000963 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000964 }
965
966 // If the main source file was not remapped, load it now.
967 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000968 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000969 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000970 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000971
972 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000973 }
974
Douglas Gregordf95a132010-08-09 20:45:32 +0000975 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000976}
977
Douglas Gregor754f3492010-07-24 00:38:13 +0000978static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +0000979 unsigned NewSize,
980 llvm::StringRef NewName) {
981 llvm::MemoryBuffer *Result
982 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
983 memcpy(const_cast<char*>(Result->getBufferStart()),
984 Old->getBufferStart(), Old->getBufferSize());
985 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000986 ' ', NewSize - Old->getBufferSize() - 1);
987 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000988
Douglas Gregor754f3492010-07-24 00:38:13 +0000989 return Result;
990}
991
Douglas Gregor175c4a92010-07-23 23:58:40 +0000992/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
993/// the source file.
994///
995/// This routine will compute the preamble of the main source file. If a
996/// non-trivial preamble is found, it will precompile that preamble into a
997/// precompiled header so that the precompiled preamble can be used to reduce
998/// reparsing time. If a precompiled preamble has already been constructed,
999/// this routine will determine if it is still valid and, if so, avoid
1000/// rebuilding the precompiled preamble.
1001///
Douglas Gregordf95a132010-08-09 20:45:32 +00001002/// \param AllowRebuild When true (the default), this routine is
1003/// allowed to rebuild the precompiled preamble if it is found to be
1004/// out-of-date.
1005///
1006/// \param MaxLines When non-zero, the maximum number of lines that
1007/// can occur within the preamble.
1008///
Douglas Gregor754f3492010-07-24 00:38:13 +00001009/// \returns If the precompiled preamble can be used, returns a newly-allocated
1010/// buffer that should be used in place of the main file when doing so.
1011/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001012llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +00001013 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +00001014 bool AllowRebuild,
1015 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001016 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1017 PreprocessorOptions &PreprocessorOpts
1018 = PreambleInvocation.getPreprocessorOpts();
1019
1020 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001021 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +00001022 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001023
Douglas Gregor73fc9122010-11-16 20:45:51 +00001024 // If ComputePreamble() Take ownership of the
1025 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1026 if (CreatedPreambleBuffer)
1027 OwnedPreambleBuffer.reset(NewPreamble.first);
1028
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001029 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001030 // We couldn't find a preamble in the main source. Clear out the current
1031 // preamble, if we have one. It's obviously no good any more.
1032 Preamble.clear();
1033 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001034 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001035 PreambleFile.clear();
1036 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001037
1038 // The next time we actually see a preamble, precompile it.
1039 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001040 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001041 }
1042
1043 if (!Preamble.empty()) {
1044 // We've previously computed a preamble. Check whether we have the same
1045 // preamble now that we did before, and that there's enough space in
1046 // the main-file buffer within the precompiled preamble to fit the
1047 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001048 if (Preamble.size() == NewPreamble.second.first &&
1049 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001050 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001051 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001052 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001053 // The preamble has not changed. We may be able to re-use the precompiled
1054 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001055
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001056 // Check that none of the files used by the preamble have changed.
1057 bool AnyFileChanged = false;
1058
1059 // First, make a record of those files that have been overridden via
1060 // remapping or unsaved_files.
1061 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1062 for (PreprocessorOptions::remapped_file_iterator
1063 R = PreprocessorOpts.remapped_file_begin(),
1064 REnd = PreprocessorOpts.remapped_file_end();
1065 !AnyFileChanged && R != REnd;
1066 ++R) {
1067 struct stat StatBuf;
1068 if (stat(R->second.c_str(), &StatBuf)) {
1069 // If we can't stat the file we're remapping to, assume that something
1070 // horrible happened.
1071 AnyFileChanged = true;
1072 break;
1073 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001074
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001075 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1076 StatBuf.st_mtime);
1077 }
1078 for (PreprocessorOptions::remapped_file_buffer_iterator
1079 R = PreprocessorOpts.remapped_file_buffer_begin(),
1080 REnd = PreprocessorOpts.remapped_file_buffer_end();
1081 !AnyFileChanged && R != REnd;
1082 ++R) {
1083 // FIXME: Should we actually compare the contents of file->buffer
1084 // remappings?
1085 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1086 0);
1087 }
1088
1089 // Check whether anything has changed.
1090 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1091 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1092 !AnyFileChanged && F != FEnd;
1093 ++F) {
1094 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1095 = OverriddenFiles.find(F->first());
1096 if (Overridden != OverriddenFiles.end()) {
1097 // This file was remapped; check whether the newly-mapped file
1098 // matches up with the previous mapping.
1099 if (Overridden->second != F->second)
1100 AnyFileChanged = true;
1101 continue;
1102 }
1103
1104 // The file was not remapped; check whether it has changed on disk.
1105 struct stat StatBuf;
1106 if (stat(F->first(), &StatBuf)) {
1107 // If we can't stat the file, assume that something horrible happened.
1108 AnyFileChanged = true;
1109 } else if (StatBuf.st_size != F->second.first ||
1110 StatBuf.st_mtime != F->second.second)
1111 AnyFileChanged = true;
1112 }
1113
1114 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001115 // Okay! We can re-use the precompiled preamble.
1116
1117 // Set the state of the diagnostic object to mimic its state
1118 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001119 // FIXME: This won't catch any #pragma push warning changes that
1120 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001121 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001122 ProcessWarningOptions(getDiagnostics(),
1123 PreambleInvocation.getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001124 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1125 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1126 StoredDiagnostics.erase(
1127 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1128 StoredDiagnostics.end());
1129
1130 // Create a version of the main file buffer that is padded to
1131 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001132 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001133 PreambleReservedSize,
1134 FrontendOpts.Inputs[0].second);
1135 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001136 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001137
1138 // If we aren't allowed to rebuild the precompiled preamble, just
1139 // return now.
1140 if (!AllowRebuild)
1141 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001142
Douglas Gregor175c4a92010-07-23 23:58:40 +00001143 // We can't reuse the previously-computed preamble. Build a new one.
1144 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001145 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001146 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001147 } else if (!AllowRebuild) {
1148 // We aren't allowed to rebuild the precompiled preamble; just
1149 // return now.
1150 return 0;
1151 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001152
1153 // If the preamble rebuild counter > 1, it's because we previously
1154 // failed to build a preamble and we're not yet ready to try
1155 // again. Decrement the counter and return a failure.
1156 if (PreambleRebuildCounter > 1) {
1157 --PreambleRebuildCounter;
1158 return 0;
1159 }
1160
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001161 // Create a temporary file for the precompiled preamble. In rare
1162 // circumstances, this can fail.
1163 std::string PreamblePCHPath = GetPreamblePCHPath();
1164 if (PreamblePCHPath.empty()) {
1165 // Try again next time.
1166 PreambleRebuildCounter = 1;
1167 return 0;
1168 }
1169
Douglas Gregor175c4a92010-07-23 23:58:40 +00001170 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001171 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001172 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001173
1174 // Create a new buffer that stores the preamble. The buffer also contains
1175 // extra space for the original contents of the file (which will be present
1176 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001177 // grows.
1178 PreambleReservedSize = NewPreamble.first->getBufferSize();
1179 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001180 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001181 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001182 PreambleReservedSize *= 2;
1183
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001184 // Save the preamble text for later; we'll need to compare against it for
1185 // subsequent reparses.
1186 Preamble.assign(NewPreamble.first->getBufferStart(),
1187 NewPreamble.first->getBufferStart()
1188 + NewPreamble.second.first);
1189 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1190
Douglas Gregor671947b2010-08-19 01:33:06 +00001191 delete PreambleBuffer;
1192 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001193 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001194 FrontendOpts.Inputs[0].second);
1195 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001196 NewPreamble.first->getBufferStart(), Preamble.size());
1197 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001198 ' ', PreambleReservedSize - Preamble.size() - 1);
1199 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001200
1201 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001202 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001203 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1204
1205 // Tell the compiler invocation to generate a temporary precompiled header.
1206 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001207 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001208 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001209 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001210 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1211 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001212
1213 // Create the compiler instance to use for building the precompiled preamble.
1214 CompilerInstance Clang;
1215 Clang.setInvocation(&PreambleInvocation);
1216 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1217
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001218 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220
1221 // Create the target instance.
1222 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1223 Clang.getTargetOpts()));
1224 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001225 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1226 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001227 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001228 PreprocessorOpts.eraseRemappedFile(
1229 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001230 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231 }
1232
1233 // Inform the target of the language options.
1234 //
1235 // FIXME: We shouldn't need to do this, the target should be immutable once
1236 // created. This complexity should be lifted elsewhere.
1237 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1238
1239 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1240 "Invocation must have exactly one source file!");
1241 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1242 "FIXME: AST inputs not yet supported here!");
1243 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1244 "IR inputs not support here!");
1245
1246 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001247 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001248 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001249 StoredDiagnostics.erase(
1250 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1251 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001252 TopLevelDecls.clear();
1253 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001254 PreprocessedEntities.clear();
1255 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256
1257 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner7ad97ff2010-11-23 07:51:02 +00001258 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001259
1260 // Create the source manager.
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001261 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner39b49bc2010-11-23 08:35:12 +00001262 Clang.getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001264 llvm::OwningPtr<PrecompilePreambleAction> Act;
1265 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1267 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001269 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1270 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001271 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001272 PreprocessorOpts.eraseRemappedFile(
1273 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001274 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001275 }
1276
1277 Act->Execute();
1278 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001279 Clang.takeInvocation();
1280
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001281 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001282 // There were errors parsing the preamble, so no precompiled header was
1283 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001284 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001285 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1286 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001287 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001288 PreprocessedEntities.clear();
1289 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001290 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001291 PreprocessorOpts.eraseRemappedFile(
1292 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001293 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001294 }
1295
1296 // Keep track of the preamble we precompiled.
1297 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001298 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1299 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001300
1301 // Keep track of all of the files that the source manager knows about,
1302 // so we can verify whether they have changed or not.
1303 FilesInPreamble.clear();
1304 SourceManager &SourceMgr = Clang.getSourceManager();
1305 const llvm::MemoryBuffer *MainFileBuffer
1306 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1307 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1308 FEnd = SourceMgr.fileinfo_end();
1309 F != FEnd;
1310 ++F) {
1311 const FileEntry *File = F->second->Entry;
1312 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1313 continue;
1314
1315 FilesInPreamble[File->getName()]
1316 = std::make_pair(F->second->getSize(), File->getModificationTime());
1317 }
1318
Douglas Gregoreababfb2010-08-04 05:53:38 +00001319 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001320 PreprocessorOpts.eraseRemappedFile(
1321 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001322 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001323 PreambleReservedSize,
1324 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001325}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001326
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001327void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1328 std::vector<Decl *> Resolved;
1329 Resolved.reserve(TopLevelDeclsInPreamble.size());
1330 ExternalASTSource &Source = *getASTContext().getExternalSource();
1331 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1332 // Resolve the declaration ID to an actual declaration, possibly
1333 // deserializing the declaration in the process.
1334 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1335 if (D)
1336 Resolved.push_back(D);
1337 }
1338 TopLevelDeclsInPreamble.clear();
1339 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1340}
1341
Douglas Gregor89d99802010-11-30 06:16:57 +00001342void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1343 if (!PP)
1344 return;
1345
1346 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1347 if (!PPRec)
1348 return;
1349
1350 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1351 if (!External)
1352 return;
1353
1354 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1355 if (PreprocessedEntity *PE
1356 = External->ReadPreprocessedEntity(PreprocessedEntitiesInPreamble[I]))
1357 PreprocessedEntities.push_back(PE);
1358 }
1359
1360 if (PreprocessedEntities.empty())
1361 return;
1362
1363 PreprocessedEntities.insert(PreprocessedEntities.end(),
1364 PPRec->begin(true), PPRec->end(true));
1365}
1366
1367ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1368 if (!PreprocessedEntitiesInPreamble.empty() &&
1369 PreprocessedEntities.empty())
1370 RealizePreprocessedEntitiesFromPreamble();
1371
1372 if (PreprocessedEntities.empty())
1373 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1374 return PPRec->begin(true);
1375
1376 return PreprocessedEntities.begin();
1377}
1378
1379ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1380 if (!PreprocessedEntitiesInPreamble.empty() &&
1381 PreprocessedEntities.empty())
1382 RealizePreprocessedEntitiesFromPreamble();
1383
1384 if (PreprocessedEntities.empty())
1385 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1386 return PPRec->end(true);
1387
1388 return PreprocessedEntities.end();
1389}
1390
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001391unsigned ASTUnit::getMaxPCHLevel() const {
1392 if (!getOnlyLocalDecls())
1393 return Decl::MaxPCHLevel;
1394
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001395 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001396}
1397
Douglas Gregor213f18b2010-10-28 15:44:59 +00001398llvm::StringRef ASTUnit::getMainFileName() const {
1399 return Invocation->getFrontendOpts().Inputs[0].second;
1400}
1401
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001402bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1403 if (!Invocation)
1404 return true;
1405
1406 // We'll manage file buffers ourselves.
1407 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1408 Invocation->getFrontendOpts().DisableFree = false;
1409
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001410 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001411 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001412 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001413 OverrideMainBuffer
1414 = getMainBufferWithPrecompiledPreamble(*Invocation);
1415 }
1416
Douglas Gregor213f18b2010-10-28 15:44:59 +00001417 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001418 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001419
Douglas Gregor213f18b2010-10-28 15:44:59 +00001420 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001421}
1422
Douglas Gregorabc563f2010-07-19 21:46:24 +00001423ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1424 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1425 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001426 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001427 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001428 bool CompleteTranslationUnit,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001429 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001430 // Create the AST unit.
1431 llvm::OwningPtr<ASTUnit> AST;
1432 AST.reset(new ASTUnit(false));
Douglas Gregore47be3e2010-11-11 00:39:14 +00001433 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001434 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001435 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001436 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001437 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001438 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001439 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001440 AST->Invocation.reset(CI);
1441
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001442 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001443}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001444
1445ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1446 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001447 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001448 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001449 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001450 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001451 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001452 unsigned NumRemappedFiles,
Douglas Gregordf95a132010-08-09 20:45:32 +00001453 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001454 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001455 bool CacheCodeCompletionResults,
1456 bool CXXPrecompilePreamble,
1457 bool CXXChainedPCH) {
Douglas Gregor28019772010-04-05 23:52:57 +00001458 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001459 // No diagnostics engine was provided, so create our own diagnostics object
1460 // with the default options.
1461 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001462 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001463 }
1464
Daniel Dunbar7b556682009-12-02 03:23:45 +00001465 llvm::SmallVector<const char *, 16> Args;
1466 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1467 Args.insert(Args.end(), ArgBegin, ArgEnd);
1468
1469 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1470 // also want to force it to use clang.
1471 Args.push_back("-fsyntax-only");
1472
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001473 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1474
1475 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001476
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001477 {
Douglas Gregore47be3e2010-11-11 00:39:14 +00001478 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001479 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001480
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001481 // FIXME: We shouldn't have to pass in the path info.
1482 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1483 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001484
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001485 // Don't check that inputs exist, they have been remapped.
1486 TheDriver.setCheckInputsExist(false);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001487
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001488 llvm::OwningPtr<driver::Compilation> C(
1489 TheDriver.BuildCompilation(Args.size(), Args.data()));
1490
1491 // We expect to get back exactly one command job, if we didn't something
1492 // failed.
1493 const driver::JobList &Jobs = C->getJobs();
1494 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1495 llvm::SmallString<256> Msg;
1496 llvm::raw_svector_ostream OS(Msg);
1497 C->PrintJob(OS, C->getJobs(), "; ", true);
1498 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1499 return 0;
1500 }
1501
1502 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1503 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1504 Diags->Report(diag::err_fe_expected_clang_command);
1505 return 0;
1506 }
1507
1508 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1509 CI.reset(new CompilerInvocation);
1510 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001511 const_cast<const char **>(CCArgs.data()),
1512 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001513 CCArgs.size(),
1514 *Diags);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001515 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001516
Douglas Gregor4db64a42010-01-23 00:14:00 +00001517 // Override any files that need remapping
1518 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001519 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001520 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001521
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001522 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001523 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001524
Douglas Gregor99ba2022010-10-27 17:24:53 +00001525 // Check whether we should precompile the preamble and/or use chained PCH.
1526 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1527 if (CI->getLangOpts().CPlusPlus) {
1528 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1529
1530 if (PrecompilePreamble && !CXXChainedPCH &&
1531 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1532 PrecompilePreamble = false;
1533 }
1534
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001535 // Create the AST unit.
1536 llvm::OwningPtr<ASTUnit> AST;
1537 AST.reset(new ASTUnit(false));
Douglas Gregore47be3e2010-11-11 00:39:14 +00001538 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001539 AST->Diagnostics = Diags;
Chris Lattner39b49bc2010-11-23 08:35:12 +00001540
1541 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001542 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001543 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001544 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1545 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001546 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001547 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1548 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1549 AST->StoredDiagnostics.swap(StoredDiagnostics);
1550 AST->Invocation.reset(CI.take());
Chris Lattner39b49bc2010-11-23 08:35:12 +00001551 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001552}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001553
1554bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1555 if (!Invocation.get())
1556 return true;
1557
Douglas Gregor213f18b2010-10-28 15:44:59 +00001558 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001559 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001560
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001561 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001562 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1563 for (PreprocessorOptions::remapped_file_buffer_iterator
1564 R = PPOpts.remapped_file_buffer_begin(),
1565 REnd = PPOpts.remapped_file_buffer_end();
1566 R != REnd;
1567 ++R) {
1568 delete R->second;
1569 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001570 Invocation->getPreprocessorOpts().clearRemappedFiles();
1571 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1572 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1573 RemappedFiles[I].second);
1574
Douglas Gregoreababfb2010-08-04 05:53:38 +00001575 // If we have a preamble file lying around, or if we might try to
1576 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001577 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001578 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001579 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001580
Douglas Gregorabc563f2010-07-19 21:46:24 +00001581 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001582 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001583 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001584 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1585 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001586
Douglas Gregor175c4a92010-07-23 23:58:40 +00001587 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001588 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor727d93e2010-08-17 00:40:40 +00001589
1590 if (ShouldCacheCodeCompletionResults) {
1591 if (CacheCodeCompletionCoolDown > 0)
1592 --CacheCodeCompletionCoolDown;
1593 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1594 CacheCodeCompletionResults();
1595 }
1596
Douglas Gregor175c4a92010-07-23 23:58:40 +00001597 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001598}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001599
Douglas Gregor87c08a52010-08-13 22:48:40 +00001600//----------------------------------------------------------------------------//
1601// Code completion
1602//----------------------------------------------------------------------------//
1603
1604namespace {
1605 /// \brief Code completion consumer that combines the cached code-completion
1606 /// results from an ASTUnit with the code-completion results provided to it,
1607 /// then passes the result on to
1608 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1609 unsigned NormalContexts;
1610 ASTUnit &AST;
1611 CodeCompleteConsumer &Next;
1612
1613 public:
1614 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001615 bool IncludeMacros, bool IncludeCodePatterns,
1616 bool IncludeGlobals)
1617 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001618 Next.isOutputBinary()), AST(AST), Next(Next)
1619 {
1620 // Compute the set of contexts in which we will look when we don't have
1621 // any information about the specific context.
1622 NormalContexts
1623 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1624 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1625 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1626 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1627 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1628 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1629 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1630 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001631 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001632 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1633 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001634
Douglas Gregor87c08a52010-08-13 22:48:40 +00001635 if (AST.getASTContext().getLangOptions().CPlusPlus)
1636 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1637 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1638 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1639 }
1640
1641 virtual void ProcessCodeCompleteResults(Sema &S,
1642 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001643 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001644 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001645
1646 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1647 OverloadCandidate *Candidates,
1648 unsigned NumCandidates) {
1649 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1650 }
1651 };
1652}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001653
Douglas Gregor5f808c22010-08-16 21:18:39 +00001654/// \brief Helper function that computes which global names are hidden by the
1655/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001656static void CalculateHiddenNames(const CodeCompletionContext &Context,
1657 CodeCompletionResult *Results,
1658 unsigned NumResults,
1659 ASTContext &Ctx,
1660 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001661 bool OnlyTagNames = false;
1662 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001663 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001664 case CodeCompletionContext::CCC_TopLevel:
1665 case CodeCompletionContext::CCC_ObjCInterface:
1666 case CodeCompletionContext::CCC_ObjCImplementation:
1667 case CodeCompletionContext::CCC_ObjCIvarList:
1668 case CodeCompletionContext::CCC_ClassStructUnion:
1669 case CodeCompletionContext::CCC_Statement:
1670 case CodeCompletionContext::CCC_Expression:
1671 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1672 case CodeCompletionContext::CCC_MemberAccess:
1673 case CodeCompletionContext::CCC_Namespace:
1674 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001675 case CodeCompletionContext::CCC_Name:
1676 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001677 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001678 break;
1679
1680 case CodeCompletionContext::CCC_EnumTag:
1681 case CodeCompletionContext::CCC_UnionTag:
1682 case CodeCompletionContext::CCC_ClassOrStructTag:
1683 OnlyTagNames = true;
1684 break;
1685
1686 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001687 case CodeCompletionContext::CCC_MacroName:
1688 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001689 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001690 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001691 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001692 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001693 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001694 case CodeCompletionContext::CCC_Other:
Douglas Gregor721f3592010-08-25 18:41:16 +00001695 // We're looking for nothing, or we're looking for names that cannot
1696 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001697 return;
1698 }
1699
John McCall0a2c5e22010-08-25 06:19:51 +00001700 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001701 for (unsigned I = 0; I != NumResults; ++I) {
1702 if (Results[I].Kind != Result::RK_Declaration)
1703 continue;
1704
1705 unsigned IDNS
1706 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1707
1708 bool Hiding = false;
1709 if (OnlyTagNames)
1710 Hiding = (IDNS & Decl::IDNS_Tag);
1711 else {
1712 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001713 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1714 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001715 if (Ctx.getLangOptions().CPlusPlus)
1716 HiddenIDNS |= Decl::IDNS_Tag;
1717 Hiding = (IDNS & HiddenIDNS);
1718 }
1719
1720 if (!Hiding)
1721 continue;
1722
1723 DeclarationName Name = Results[I].Declaration->getDeclName();
1724 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1725 HiddenNames.insert(Identifier->getName());
1726 else
1727 HiddenNames.insert(Name.getAsString());
1728 }
1729}
1730
1731
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001732void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1733 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001734 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001735 unsigned NumResults) {
1736 // Merge the results we were given with the results we cached.
1737 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001738 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001739 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001740 : (1 << (Context.getKind() - 1)));
1741
1742 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001743 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001744 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall0a2c5e22010-08-25 06:19:51 +00001745 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001746 llvm::SmallVector<Result, 8> AllResults;
1747 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001748 C = AST.cached_completion_begin(),
1749 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001750 C != CEnd; ++C) {
1751 // If the context we are in matches any of the contexts we are
1752 // interested in, we'll add this result.
1753 if ((C->ShowInContexts & InContexts) == 0)
1754 continue;
1755
1756 // If we haven't added any results previously, do so now.
1757 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001758 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1759 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001760 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1761 AddedResult = true;
1762 }
1763
Douglas Gregor5f808c22010-08-16 21:18:39 +00001764 // Determine whether this global completion result is hidden by a local
1765 // completion result. If so, skip it.
1766 if (C->Kind != CXCursor_MacroDefinition &&
1767 HiddenNames.count(C->Completion->getTypedText()))
1768 continue;
1769
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001770 // Adjust priority based on similar type classes.
1771 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001772 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001773 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001774 if (!Context.getPreferredType().isNull()) {
1775 if (C->Kind == CXCursor_MacroDefinition) {
1776 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001777 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001778 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001779 } else if (C->Type) {
1780 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001781 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001782 Context.getPreferredType().getUnqualifiedType());
1783 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1784 if (ExpectedSTC == C->TypeClass) {
1785 // We know this type is similar; check for an exact match.
1786 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001787 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001788 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001789 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001790 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1791 Priority /= CCF_ExactTypeMatch;
1792 else
1793 Priority /= CCF_SimilarTypeMatch;
1794 }
1795 }
1796 }
1797
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001798 // Adjust the completion string, if required.
1799 if (C->Kind == CXCursor_MacroDefinition &&
1800 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1801 // Create a new code-completion string that just contains the
1802 // macro name, without its arguments.
1803 Completion = new CodeCompletionString;
1804 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1805 StringsToDestroy.push_back(Completion);
Douglas Gregor4125c372010-08-25 18:03:13 +00001806 CursorKind = CXCursor_NotImplemented;
1807 Priority = CCP_CodePattern;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001808 }
1809
Douglas Gregor4125c372010-08-25 18:03:13 +00001810 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001811 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001812 }
1813
1814 // If we did not add any cached completion results, just forward the
1815 // results we were given to the next consumer.
1816 if (!AddedResult) {
1817 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1818 return;
1819 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001820
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001821 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1822 AllResults.size());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001823
1824 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1825 delete StringsToDestroy[I];
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001826}
1827
1828
1829
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001830void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1831 RemappedFile *RemappedFiles,
1832 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001833 bool IncludeMacros,
1834 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001835 CodeCompleteConsumer &Consumer,
1836 Diagnostic &Diag, LangOptions &LangOpts,
1837 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00001838 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1839 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001840 if (!Invocation.get())
1841 return;
1842
Douglas Gregor213f18b2010-10-28 15:44:59 +00001843 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001844 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1845 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00001846
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001847 CompilerInvocation CCInvocation(*Invocation);
1848 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1849 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001850
Douglas Gregor87c08a52010-08-13 22:48:40 +00001851 FrontendOpts.ShowMacrosInCodeCompletion
1852 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001853 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001854 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1855 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001856 FrontendOpts.CodeCompletionAt.FileName = File;
1857 FrontendOpts.CodeCompletionAt.Line = Line;
1858 FrontendOpts.CodeCompletionAt.Column = Column;
1859
1860 // Set the language options appropriately.
1861 LangOpts = CCInvocation.getLangOpts();
1862
1863 CompilerInstance Clang;
1864 Clang.setInvocation(&CCInvocation);
1865 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1866
1867 // Set up diagnostics, capturing any diagnostics produced.
1868 Clang.setDiagnostics(&Diag);
Douglas Gregor32be4a52010-10-11 21:37:58 +00001869 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001870 CaptureDroppedDiagnostics Capture(true,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001871 Clang.getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001872 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001873
1874 // Create the target instance.
1875 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1876 Clang.getTargetOpts()));
1877 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001878 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001879 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001880 }
1881
1882 // Inform the target of the language options.
1883 //
1884 // FIXME: We shouldn't need to do this, the target should be immutable once
1885 // created. This complexity should be lifted elsewhere.
1886 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1887
1888 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1889 "Invocation must have exactly one source file!");
1890 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1891 "FIXME: AST inputs not yet supported here!");
1892 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1893 "IR inputs not support here!");
1894
1895
1896 // Use the source and file managers that we were given.
1897 Clang.setFileManager(&FileMgr);
1898 Clang.setSourceManager(&SourceMgr);
1899
1900 // Remap files.
1901 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001902 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00001903 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001904 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1905 RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00001906 OwnedBuffers.push_back(RemappedFiles[I].second);
1907 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001908
Douglas Gregor87c08a52010-08-13 22:48:40 +00001909 // Use the code completion consumer we were given, but adding any cached
1910 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00001911 AugmentedCodeCompleteConsumer *AugmentedConsumer
1912 = new AugmentedCodeCompleteConsumer(*this, Consumer,
1913 FrontendOpts.ShowMacrosInCodeCompletion,
1914 FrontendOpts.ShowCodePatternsInCodeCompletion,
1915 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
1916 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001917
Douglas Gregordf95a132010-08-09 20:45:32 +00001918 // If we have a precompiled preamble, try to use it. We only allow
1919 // the use of the precompiled preamble if we're if the completion
1920 // point is within the main file, after the end of the precompiled
1921 // preamble.
1922 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1923 if (!PreambleFile.empty()) {
1924 using llvm::sys::FileStatus;
1925 llvm::sys::PathWithStatus CompleteFilePath(File);
1926 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1927 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1928 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1929 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00001930 OverrideMainBuffer
Douglas Gregorc9c29a82010-08-25 18:04:15 +00001931 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1932 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00001933 }
1934
1935 // If the main file has been overridden due to the use of a preamble,
1936 // make that override happen and introduce the preamble.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001937 StoredDiagnostics.insert(StoredDiagnostics.end(),
1938 this->StoredDiagnostics.begin(),
1939 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00001940 if (OverrideMainBuffer) {
1941 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1942 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1943 PreprocessorOpts.PrecompiledPreambleBytes.second
1944 = PreambleEndsAtStartOfLine;
1945 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1946 PreprocessorOpts.DisablePCHValidation = true;
1947
1948 // The stored diagnostics have the old source manager. Copy them
1949 // to our output set of stored diagnostics, updating the source
1950 // manager to the one we were given.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001951 for (unsigned I = NumStoredDiagnosticsFromDriver,
1952 N = this->StoredDiagnostics.size();
1953 I < N; ++I) {
Douglas Gregordf95a132010-08-09 20:45:32 +00001954 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1955 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1956 StoredDiagnostics[I].setLocation(Loc);
1957 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001958
Douglas Gregor2283d792010-08-20 00:59:43 +00001959 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001960 } else {
1961 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1962 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00001963 }
1964
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001965 llvm::OwningPtr<SyntaxOnlyAction> Act;
1966 Act.reset(new SyntaxOnlyAction);
1967 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1968 Clang.getFrontendOpts().Inputs[0].first)) {
1969 Act->Execute();
1970 Act->EndSourceFile();
1971 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001972
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001973 // Steal back our resources.
1974 Clang.takeFileManager();
1975 Clang.takeSourceManager();
1976 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001977}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001978
1979bool ASTUnit::Save(llvm::StringRef File) {
1980 if (getDiagnostics().hasErrorOccurred())
1981 return true;
1982
1983 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1984 // unconditionally create a stat cache when we parse the file?
1985 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001986 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1987 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001988 if (!ErrorInfo.empty() || Out.has_error())
1989 return true;
1990
1991 std::vector<unsigned char> Buffer;
1992 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001993 ASTWriter Writer(Stream);
1994 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001995
1996 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001997 if (!Buffer.empty())
1998 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001999 Out.close();
2000 return Out.has_error();
2001}