blob: d042f3fb857794e14ac4498ee6dbd40bfb84108b [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());
Douglas Gregord64f4c12010-12-09 21:27:43 +0000851
852 if (ShouldCacheCodeCompletionResults) {
853 if (CacheCodeCompletionCoolDown > 0)
854 --CacheCodeCompletionCoolDown;
855 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
856 CacheCodeCompletionResults();
857 }
858
Douglas Gregorabc563f2010-07-19 21:46:24 +0000859 return false;
860
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000861error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000862 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000863 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000864 PreprocessorOpts.eraseRemappedFile(
865 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000866 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000867 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000868 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000869 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000870
Douglas Gregord54eb442010-10-12 16:25:54 +0000871 StoredDiagnostics.clear();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000872 Clang.takeSourceManager();
873 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000874 Invocation.reset(Clang.takeInvocation());
875 return true;
876}
877
Douglas Gregor44c181a2010-07-23 00:33:23 +0000878/// \brief Simple function to retrieve a path for a preamble precompiled header.
879static std::string GetPreamblePCHPath() {
880 // FIXME: This is lame; sys::Path should provide this function (in particular,
881 // it should know how to find the temporary files dir).
882 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000883 // FIXME: This is a hack so that we can override the preamble file during
884 // crash-recovery testing, which is the only case where the preamble files
885 // are not necessarily cleaned up.
886 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
887 if (TmpFile)
888 return TmpFile;
889
Douglas Gregor44c181a2010-07-23 00:33:23 +0000890 std::string Error;
891 const char *TmpDir = ::getenv("TMPDIR");
892 if (!TmpDir)
893 TmpDir = ::getenv("TEMP");
894 if (!TmpDir)
895 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000896#ifdef LLVM_ON_WIN32
897 if (!TmpDir)
898 TmpDir = ::getenv("USERPROFILE");
899#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000900 if (!TmpDir)
901 TmpDir = "/tmp";
902 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000903 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000904 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000905 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000906 if (P.createTemporaryFileOnDisk())
907 return std::string();
908
Douglas Gregor44c181a2010-07-23 00:33:23 +0000909 return P.str();
910}
911
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000912/// \brief Compute the preamble for the main file, providing the source buffer
913/// that corresponds to the main file along with a pair (bytes, start-of-line)
914/// that describes the preamble.
915std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000916ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
917 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000918 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +0000919 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000920 CreatedBuffer = false;
921
Douglas Gregor44c181a2010-07-23 00:33:23 +0000922 // Try to determine if the main file has been remapped, either from the
923 // command line (to another file) or directly through the compiler invocation
924 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000925 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000926 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
927 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
928 // Check whether there is a file-file remapping of the main file
929 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000930 M = PreprocessorOpts.remapped_file_begin(),
931 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000932 M != E;
933 ++M) {
934 llvm::sys::PathWithStatus MPath(M->first);
935 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
936 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
937 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000938 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000939 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000940 CreatedBuffer = false;
941 }
942
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000943 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000944 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000945 return std::make_pair((llvm::MemoryBuffer*)0,
946 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000947 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000948 }
949 }
950 }
951
952 // Check whether there is a file-buffer remapping. It supercedes the
953 // file-file remapping.
954 for (PreprocessorOptions::remapped_file_buffer_iterator
955 M = PreprocessorOpts.remapped_file_buffer_begin(),
956 E = PreprocessorOpts.remapped_file_buffer_end();
957 M != E;
958 ++M) {
959 llvm::sys::PathWithStatus MPath(M->first);
960 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
961 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
962 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000963 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000964 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000965 CreatedBuffer = false;
966 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000967
Douglas Gregor175c4a92010-07-23 23:58:40 +0000968 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000969 }
970 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000971 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000972 }
973
974 // If the main source file was not remapped, load it now.
975 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000976 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000977 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000978 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000979
980 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000981 }
982
Douglas Gregordf95a132010-08-09 20:45:32 +0000983 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000984}
985
Douglas Gregor754f3492010-07-24 00:38:13 +0000986static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +0000987 unsigned NewSize,
988 llvm::StringRef NewName) {
989 llvm::MemoryBuffer *Result
990 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
991 memcpy(const_cast<char*>(Result->getBufferStart()),
992 Old->getBufferStart(), Old->getBufferSize());
993 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000994 ' ', NewSize - Old->getBufferSize() - 1);
995 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000996
Douglas Gregor754f3492010-07-24 00:38:13 +0000997 return Result;
998}
999
Douglas Gregor175c4a92010-07-23 23:58:40 +00001000/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1001/// the source file.
1002///
1003/// This routine will compute the preamble of the main source file. If a
1004/// non-trivial preamble is found, it will precompile that preamble into a
1005/// precompiled header so that the precompiled preamble can be used to reduce
1006/// reparsing time. If a precompiled preamble has already been constructed,
1007/// this routine will determine if it is still valid and, if so, avoid
1008/// rebuilding the precompiled preamble.
1009///
Douglas Gregordf95a132010-08-09 20:45:32 +00001010/// \param AllowRebuild When true (the default), this routine is
1011/// allowed to rebuild the precompiled preamble if it is found to be
1012/// out-of-date.
1013///
1014/// \param MaxLines When non-zero, the maximum number of lines that
1015/// can occur within the preamble.
1016///
Douglas Gregor754f3492010-07-24 00:38:13 +00001017/// \returns If the precompiled preamble can be used, returns a newly-allocated
1018/// buffer that should be used in place of the main file when doing so.
1019/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001020llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +00001021 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +00001022 bool AllowRebuild,
1023 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001024 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1025 PreprocessorOptions &PreprocessorOpts
1026 = PreambleInvocation.getPreprocessorOpts();
1027
1028 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001029 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +00001030 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001031
Douglas Gregor73fc9122010-11-16 20:45:51 +00001032 // If ComputePreamble() Take ownership of the
1033 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1034 if (CreatedPreambleBuffer)
1035 OwnedPreambleBuffer.reset(NewPreamble.first);
1036
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001037 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001038 // We couldn't find a preamble in the main source. Clear out the current
1039 // preamble, if we have one. It's obviously no good any more.
1040 Preamble.clear();
1041 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001042 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001043 PreambleFile.clear();
1044 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001045
1046 // The next time we actually see a preamble, precompile it.
1047 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001048 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001049 }
1050
1051 if (!Preamble.empty()) {
1052 // We've previously computed a preamble. Check whether we have the same
1053 // preamble now that we did before, and that there's enough space in
1054 // the main-file buffer within the precompiled preamble to fit the
1055 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001056 if (Preamble.size() == NewPreamble.second.first &&
1057 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001058 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001059 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001060 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001061 // The preamble has not changed. We may be able to re-use the precompiled
1062 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001063
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001064 // Check that none of the files used by the preamble have changed.
1065 bool AnyFileChanged = false;
1066
1067 // First, make a record of those files that have been overridden via
1068 // remapping or unsaved_files.
1069 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1070 for (PreprocessorOptions::remapped_file_iterator
1071 R = PreprocessorOpts.remapped_file_begin(),
1072 REnd = PreprocessorOpts.remapped_file_end();
1073 !AnyFileChanged && R != REnd;
1074 ++R) {
1075 struct stat StatBuf;
1076 if (stat(R->second.c_str(), &StatBuf)) {
1077 // If we can't stat the file we're remapping to, assume that something
1078 // horrible happened.
1079 AnyFileChanged = true;
1080 break;
1081 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001082
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001083 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1084 StatBuf.st_mtime);
1085 }
1086 for (PreprocessorOptions::remapped_file_buffer_iterator
1087 R = PreprocessorOpts.remapped_file_buffer_begin(),
1088 REnd = PreprocessorOpts.remapped_file_buffer_end();
1089 !AnyFileChanged && R != REnd;
1090 ++R) {
1091 // FIXME: Should we actually compare the contents of file->buffer
1092 // remappings?
1093 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1094 0);
1095 }
1096
1097 // Check whether anything has changed.
1098 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1099 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1100 !AnyFileChanged && F != FEnd;
1101 ++F) {
1102 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1103 = OverriddenFiles.find(F->first());
1104 if (Overridden != OverriddenFiles.end()) {
1105 // This file was remapped; check whether the newly-mapped file
1106 // matches up with the previous mapping.
1107 if (Overridden->second != F->second)
1108 AnyFileChanged = true;
1109 continue;
1110 }
1111
1112 // The file was not remapped; check whether it has changed on disk.
1113 struct stat StatBuf;
1114 if (stat(F->first(), &StatBuf)) {
1115 // If we can't stat the file, assume that something horrible happened.
1116 AnyFileChanged = true;
1117 } else if (StatBuf.st_size != F->second.first ||
1118 StatBuf.st_mtime != F->second.second)
1119 AnyFileChanged = true;
1120 }
1121
1122 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001123 // Okay! We can re-use the precompiled preamble.
1124
1125 // Set the state of the diagnostic object to mimic its state
1126 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001127 // FIXME: This won't catch any #pragma push warning changes that
1128 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001129 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001130 ProcessWarningOptions(getDiagnostics(),
1131 PreambleInvocation.getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001132 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1133 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1134 StoredDiagnostics.erase(
1135 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1136 StoredDiagnostics.end());
1137
1138 // Create a version of the main file buffer that is padded to
1139 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001140 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001141 PreambleReservedSize,
1142 FrontendOpts.Inputs[0].second);
1143 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001144 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001145
1146 // If we aren't allowed to rebuild the precompiled preamble, just
1147 // return now.
1148 if (!AllowRebuild)
1149 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001150
Douglas Gregor175c4a92010-07-23 23:58:40 +00001151 // We can't reuse the previously-computed preamble. Build a new one.
1152 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001153 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001154 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001155 } else if (!AllowRebuild) {
1156 // We aren't allowed to rebuild the precompiled preamble; just
1157 // return now.
1158 return 0;
1159 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001160
1161 // If the preamble rebuild counter > 1, it's because we previously
1162 // failed to build a preamble and we're not yet ready to try
1163 // again. Decrement the counter and return a failure.
1164 if (PreambleRebuildCounter > 1) {
1165 --PreambleRebuildCounter;
1166 return 0;
1167 }
1168
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001169 // Create a temporary file for the precompiled preamble. In rare
1170 // circumstances, this can fail.
1171 std::string PreamblePCHPath = GetPreamblePCHPath();
1172 if (PreamblePCHPath.empty()) {
1173 // Try again next time.
1174 PreambleRebuildCounter = 1;
1175 return 0;
1176 }
1177
Douglas Gregor175c4a92010-07-23 23:58:40 +00001178 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001179 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001180 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001181
1182 // Create a new buffer that stores the preamble. The buffer also contains
1183 // extra space for the original contents of the file (which will be present
1184 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001185 // grows.
1186 PreambleReservedSize = NewPreamble.first->getBufferSize();
1187 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001188 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001189 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001190 PreambleReservedSize *= 2;
1191
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001192 // Save the preamble text for later; we'll need to compare against it for
1193 // subsequent reparses.
1194 Preamble.assign(NewPreamble.first->getBufferStart(),
1195 NewPreamble.first->getBufferStart()
1196 + NewPreamble.second.first);
1197 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1198
Douglas Gregor671947b2010-08-19 01:33:06 +00001199 delete PreambleBuffer;
1200 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001201 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001202 FrontendOpts.Inputs[0].second);
1203 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001204 NewPreamble.first->getBufferStart(), Preamble.size());
1205 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001206 ' ', PreambleReservedSize - Preamble.size() - 1);
1207 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001208
1209 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001210 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001211 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1212
1213 // Tell the compiler invocation to generate a temporary precompiled header.
1214 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001215 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001217 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001218 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1219 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220
1221 // Create the compiler instance to use for building the precompiled preamble.
1222 CompilerInstance Clang;
1223 Clang.setInvocation(&PreambleInvocation);
1224 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1225
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001226 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001227 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228
1229 // Create the target instance.
1230 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1231 Clang.getTargetOpts()));
1232 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001233 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1234 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001235 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001236 PreprocessorOpts.eraseRemappedFile(
1237 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001238 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001239 }
1240
1241 // Inform the target of the language options.
1242 //
1243 // FIXME: We shouldn't need to do this, the target should be immutable once
1244 // created. This complexity should be lifted elsewhere.
1245 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1246
1247 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1248 "Invocation must have exactly one source file!");
1249 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1250 "FIXME: AST inputs not yet supported here!");
1251 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1252 "IR inputs not support here!");
1253
1254 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001255 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001256 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001257 StoredDiagnostics.erase(
1258 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1259 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001260 TopLevelDecls.clear();
1261 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001262 PreprocessedEntities.clear();
1263 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001264
1265 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner7ad97ff2010-11-23 07:51:02 +00001266 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001267
1268 // Create the source manager.
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001269 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner39b49bc2010-11-23 08:35:12 +00001270 Clang.getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001271
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001272 llvm::OwningPtr<PrecompilePreambleAction> Act;
1273 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001274 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1275 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001276 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1278 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001279 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001280 PreprocessorOpts.eraseRemappedFile(
1281 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001282 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 }
1284
1285 Act->Execute();
1286 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001287 Clang.takeInvocation();
1288
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001289 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001290 // There were errors parsing the preamble, so no precompiled header was
1291 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001292 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001293 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1294 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001295 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001296 PreprocessedEntities.clear();
1297 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001298 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001299 PreprocessorOpts.eraseRemappedFile(
1300 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001301 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001302 }
1303
1304 // Keep track of the preamble we precompiled.
1305 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001306 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1307 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001308
1309 // Keep track of all of the files that the source manager knows about,
1310 // so we can verify whether they have changed or not.
1311 FilesInPreamble.clear();
1312 SourceManager &SourceMgr = Clang.getSourceManager();
1313 const llvm::MemoryBuffer *MainFileBuffer
1314 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1315 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1316 FEnd = SourceMgr.fileinfo_end();
1317 F != FEnd;
1318 ++F) {
1319 const FileEntry *File = F->second->Entry;
1320 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1321 continue;
1322
1323 FilesInPreamble[File->getName()]
1324 = std::make_pair(F->second->getSize(), File->getModificationTime());
1325 }
1326
Douglas Gregoreababfb2010-08-04 05:53:38 +00001327 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001328 PreprocessorOpts.eraseRemappedFile(
1329 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001330 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001331 PreambleReservedSize,
1332 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001333}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001334
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001335void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1336 std::vector<Decl *> Resolved;
1337 Resolved.reserve(TopLevelDeclsInPreamble.size());
1338 ExternalASTSource &Source = *getASTContext().getExternalSource();
1339 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1340 // Resolve the declaration ID to an actual declaration, possibly
1341 // deserializing the declaration in the process.
1342 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1343 if (D)
1344 Resolved.push_back(D);
1345 }
1346 TopLevelDeclsInPreamble.clear();
1347 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1348}
1349
Douglas Gregor89d99802010-11-30 06:16:57 +00001350void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1351 if (!PP)
1352 return;
1353
1354 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1355 if (!PPRec)
1356 return;
1357
1358 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1359 if (!External)
1360 return;
1361
1362 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1363 if (PreprocessedEntity *PE
1364 = External->ReadPreprocessedEntity(PreprocessedEntitiesInPreamble[I]))
1365 PreprocessedEntities.push_back(PE);
1366 }
1367
1368 if (PreprocessedEntities.empty())
1369 return;
1370
1371 PreprocessedEntities.insert(PreprocessedEntities.end(),
1372 PPRec->begin(true), PPRec->end(true));
1373}
1374
1375ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1376 if (!PreprocessedEntitiesInPreamble.empty() &&
1377 PreprocessedEntities.empty())
1378 RealizePreprocessedEntitiesFromPreamble();
1379
1380 if (PreprocessedEntities.empty())
1381 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1382 return PPRec->begin(true);
1383
1384 return PreprocessedEntities.begin();
1385}
1386
1387ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1388 if (!PreprocessedEntitiesInPreamble.empty() &&
1389 PreprocessedEntities.empty())
1390 RealizePreprocessedEntitiesFromPreamble();
1391
1392 if (PreprocessedEntities.empty())
1393 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1394 return PPRec->end(true);
1395
1396 return PreprocessedEntities.end();
1397}
1398
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001399unsigned ASTUnit::getMaxPCHLevel() const {
1400 if (!getOnlyLocalDecls())
1401 return Decl::MaxPCHLevel;
1402
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001403 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001404}
1405
Douglas Gregor213f18b2010-10-28 15:44:59 +00001406llvm::StringRef ASTUnit::getMainFileName() const {
1407 return Invocation->getFrontendOpts().Inputs[0].second;
1408}
1409
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001410bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1411 if (!Invocation)
1412 return true;
1413
1414 // We'll manage file buffers ourselves.
1415 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1416 Invocation->getFrontendOpts().DisableFree = false;
1417
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001418 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001419 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001420 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001421 OverrideMainBuffer
1422 = getMainBufferWithPrecompiledPreamble(*Invocation);
1423 }
1424
Douglas Gregor213f18b2010-10-28 15:44:59 +00001425 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001426 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001427
Douglas Gregor213f18b2010-10-28 15:44:59 +00001428 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001429}
1430
Douglas Gregorabc563f2010-07-19 21:46:24 +00001431ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1432 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1433 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001434 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001435 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001436 bool CompleteTranslationUnit,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001437 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001438 // Create the AST unit.
1439 llvm::OwningPtr<ASTUnit> AST;
1440 AST.reset(new ASTUnit(false));
Douglas Gregore47be3e2010-11-11 00:39:14 +00001441 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001442 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001443 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001444 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001445 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001446 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001447 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001448 AST->Invocation.reset(CI);
1449
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001450 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001451}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001452
1453ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1454 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001455 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001456 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001457 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001458 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001459 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001460 unsigned NumRemappedFiles,
Douglas Gregordf95a132010-08-09 20:45:32 +00001461 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001462 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001463 bool CacheCodeCompletionResults,
1464 bool CXXPrecompilePreamble,
1465 bool CXXChainedPCH) {
Douglas Gregor28019772010-04-05 23:52:57 +00001466 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001467 // No diagnostics engine was provided, so create our own diagnostics object
1468 // with the default options.
1469 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001470 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001471 }
1472
Daniel Dunbar7b556682009-12-02 03:23:45 +00001473 llvm::SmallVector<const char *, 16> Args;
1474 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1475 Args.insert(Args.end(), ArgBegin, ArgEnd);
1476
1477 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1478 // also want to force it to use clang.
1479 Args.push_back("-fsyntax-only");
1480
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001481 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1482
1483 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001484
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001485 {
Douglas Gregore47be3e2010-11-11 00:39:14 +00001486 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001487 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001488
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001489 // FIXME: We shouldn't have to pass in the path info.
1490 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1491 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001492
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001493 // Don't check that inputs exist, they have been remapped.
1494 TheDriver.setCheckInputsExist(false);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001495
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001496 llvm::OwningPtr<driver::Compilation> C(
1497 TheDriver.BuildCompilation(Args.size(), Args.data()));
1498
1499 // We expect to get back exactly one command job, if we didn't something
1500 // failed.
1501 const driver::JobList &Jobs = C->getJobs();
1502 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1503 llvm::SmallString<256> Msg;
1504 llvm::raw_svector_ostream OS(Msg);
1505 C->PrintJob(OS, C->getJobs(), "; ", true);
1506 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1507 return 0;
1508 }
1509
1510 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1511 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1512 Diags->Report(diag::err_fe_expected_clang_command);
1513 return 0;
1514 }
1515
1516 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1517 CI.reset(new CompilerInvocation);
1518 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001519 const_cast<const char **>(CCArgs.data()),
1520 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001521 CCArgs.size(),
1522 *Diags);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001523 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001524
Douglas Gregor4db64a42010-01-23 00:14:00 +00001525 // Override any files that need remapping
1526 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001527 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001528 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001529
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001530 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001531 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001532
Douglas Gregor99ba2022010-10-27 17:24:53 +00001533 // Check whether we should precompile the preamble and/or use chained PCH.
1534 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1535 if (CI->getLangOpts().CPlusPlus) {
1536 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1537
1538 if (PrecompilePreamble && !CXXChainedPCH &&
1539 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1540 PrecompilePreamble = false;
1541 }
1542
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001543 // Create the AST unit.
1544 llvm::OwningPtr<ASTUnit> AST;
1545 AST.reset(new ASTUnit(false));
Douglas Gregore47be3e2010-11-11 00:39:14 +00001546 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001547 AST->Diagnostics = Diags;
Chris Lattner39b49bc2010-11-23 08:35:12 +00001548
1549 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001550 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001551 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001552 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1553 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001554 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001555 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1556 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1557 AST->StoredDiagnostics.swap(StoredDiagnostics);
1558 AST->Invocation.reset(CI.take());
Chris Lattner39b49bc2010-11-23 08:35:12 +00001559 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001560}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001561
1562bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1563 if (!Invocation.get())
1564 return true;
1565
Douglas Gregor213f18b2010-10-28 15:44:59 +00001566 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001567 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001568
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001569 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001570 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1571 for (PreprocessorOptions::remapped_file_buffer_iterator
1572 R = PPOpts.remapped_file_buffer_begin(),
1573 REnd = PPOpts.remapped_file_buffer_end();
1574 R != REnd;
1575 ++R) {
1576 delete R->second;
1577 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001578 Invocation->getPreprocessorOpts().clearRemappedFiles();
1579 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1580 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1581 RemappedFiles[I].second);
1582
Douglas Gregoreababfb2010-08-04 05:53:38 +00001583 // If we have a preamble file lying around, or if we might try to
1584 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001585 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001586 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001587 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001588
Douglas Gregorabc563f2010-07-19 21:46:24 +00001589 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001590 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001591 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001592 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1593 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001594
Douglas Gregor175c4a92010-07-23 23:58:40 +00001595 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001596 bool Result = Parse(OverrideMainBuffer);
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}