blob: 0370c2e125b540def94ab349b32473a1ddef7aa7 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Douglas Gregorf88e35b2010-11-30 06:16:57 +000030#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000031#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000032#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000034#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000035#include "clang/Basic/TargetInfo.h"
36#include "clang/Basic/Diagnostic.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000037#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000038#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000043#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000044#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000045#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000046#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000047using namespace clang;
48
Douglas Gregor16896c42010-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 Kramerf2e5a912010-11-09 20:00:56 +000057 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000058 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000059 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000060 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000061 }
62
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000065 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000066 }
67
Douglas Gregor16896c42010-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 Gregorbb420ab2010-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 Gregor68dbaea2010-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 Gregor9aeaa4d2010-12-07 00:05:48 +000089static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +000090
Douglas Gregord03e8232010-04-05 21:10:19 +000091ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000092 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000093 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
94 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000095 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000096 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000097 ShouldCacheCodeCompletionResults(false),
98 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000099 CacheCodeCompletionCoolDown(0),
100 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000101 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000102 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000103 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
104 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000105}
Douglas Gregord03e8232010-04-05 21:10:19 +0000106
Daniel Dunbar764c0822009-12-01 09:51:01 +0000107ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000108 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000109 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000110 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000111 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-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 Gregor96c04262010-07-27 14:52:07 +0000126
127 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000128 delete PreambleBuffer;
129
Douglas Gregor16896c42010-10-28 15:44:59 +0000130 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000131
132 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000133 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000134 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
135 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000136}
137
138void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000139 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
140 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000141 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000142}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000143
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000147 const LangOptions &LangOpts,
148 bool &IsNestedNameSpecifier) {
149 IsNestedNameSpecifier = false;
150
Douglas Gregor39982192010-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 Gregor5e35d592010-09-14 23:59:36 +0000165 | (1 << (CodeCompletionContext::CCC_Type - 1))
166 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000181 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000182 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000183 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-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 Gregor39982192010-08-15 06:18:01 +0000190 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000192 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-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 Gregor5e35d592010-09-14 23:59:36 +0000198 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000203 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000204
205 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000206 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000207 }
208
209 return Contexts;
210}
211
Douglas Gregorb14904c2010-08-13 22:48:40 +0000212void ASTUnit::CacheCodeCompletionResults() {
213 if (!TheSema)
214 return;
215
Douglas Gregor16896c42010-10-28 15:44:59 +0000216 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000217 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000218
219 // Clear out the previous results.
220 ClearCachedCompletionResults();
221
222 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000223 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000224 llvm::SmallVector<Result, 8> Results;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000225 TheSema->GatherGlobalCodeCompletions(CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000226
227 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000228 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
229
Douglas Gregorb14904c2010-08-13 22:48:40 +0000230 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
231 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000232 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000233 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000234 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000235 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
236 CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000237 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000238 Ctx->getLangOptions(),
239 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000240 CachedResult.Priority = Results[I].Priority;
241 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000242 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000243
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000244 // Keep track of the type of this completion in an ASTContext-agnostic
245 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000246 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000247 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000248 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000249 CachedResult.Type = 0;
250 } else {
251 CanQualType CanUsageType
252 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
253 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
254
255 // Determine whether we have already seen this type. If so, we save
256 // ourselves the work of formatting the type string by using the
257 // temporary, CanQualType-based hash table to find the associated value.
258 unsigned &TypeValue = CompletionTypes[CanUsageType];
259 if (TypeValue == 0) {
260 TypeValue = CompletionTypes.size();
261 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
262 = TypeValue;
263 }
264
265 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000266 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000267
Douglas Gregor39982192010-08-15 06:18:01 +0000268 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000269
270 /// Handle nested-name-specifiers in C++.
271 if (TheSema->Context.getLangOptions().CPlusPlus &&
272 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
273 // The contexts in which a nested-name-specifier can appear in C++.
274 unsigned NNSContexts
275 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
276 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
277 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
278 | (1 << (CodeCompletionContext::CCC_Statement - 1))
279 | (1 << (CodeCompletionContext::CCC_Expression - 1))
280 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
281 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
282 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
283 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000284 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000285 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
286 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000287
288 if (isa<NamespaceDecl>(Results[I].Declaration) ||
289 isa<NamespaceAliasDecl>(Results[I].Declaration))
290 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
291
292 if (unsigned RemainingContexts
293 = NNSContexts & ~CachedResult.ShowInContexts) {
294 // If there any contexts where this completion can be a
295 // nested-name-specifier but isn't already an option, create a
296 // nested-name-specifier completion.
297 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000298 CachedResult.Completion
299 = Results[I].CreateCodeCompletionString(*TheSema,
300 CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000301 CachedResult.ShowInContexts = RemainingContexts;
302 CachedResult.Priority = CCP_NestedNameSpecifier;
303 CachedResult.TypeClass = STC_Void;
304 CachedResult.Type = 0;
305 CachedCompletionResults.push_back(CachedResult);
306 }
307 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000308 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000309 }
310
Douglas Gregorb14904c2010-08-13 22:48:40 +0000311 case Result::RK_Keyword:
312 case Result::RK_Pattern:
313 // Ignore keywords and patterns; we don't care, since they are so
314 // easily regenerated.
315 break;
316
317 case Result::RK_Macro: {
318 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000319 CachedResult.Completion
320 = Results[I].CreateCodeCompletionString(*TheSema,
321 CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000322 CachedResult.ShowInContexts
323 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
324 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
325 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
326 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
327 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
328 | (1 << (CodeCompletionContext::CCC_Statement - 1))
329 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000330 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000331 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000332 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
333 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
334
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000335
Douglas Gregorb14904c2010-08-13 22:48:40 +0000336 CachedResult.Priority = Results[I].Priority;
337 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000338 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000339 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000340 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000341 CachedCompletionResults.push_back(CachedResult);
342 break;
343 }
344 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000345 }
346
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000347 // Make a note of the state when we performed this caching.
348 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000349}
350
351void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000352 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000353 CachedCompletionTypes.clear();
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000354 CachedCompletionAllocator.Reset();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000355}
356
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000357namespace {
358
Sebastian Redl2c499f62010-08-18 23:56:43 +0000359/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000360/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000361class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000362 LangOptions &LangOpt;
363 HeaderSearch &HSI;
364 std::string &TargetTriple;
365 std::string &Predefines;
366 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000368 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000370public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000371 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000372 std::string &TargetTriple, std::string &Predefines,
373 unsigned &Counter)
374 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
375 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000376
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000377 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
378 LangOpt = LangOpts;
379 return false;
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000382 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000383 TargetTriple = Triple;
384 return false;
385 }
Mike Stump11289f42009-09-09 15:08:12 +0000386
Sebastian Redl8b41f302010-07-14 23:29:55 +0000387 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000388 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000389 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000390 Predefines = Buffers[0].Data;
391 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
392 Predefines += Buffers[I].Data;
393 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000394 return false;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Douglas Gregora2f49452010-03-16 19:09:18 +0000397 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000398 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
399 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000401 virtual void ReadCounter(unsigned Value) {
402 Counter = Value;
403 }
404};
405
Douglas Gregor33cdd812010-02-18 18:08:43 +0000406class StoredDiagnosticClient : public DiagnosticClient {
407 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
408
409public:
410 explicit StoredDiagnosticClient(
411 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
412 : StoredDiags(StoredDiags) { }
413
414 virtual void HandleDiagnostic(Diagnostic::Level Level,
415 const DiagnosticInfo &Info);
416};
417
418/// \brief RAII object that optionally captures diagnostics, if
419/// there is no diagnostic client to capture them already.
420class CaptureDroppedDiagnostics {
421 Diagnostic &Diags;
422 StoredDiagnosticClient Client;
423 DiagnosticClient *PreviousClient;
424
425public:
426 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000427 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000428 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000429 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000430 if (RequestCapture || Diags.getClient() == 0) {
431 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000432 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000433 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000434 }
435
436 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000437 if (Diags.getClient() == &Client) {
438 Diags.takeClient();
439 Diags.setClient(PreviousClient);
440 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000441 }
442};
443
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000444} // anonymous namespace
445
Douglas Gregor33cdd812010-02-18 18:08:43 +0000446void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
447 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000448 // Default implementation (Warnings/errors count).
449 DiagnosticClient::HandleDiagnostic(Level, Info);
450
Douglas Gregor33cdd812010-02-18 18:08:43 +0000451 StoredDiags.push_back(StoredDiagnostic(Level, Info));
452}
453
Steve Naroffc0683b92009-09-03 18:19:54 +0000454const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000455 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000456}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000457
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000458const std::string &ASTUnit::getASTFileName() {
459 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000460 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000461}
462
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000463llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000464 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000465 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000466 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000467}
468
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000469/// \brief Configure the diagnostics object for use with ASTUnit.
470void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000471 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000472 ASTUnit &AST, bool CaptureDiagnostics) {
473 if (!Diags.getPtr()) {
474 // No diagnostics engine was provided, so create our own diagnostics object
475 // with the default options.
476 DiagnosticOptions DiagOpts;
477 DiagnosticClient *Client = 0;
478 if (CaptureDiagnostics)
479 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000480 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
481 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000482 } else if (CaptureDiagnostics) {
483 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
484 }
485}
486
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000487ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000488 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000489 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000490 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000491 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000492 unsigned NumRemappedFiles,
493 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000494 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000495 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000496
Douglas Gregor16bef852009-10-16 20:01:17 +0000497 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000498 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000499 AST->Diagnostics = Diags;
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000500 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000501 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +0000502 AST->getFileManager()));
503 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000504
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000505 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
506 // Create the file entry for the file that we're mapping from.
507 const FileEntry *FromFile
508 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
509 RemappedFiles[I].second->getBufferSize(),
Chris Lattner5159f612010-11-23 08:35:12 +0000510 0);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000511 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000512 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000513 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000514 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000515 continue;
516 }
517
518 // Override the contents of the "from" file with the contents of
519 // the "to" file.
520 AST->getSourceManager().overrideFileContents(FromFile,
521 RemappedFiles[I].second);
522 }
523
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000524 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000525
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000526 LangOptions LangInfo;
527 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
528 std::string TargetTriple;
529 std::string Predefines;
530 unsigned Counter;
531
Sebastian Redl2c499f62010-08-18 23:56:43 +0000532 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000533
Sebastian Redl2c499f62010-08-18 23:56:43 +0000534 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000535 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000536 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000537 Predefines, Counter));
538
Sebastian Redl009e7f22010-10-05 16:15:19 +0000539 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000540 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000541 break;
Mike Stump11289f42009-09-09 15:08:12 +0000542
Sebastian Redl2c499f62010-08-18 23:56:43 +0000543 case ASTReader::Failure:
544 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000545 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000546 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000547 }
Mike Stump11289f42009-09-09 15:08:12 +0000548
Daniel Dunbara8a50932009-12-02 08:44:16 +0000549 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
550
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000551 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000552
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000554 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000555 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000556 TargetOptions TargetOpts;
557 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000558 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000559 TargetOpts.CPU = "";
560 TargetOpts.Features.clear();
561 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000562 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
563 TargetOpts));
564 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
565 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000566 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000567 Preprocessor &PP = *AST->PP.get();
568
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000569 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000570 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000571 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000573 // Create and initialize the ASTContext.
574
575 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000576 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000577 *AST->Target.get(),
578 PP.getIdentifierTable(),
579 PP.getSelectorTable(),
580 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000581 /* size_reserve = */0));
582 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000583
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000584 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000585
Sebastian Redl2c499f62010-08-18 23:56:43 +0000586 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000587 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000588 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000589 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000590 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000591 Context.setExternalSource(Source);
592
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000593 // Create an AST consumer, even though it isn't used.
594 AST->Consumer.reset(new ASTConsumer);
595
Sebastian Redl2c499f62010-08-18 23:56:43 +0000596 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000597 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
598 AST->TheSema->Initialize();
599 ReaderPtr->InitializeSema(*AST->TheSema);
600
Mike Stump11289f42009-09-09 15:08:12 +0000601 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000602}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000603
604namespace {
605
Daniel Dunbar644dca02009-12-04 08:17:33 +0000606class TopLevelDeclTrackerConsumer : public ASTConsumer {
607 ASTUnit &Unit;
608
609public:
610 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
611
612 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000613 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
614 Decl *D = *it;
615 // FIXME: Currently ObjC method declarations are incorrectly being
616 // reported as top-level declarations, even though their DeclContext
617 // is the containing ObjC @interface/@implementation. This is a
618 // fundamental problem in the parser right now.
619 if (isa<ObjCMethodDecl>(D))
620 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000621 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000622 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000623 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000624
625 // We're not interested in "interesting" decls.
626 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000627};
628
629class TopLevelDeclTrackerAction : public ASTFrontendAction {
630public:
631 ASTUnit &Unit;
632
Daniel Dunbar764c0822009-12-01 09:51:01 +0000633 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
634 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000635 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000636 }
637
638public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000639 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
640
Daniel Dunbar764c0822009-12-01 09:51:01 +0000641 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000642 virtual bool usesCompleteTranslationUnit() {
643 return Unit.isCompleteTranslationUnit();
644 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000645};
646
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000647class PrecompilePreambleConsumer : public PCHGenerator,
648 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000649 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000650 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000651
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000652public:
653 PrecompilePreambleConsumer(ASTUnit &Unit,
654 const Preprocessor &PP, bool Chaining,
655 const char *isysroot, llvm::raw_ostream *Out)
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000656 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit) { }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000657
Douglas Gregore9db88f2010-08-03 19:06:41 +0000658 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000659 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
660 Decl *D = *it;
661 // FIXME: Currently ObjC method declarations are incorrectly being
662 // reported as top-level declarations, even though their DeclContext
663 // is the containing ObjC @interface/@implementation. This is a
664 // fundamental problem in the parser right now.
665 if (isa<ObjCMethodDecl>(D))
666 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000667 TopLevelDecls.push_back(D);
668 }
669 }
670
671 virtual void HandleTranslationUnit(ASTContext &Ctx) {
672 PCHGenerator::HandleTranslationUnit(Ctx);
673 if (!Unit.getDiagnostics().hasErrorOccurred()) {
674 // Translate the top-level declarations we captured during
675 // parsing into declaration IDs in the precompiled
676 // preamble. This will allow us to deserialize those top-level
677 // declarations when requested.
678 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
679 Unit.addTopLevelDeclFromPreamble(
680 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000681 }
682 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000683
684 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
685 uint64_t Offset) {
686 Unit.addPreprocessedEntityFromPreamble(Offset);
687 }
688
689 virtual ASTSerializationListener *GetASTSerializationListener() {
690 return this;
691 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000692};
693
694class PrecompilePreambleAction : public ASTFrontendAction {
695 ASTUnit &Unit;
696
697public:
698 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
699
700 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
701 llvm::StringRef InFile) {
702 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000703 std::string OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000704 llvm::raw_ostream *OS = 0;
705 bool Chaining;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000706 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
707 OutputFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000708 OS, Chaining))
709 return 0;
710
711 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
712 Sysroot.c_str() : 0;
713 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
714 isysroot, OS);
715 }
716
717 virtual bool hasCodeCompletionSupport() const { return false; }
718 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000719 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000720};
721
Daniel Dunbar764c0822009-12-01 09:51:01 +0000722}
723
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000724/// Parse the source file into a translation unit using the given compiler
725/// invocation, replacing the current translation unit.
726///
727/// \returns True if a failure occurred that causes the ASTUnit not to
728/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000729bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000730 delete SavedMainFileBuffer;
731 SavedMainFileBuffer = 0;
732
Douglas Gregora0734c52010-08-19 01:33:06 +0000733 if (!Invocation.get()) {
734 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000735 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000736 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000737
Daniel Dunbar764c0822009-12-01 09:51:01 +0000738 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000739 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000740 Clang.setInvocation(Invocation.take());
741 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
742
Douglas Gregor8e984da2010-08-04 16:47:14 +0000743 // Set up diagnostics, capturing any diagnostics that would
744 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000745 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000746
Daniel Dunbar764c0822009-12-01 09:51:01 +0000747 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +0000748 Clang.getTargetOpts().Features = TargetFeatures;
Daniel Dunbar764c0822009-12-01 09:51:01 +0000749 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
750 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000751 if (!Clang.hasTarget()) {
752 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000753 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000754 }
755
Daniel Dunbar764c0822009-12-01 09:51:01 +0000756 // Inform the target of the language options.
757 //
758 // FIXME: We shouldn't need to do this, the target should be immutable once
759 // created. This complexity should be lifted elsewhere.
760 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000761
Daniel Dunbar764c0822009-12-01 09:51:01 +0000762 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
763 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000764 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000765 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000766 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
767 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000768
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000769 // Configure the various subsystems.
770 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000771 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000772 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
773 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000774 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000775 Ctx.reset();
776 PP.reset();
777
778 // Clear out old caches and data.
779 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000780 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000781 CleanTemporaryFiles();
782 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000783
Douglas Gregor7b02b582010-08-20 00:02:33 +0000784 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000785 StoredDiagnostics.erase(
786 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
787 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000788 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000789 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000790 }
791
Daniel Dunbar764c0822009-12-01 09:51:01 +0000792 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000793 Clang.setFileManager(&getFileManager());
794
Daniel Dunbar764c0822009-12-01 09:51:01 +0000795 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000796 Clang.setSourceManager(&getSourceManager());
797
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000798 // If the main file has been overridden due to the use of a preamble,
799 // make that override happen and introduce the preamble.
800 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000801 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000802 if (OverrideMainBuffer) {
803 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
804 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
805 PreprocessorOpts.PrecompiledPreambleBytes.second
806 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000807 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000808 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000809 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000810
Douglas Gregord9a30af2010-08-02 20:51:39 +0000811 // The stored diagnostic has the old source manager in it; update
812 // the locations to refer into the new source manager. Since we've
813 // been careful to make sure that the source manager's state
814 // before and after are identical, so that we can reuse the source
815 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000816 for (unsigned I = NumStoredDiagnosticsFromDriver,
817 N = StoredDiagnostics.size();
818 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000819 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
820 getSourceManager());
821 StoredDiagnostics[I].setLocation(Loc);
822 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000823
824 // Keep track of the override buffer;
825 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000826 } else {
827 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
828 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000829 }
830
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000831 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
832 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000833 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000834 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000835 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000836
Daniel Dunbar644dca02009-12-04 08:17:33 +0000837 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000838
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000839 // Steal the created target, context, and preprocessor, and take back the
840 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000841 TheSema.reset(Clang.takeSema());
842 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000843 Ctx.reset(Clang.takeASTContext());
844 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000845 Clang.takeSourceManager();
846 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000847 Target.reset(Clang.takeTarget());
848
Daniel Dunbar644dca02009-12-04 08:17:33 +0000849 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000850
851 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000852 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000853 PreprocessorOpts.eraseRemappedFile(
854 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000855 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
856 }
857
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000858 Invocation.reset(Clang.takeInvocation());
Douglas Gregoraca48a52010-12-09 21:27:43 +0000859
860 if (ShouldCacheCodeCompletionResults) {
861 if (CacheCodeCompletionCoolDown > 0)
862 --CacheCodeCompletionCoolDown;
863 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
864 CacheCodeCompletionResults();
865 }
866
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000867 return false;
868
Daniel Dunbar764c0822009-12-01 09:51:01 +0000869error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000870 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000871 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000872 PreprocessorOpts.eraseRemappedFile(
873 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000874 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000875 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000876 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000877 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000878
Douglas Gregorefc46952010-10-12 16:25:54 +0000879 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000880 Clang.takeSourceManager();
881 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000882 Invocation.reset(Clang.takeInvocation());
883 return true;
884}
885
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000886/// \brief Simple function to retrieve a path for a preamble precompiled header.
887static std::string GetPreamblePCHPath() {
888 // FIXME: This is lame; sys::Path should provide this function (in particular,
889 // it should know how to find the temporary files dir).
890 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000891 // FIXME: This is a hack so that we can override the preamble file during
892 // crash-recovery testing, which is the only case where the preamble files
893 // are not necessarily cleaned up.
894 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
895 if (TmpFile)
896 return TmpFile;
897
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000898 std::string Error;
899 const char *TmpDir = ::getenv("TMPDIR");
900 if (!TmpDir)
901 TmpDir = ::getenv("TEMP");
902 if (!TmpDir)
903 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000904#ifdef LLVM_ON_WIN32
905 if (!TmpDir)
906 TmpDir = ::getenv("USERPROFILE");
907#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000908 if (!TmpDir)
909 TmpDir = "/tmp";
910 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000911 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000912 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000913 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000914 if (P.createTemporaryFileOnDisk())
915 return std::string();
916
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000917 return P.str();
918}
919
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000920/// \brief Compute the preamble for the main file, providing the source buffer
921/// that corresponds to the main file along with a pair (bytes, start-of-line)
922/// that describes the preamble.
923std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000924ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
925 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000926 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000927 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000928 CreatedBuffer = false;
929
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000930 // Try to determine if the main file has been remapped, either from the
931 // command line (to another file) or directly through the compiler invocation
932 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000933 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000934 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
935 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
936 // Check whether there is a file-file remapping of the main file
937 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000938 M = PreprocessorOpts.remapped_file_begin(),
939 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000940 M != E;
941 ++M) {
942 llvm::sys::PathWithStatus MPath(M->first);
943 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
944 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
945 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000946 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000947 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000948 CreatedBuffer = false;
949 }
950
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000951 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000952 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000953 return std::make_pair((llvm::MemoryBuffer*)0,
954 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000955 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000956 }
957 }
958 }
959
960 // Check whether there is a file-buffer remapping. It supercedes the
961 // file-file remapping.
962 for (PreprocessorOptions::remapped_file_buffer_iterator
963 M = PreprocessorOpts.remapped_file_buffer_begin(),
964 E = PreprocessorOpts.remapped_file_buffer_end();
965 M != E;
966 ++M) {
967 llvm::sys::PathWithStatus MPath(M->first);
968 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
969 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
970 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000971 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000972 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000973 CreatedBuffer = false;
974 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000975
Douglas Gregor4dde7492010-07-23 23:58:40 +0000976 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000977 }
978 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000979 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000980 }
981
982 // If the main source file was not remapped, load it now.
983 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000984 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000985 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000986 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000987
988 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000989 }
990
Douglas Gregor028d3e42010-08-09 20:45:32 +0000991 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000992}
993
Douglas Gregor6481ef12010-07-24 00:38:13 +0000994static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +0000995 unsigned NewSize,
996 llvm::StringRef NewName) {
997 llvm::MemoryBuffer *Result
998 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
999 memcpy(const_cast<char*>(Result->getBufferStart()),
1000 Old->getBufferStart(), Old->getBufferSize());
1001 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001002 ' ', NewSize - Old->getBufferSize() - 1);
1003 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001004
Douglas Gregor6481ef12010-07-24 00:38:13 +00001005 return Result;
1006}
1007
Douglas Gregor4dde7492010-07-23 23:58:40 +00001008/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1009/// the source file.
1010///
1011/// This routine will compute the preamble of the main source file. If a
1012/// non-trivial preamble is found, it will precompile that preamble into a
1013/// precompiled header so that the precompiled preamble can be used to reduce
1014/// reparsing time. If a precompiled preamble has already been constructed,
1015/// this routine will determine if it is still valid and, if so, avoid
1016/// rebuilding the precompiled preamble.
1017///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001018/// \param AllowRebuild When true (the default), this routine is
1019/// allowed to rebuild the precompiled preamble if it is found to be
1020/// out-of-date.
1021///
1022/// \param MaxLines When non-zero, the maximum number of lines that
1023/// can occur within the preamble.
1024///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001025/// \returns If the precompiled preamble can be used, returns a newly-allocated
1026/// buffer that should be used in place of the main file when doing so.
1027/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001028llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001029 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001030 bool AllowRebuild,
1031 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001032 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1033 PreprocessorOptions &PreprocessorOpts
1034 = PreambleInvocation.getPreprocessorOpts();
1035
1036 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001037 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001038 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001039
Douglas Gregor3edb1672010-11-16 20:45:51 +00001040 // If ComputePreamble() Take ownership of the
1041 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1042 if (CreatedPreambleBuffer)
1043 OwnedPreambleBuffer.reset(NewPreamble.first);
1044
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001045 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001046 // We couldn't find a preamble in the main source. Clear out the current
1047 // preamble, if we have one. It's obviously no good any more.
1048 Preamble.clear();
1049 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001050 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001051 PreambleFile.clear();
1052 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001053
1054 // The next time we actually see a preamble, precompile it.
1055 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001056 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001057 }
1058
1059 if (!Preamble.empty()) {
1060 // We've previously computed a preamble. Check whether we have the same
1061 // preamble now that we did before, and that there's enough space in
1062 // the main-file buffer within the precompiled preamble to fit the
1063 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001064 if (Preamble.size() == NewPreamble.second.first &&
1065 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001066 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001067 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001068 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001069 // The preamble has not changed. We may be able to re-use the precompiled
1070 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001071
Douglas Gregor0e119552010-07-31 00:40:00 +00001072 // Check that none of the files used by the preamble have changed.
1073 bool AnyFileChanged = false;
1074
1075 // First, make a record of those files that have been overridden via
1076 // remapping or unsaved_files.
1077 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1078 for (PreprocessorOptions::remapped_file_iterator
1079 R = PreprocessorOpts.remapped_file_begin(),
1080 REnd = PreprocessorOpts.remapped_file_end();
1081 !AnyFileChanged && R != REnd;
1082 ++R) {
1083 struct stat StatBuf;
1084 if (stat(R->second.c_str(), &StatBuf)) {
1085 // If we can't stat the file we're remapping to, assume that something
1086 // horrible happened.
1087 AnyFileChanged = true;
1088 break;
1089 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001090
Douglas Gregor0e119552010-07-31 00:40:00 +00001091 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1092 StatBuf.st_mtime);
1093 }
1094 for (PreprocessorOptions::remapped_file_buffer_iterator
1095 R = PreprocessorOpts.remapped_file_buffer_begin(),
1096 REnd = PreprocessorOpts.remapped_file_buffer_end();
1097 !AnyFileChanged && R != REnd;
1098 ++R) {
1099 // FIXME: Should we actually compare the contents of file->buffer
1100 // remappings?
1101 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1102 0);
1103 }
1104
1105 // Check whether anything has changed.
1106 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1107 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1108 !AnyFileChanged && F != FEnd;
1109 ++F) {
1110 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1111 = OverriddenFiles.find(F->first());
1112 if (Overridden != OverriddenFiles.end()) {
1113 // This file was remapped; check whether the newly-mapped file
1114 // matches up with the previous mapping.
1115 if (Overridden->second != F->second)
1116 AnyFileChanged = true;
1117 continue;
1118 }
1119
1120 // The file was not remapped; check whether it has changed on disk.
1121 struct stat StatBuf;
1122 if (stat(F->first(), &StatBuf)) {
1123 // If we can't stat the file, assume that something horrible happened.
1124 AnyFileChanged = true;
1125 } else if (StatBuf.st_size != F->second.first ||
1126 StatBuf.st_mtime != F->second.second)
1127 AnyFileChanged = true;
1128 }
1129
1130 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001131 // Okay! We can re-use the precompiled preamble.
1132
1133 // Set the state of the diagnostic object to mimic its state
1134 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001135 // FIXME: This won't catch any #pragma push warning changes that
1136 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001137 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001138 ProcessWarningOptions(getDiagnostics(),
1139 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001140 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1141 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1142 StoredDiagnostics.erase(
1143 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1144 StoredDiagnostics.end());
1145
1146 // Create a version of the main file buffer that is padded to
1147 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001148 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001149 PreambleReservedSize,
1150 FrontendOpts.Inputs[0].second);
1151 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001152 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001153
1154 // If we aren't allowed to rebuild the precompiled preamble, just
1155 // return now.
1156 if (!AllowRebuild)
1157 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001158
Douglas Gregor4dde7492010-07-23 23:58:40 +00001159 // We can't reuse the previously-computed preamble. Build a new one.
1160 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001161 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001162 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001163 } else if (!AllowRebuild) {
1164 // We aren't allowed to rebuild the precompiled preamble; just
1165 // return now.
1166 return 0;
1167 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001168
1169 // If the preamble rebuild counter > 1, it's because we previously
1170 // failed to build a preamble and we're not yet ready to try
1171 // again. Decrement the counter and return a failure.
1172 if (PreambleRebuildCounter > 1) {
1173 --PreambleRebuildCounter;
1174 return 0;
1175 }
1176
Douglas Gregore10f0e52010-09-11 17:56:52 +00001177 // Create a temporary file for the precompiled preamble. In rare
1178 // circumstances, this can fail.
1179 std::string PreamblePCHPath = GetPreamblePCHPath();
1180 if (PreamblePCHPath.empty()) {
1181 // Try again next time.
1182 PreambleRebuildCounter = 1;
1183 return 0;
1184 }
1185
Douglas Gregor4dde7492010-07-23 23:58:40 +00001186 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001187 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001188 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189
1190 // Create a new buffer that stores the preamble. The buffer also contains
1191 // extra space for the original contents of the file (which will be present
1192 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001193 // grows.
1194 PreambleReservedSize = NewPreamble.first->getBufferSize();
1195 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001196 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001197 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001198 PreambleReservedSize *= 2;
1199
Douglas Gregord9a30af2010-08-02 20:51:39 +00001200 // Save the preamble text for later; we'll need to compare against it for
1201 // subsequent reparses.
1202 Preamble.assign(NewPreamble.first->getBufferStart(),
1203 NewPreamble.first->getBufferStart()
1204 + NewPreamble.second.first);
1205 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1206
Douglas Gregora0734c52010-08-19 01:33:06 +00001207 delete PreambleBuffer;
1208 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001209 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001210 FrontendOpts.Inputs[0].second);
1211 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001212 NewPreamble.first->getBufferStart(), Preamble.size());
1213 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001214 ' ', PreambleReservedSize - Preamble.size() - 1);
1215 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001216
1217 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001218 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1220
1221 // Tell the compiler invocation to generate a temporary precompiled header.
1222 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001223 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001224 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001225 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001226 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1227 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001228
1229 // Create the compiler instance to use for building the precompiled preamble.
1230 CompilerInstance Clang;
1231 Clang.setInvocation(&PreambleInvocation);
1232 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1233
Douglas Gregor8e984da2010-08-04 16:47:14 +00001234 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001235 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236
1237 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001238 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001239 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1240 Clang.getTargetOpts()));
1241 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001242 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1243 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001244 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001245 PreprocessorOpts.eraseRemappedFile(
1246 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001247 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001248 }
1249
1250 // Inform the target of the language options.
1251 //
1252 // FIXME: We shouldn't need to do this, the target should be immutable once
1253 // created. This complexity should be lifted elsewhere.
1254 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1255
1256 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1257 "Invocation must have exactly one source file!");
1258 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1259 "FIXME: AST inputs not yet supported here!");
1260 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1261 "IR inputs not support here!");
1262
1263 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001264 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001265 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001266 StoredDiagnostics.erase(
1267 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1268 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001269 TopLevelDecls.clear();
1270 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001271 PreprocessedEntities.clear();
1272 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001273
1274 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner3f5a9ef2010-11-23 07:51:02 +00001275 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001276
1277 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001278 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +00001279 Clang.getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001280
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001281 llvm::OwningPtr<PrecompilePreambleAction> Act;
1282 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001283 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1284 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001285 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001286 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1287 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001288 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001289 PreprocessorOpts.eraseRemappedFile(
1290 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001291 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001292 }
1293
1294 Act->Execute();
1295 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001296 Clang.takeInvocation();
1297
Douglas Gregore9db88f2010-08-03 19:06:41 +00001298 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001299 // There were errors parsing the preamble, so no precompiled header was
1300 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001301 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001302 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1303 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001304 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001305 PreprocessedEntities.clear();
1306 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001307 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001308 PreprocessorOpts.eraseRemappedFile(
1309 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001310 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001311 }
1312
1313 // Keep track of the preamble we precompiled.
1314 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001315 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1316 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001317
1318 // Keep track of all of the files that the source manager knows about,
1319 // so we can verify whether they have changed or not.
1320 FilesInPreamble.clear();
1321 SourceManager &SourceMgr = Clang.getSourceManager();
1322 const llvm::MemoryBuffer *MainFileBuffer
1323 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1324 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1325 FEnd = SourceMgr.fileinfo_end();
1326 F != FEnd;
1327 ++F) {
1328 const FileEntry *File = F->second->Entry;
1329 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1330 continue;
1331
1332 FilesInPreamble[File->getName()]
1333 = std::make_pair(F->second->getSize(), File->getModificationTime());
1334 }
1335
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001336 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001337 PreprocessorOpts.eraseRemappedFile(
1338 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001339 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001340 PreambleReservedSize,
1341 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001342}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001343
Douglas Gregore9db88f2010-08-03 19:06:41 +00001344void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1345 std::vector<Decl *> Resolved;
1346 Resolved.reserve(TopLevelDeclsInPreamble.size());
1347 ExternalASTSource &Source = *getASTContext().getExternalSource();
1348 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1349 // Resolve the declaration ID to an actual declaration, possibly
1350 // deserializing the declaration in the process.
1351 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1352 if (D)
1353 Resolved.push_back(D);
1354 }
1355 TopLevelDeclsInPreamble.clear();
1356 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1357}
1358
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001359void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1360 if (!PP)
1361 return;
1362
1363 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1364 if (!PPRec)
1365 return;
1366
1367 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1368 if (!External)
1369 return;
1370
1371 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1372 if (PreprocessedEntity *PE
Douglas Gregor46c50012011-02-11 19:46:30 +00001373 = External->ReadPreprocessedEntityAtOffset(
1374 PreprocessedEntitiesInPreamble[I]))
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001375 PreprocessedEntities.push_back(PE);
1376 }
1377
1378 if (PreprocessedEntities.empty())
1379 return;
1380
1381 PreprocessedEntities.insert(PreprocessedEntities.end(),
1382 PPRec->begin(true), PPRec->end(true));
1383}
1384
1385ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1386 if (!PreprocessedEntitiesInPreamble.empty() &&
1387 PreprocessedEntities.empty())
1388 RealizePreprocessedEntitiesFromPreamble();
1389
1390 if (PreprocessedEntities.empty())
1391 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1392 return PPRec->begin(true);
1393
1394 return PreprocessedEntities.begin();
1395}
1396
1397ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1398 if (!PreprocessedEntitiesInPreamble.empty() &&
1399 PreprocessedEntities.empty())
1400 RealizePreprocessedEntitiesFromPreamble();
1401
1402 if (PreprocessedEntities.empty())
1403 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1404 return PPRec->end(true);
1405
1406 return PreprocessedEntities.end();
1407}
1408
Douglas Gregore9db88f2010-08-03 19:06:41 +00001409unsigned ASTUnit::getMaxPCHLevel() const {
1410 if (!getOnlyLocalDecls())
1411 return Decl::MaxPCHLevel;
1412
Sebastian Redl009e7f22010-10-05 16:15:19 +00001413 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001414}
1415
Douglas Gregor16896c42010-10-28 15:44:59 +00001416llvm::StringRef ASTUnit::getMainFileName() const {
1417 return Invocation->getFrontendOpts().Inputs[0].second;
1418}
1419
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001420bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1421 if (!Invocation)
1422 return true;
1423
1424 // We'll manage file buffers ourselves.
1425 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1426 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001427 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001428
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001429 // Save the target features.
1430 TargetFeatures = Invocation->getTargetOpts().Features;
1431
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001432 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001433 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001434 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001435 OverrideMainBuffer
1436 = getMainBufferWithPrecompiledPreamble(*Invocation);
1437 }
1438
Douglas Gregor16896c42010-10-28 15:44:59 +00001439 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001440 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001441
Douglas Gregor16896c42010-10-28 15:44:59 +00001442 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001443}
1444
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001445ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1446 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1447 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001448 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001449 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001450 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001451 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001452 // Create the AST unit.
1453 llvm::OwningPtr<ASTUnit> AST;
1454 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001455 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001456 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001457 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001458 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001459 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001460 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001461 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001462 AST->Invocation.reset(CI);
1463
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001464 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001465}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001466
1467ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1468 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001469 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001470 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001471 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001472 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001473 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001474 unsigned NumRemappedFiles,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001475 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001476 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001477 bool CacheCodeCompletionResults,
1478 bool CXXPrecompilePreamble,
1479 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001480 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001481 // No diagnostics engine was provided, so create our own diagnostics object
1482 // with the default options.
1483 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001484 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1485 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001486 }
1487
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001488 llvm::SmallVector<const char *, 16> Args;
1489 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1490 Args.insert(Args.end(), ArgBegin, ArgEnd);
1491
1492 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1493 // also want to force it to use clang.
1494 Args.push_back("-fsyntax-only");
1495
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001496 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1497
1498 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001499
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001500 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001501 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001502 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001503
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001504 // FIXME: We shouldn't have to pass in the path info.
1505 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1506 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001507
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001508 // Don't check that inputs exist, they have been remapped.
1509 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001510
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001511 llvm::OwningPtr<driver::Compilation> C(
1512 TheDriver.BuildCompilation(Args.size(), Args.data()));
1513
1514 // We expect to get back exactly one command job, if we didn't something
1515 // failed.
1516 const driver::JobList &Jobs = C->getJobs();
1517 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1518 llvm::SmallString<256> Msg;
1519 llvm::raw_svector_ostream OS(Msg);
1520 C->PrintJob(OS, C->getJobs(), "; ", true);
1521 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1522 return 0;
1523 }
1524
1525 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1526 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1527 Diags->Report(diag::err_fe_expected_clang_command);
1528 return 0;
1529 }
1530
1531 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1532 CI.reset(new CompilerInvocation);
1533 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001534 const_cast<const char **>(CCArgs.data()),
1535 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001536 CCArgs.size(),
1537 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001538 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001539
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001540 // Override any files that need remapping
1541 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001542 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001543 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001544
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001545 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001546 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001547
Douglas Gregorf5a18542010-10-27 17:24:53 +00001548 // Check whether we should precompile the preamble and/or use chained PCH.
1549 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1550 if (CI->getLangOpts().CPlusPlus) {
1551 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1552
1553 if (PrecompilePreamble && !CXXChainedPCH &&
1554 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1555 PrecompilePreamble = false;
1556 }
1557
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001558 // Create the AST unit.
1559 llvm::OwningPtr<ASTUnit> AST;
1560 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001561 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001562 AST->Diagnostics = Diags;
Chris Lattner5159f612010-11-23 08:35:12 +00001563
1564 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001565 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001566 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001567 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1568 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001569 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001570 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1571 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1572 AST->StoredDiagnostics.swap(StoredDiagnostics);
1573 AST->Invocation.reset(CI.take());
Chris Lattner5159f612010-11-23 08:35:12 +00001574 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001575}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001576
1577bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1578 if (!Invocation.get())
1579 return true;
1580
Douglas Gregor16896c42010-10-28 15:44:59 +00001581 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001582 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001583
Douglas Gregor0e119552010-07-31 00:40:00 +00001584 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001585 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001586 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001587 for (PreprocessorOptions::remapped_file_buffer_iterator
1588 R = PPOpts.remapped_file_buffer_begin(),
1589 REnd = PPOpts.remapped_file_buffer_end();
1590 R != REnd;
1591 ++R) {
1592 delete R->second;
1593 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001594 Invocation->getPreprocessorOpts().clearRemappedFiles();
1595 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1596 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1597 RemappedFiles[I].second);
1598
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001599 // If we have a preamble file lying around, or if we might try to
1600 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001601 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001602 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001603 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001604
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001605 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001606 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001607 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001608 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1609 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001610
Douglas Gregor4dde7492010-07-23 23:58:40 +00001611 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001612 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001613 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001614}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001615
Douglas Gregorb14904c2010-08-13 22:48:40 +00001616//----------------------------------------------------------------------------//
1617// Code completion
1618//----------------------------------------------------------------------------//
1619
1620namespace {
1621 /// \brief Code completion consumer that combines the cached code-completion
1622 /// results from an ASTUnit with the code-completion results provided to it,
1623 /// then passes the result on to
1624 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1625 unsigned NormalContexts;
1626 ASTUnit &AST;
1627 CodeCompleteConsumer &Next;
1628
1629 public:
1630 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001631 bool IncludeMacros, bool IncludeCodePatterns,
1632 bool IncludeGlobals)
1633 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001634 Next.isOutputBinary()), AST(AST), Next(Next)
1635 {
1636 // Compute the set of contexts in which we will look when we don't have
1637 // any information about the specific context.
1638 NormalContexts
1639 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1640 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1641 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1642 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1643 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1644 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1645 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1646 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001647 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001648 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1649 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001650
Douglas Gregorb14904c2010-08-13 22:48:40 +00001651 if (AST.getASTContext().getLangOptions().CPlusPlus)
1652 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1653 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1654 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1655 }
1656
1657 virtual void ProcessCodeCompleteResults(Sema &S,
1658 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001659 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001660 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001661
1662 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1663 OverloadCandidate *Candidates,
1664 unsigned NumCandidates) {
1665 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1666 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001667
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001668 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001669 return Next.getAllocator();
1670 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001671 };
1672}
Douglas Gregord46cf182010-08-16 20:01:48 +00001673
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001674/// \brief Helper function that computes which global names are hidden by the
1675/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001676static void CalculateHiddenNames(const CodeCompletionContext &Context,
1677 CodeCompletionResult *Results,
1678 unsigned NumResults,
1679 ASTContext &Ctx,
1680 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001681 bool OnlyTagNames = false;
1682 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001683 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001684 case CodeCompletionContext::CCC_TopLevel:
1685 case CodeCompletionContext::CCC_ObjCInterface:
1686 case CodeCompletionContext::CCC_ObjCImplementation:
1687 case CodeCompletionContext::CCC_ObjCIvarList:
1688 case CodeCompletionContext::CCC_ClassStructUnion:
1689 case CodeCompletionContext::CCC_Statement:
1690 case CodeCompletionContext::CCC_Expression:
1691 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1692 case CodeCompletionContext::CCC_MemberAccess:
1693 case CodeCompletionContext::CCC_Namespace:
1694 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001695 case CodeCompletionContext::CCC_Name:
1696 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001697 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001698 break;
1699
1700 case CodeCompletionContext::CCC_EnumTag:
1701 case CodeCompletionContext::CCC_UnionTag:
1702 case CodeCompletionContext::CCC_ClassOrStructTag:
1703 OnlyTagNames = true;
1704 break;
1705
1706 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001707 case CodeCompletionContext::CCC_MacroName:
1708 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001709 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001710 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001711 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001712 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001713 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001714 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001715 // We're looking for nothing, or we're looking for names that cannot
1716 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001717 return;
1718 }
1719
John McCall276321a2010-08-25 06:19:51 +00001720 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001721 for (unsigned I = 0; I != NumResults; ++I) {
1722 if (Results[I].Kind != Result::RK_Declaration)
1723 continue;
1724
1725 unsigned IDNS
1726 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1727
1728 bool Hiding = false;
1729 if (OnlyTagNames)
1730 Hiding = (IDNS & Decl::IDNS_Tag);
1731 else {
1732 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001733 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1734 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001735 if (Ctx.getLangOptions().CPlusPlus)
1736 HiddenIDNS |= Decl::IDNS_Tag;
1737 Hiding = (IDNS & HiddenIDNS);
1738 }
1739
1740 if (!Hiding)
1741 continue;
1742
1743 DeclarationName Name = Results[I].Declaration->getDeclName();
1744 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1745 HiddenNames.insert(Identifier->getName());
1746 else
1747 HiddenNames.insert(Name.getAsString());
1748 }
1749}
1750
1751
Douglas Gregord46cf182010-08-16 20:01:48 +00001752void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1753 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001754 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001755 unsigned NumResults) {
1756 // Merge the results we were given with the results we cached.
1757 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001758 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001759 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001760 : (1 << (Context.getKind() - 1)));
1761
1762 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001763 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001764 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001765 llvm::SmallVector<Result, 8> AllResults;
1766 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001767 C = AST.cached_completion_begin(),
1768 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001769 C != CEnd; ++C) {
1770 // If the context we are in matches any of the contexts we are
1771 // interested in, we'll add this result.
1772 if ((C->ShowInContexts & InContexts) == 0)
1773 continue;
1774
1775 // If we haven't added any results previously, do so now.
1776 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001777 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1778 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001779 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1780 AddedResult = true;
1781 }
1782
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001783 // Determine whether this global completion result is hidden by a local
1784 // completion result. If so, skip it.
1785 if (C->Kind != CXCursor_MacroDefinition &&
1786 HiddenNames.count(C->Completion->getTypedText()))
1787 continue;
1788
Douglas Gregord46cf182010-08-16 20:01:48 +00001789 // Adjust priority based on similar type classes.
1790 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001791 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001792 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001793 if (!Context.getPreferredType().isNull()) {
1794 if (C->Kind == CXCursor_MacroDefinition) {
1795 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001796 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001797 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001798 } else if (C->Type) {
1799 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001800 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001801 Context.getPreferredType().getUnqualifiedType());
1802 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1803 if (ExpectedSTC == C->TypeClass) {
1804 // We know this type is similar; check for an exact match.
1805 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001806 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001807 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001808 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001809 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1810 Priority /= CCF_ExactTypeMatch;
1811 else
1812 Priority /= CCF_SimilarTypeMatch;
1813 }
1814 }
1815 }
1816
Douglas Gregor12785102010-08-24 20:21:13 +00001817 // Adjust the completion string, if required.
1818 if (C->Kind == CXCursor_MacroDefinition &&
1819 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1820 // Create a new code-completion string that just contains the
1821 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001822 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1823 C->Availability);
1824 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00001825 CursorKind = CXCursor_NotImplemented;
1826 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001827 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00001828 }
1829
Douglas Gregor8850aa32010-08-25 18:03:13 +00001830 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001831 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001832 }
1833
1834 // If we did not add any cached completion results, just forward the
1835 // results we were given to the next consumer.
1836 if (!AddedResult) {
1837 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1838 return;
1839 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001840
Douglas Gregord46cf182010-08-16 20:01:48 +00001841 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1842 AllResults.size());
1843}
1844
1845
1846
Douglas Gregor8e984da2010-08-04 16:47:14 +00001847void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1848 RemappedFile *RemappedFiles,
1849 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001850 bool IncludeMacros,
1851 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001852 CodeCompleteConsumer &Consumer,
1853 Diagnostic &Diag, LangOptions &LangOpts,
1854 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001855 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1856 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001857 if (!Invocation.get())
1858 return;
1859
Douglas Gregor16896c42010-10-28 15:44:59 +00001860 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001861 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1862 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00001863
Douglas Gregor8e984da2010-08-04 16:47:14 +00001864 CompilerInvocation CCInvocation(*Invocation);
1865 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1866 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001867
Douglas Gregorb14904c2010-08-13 22:48:40 +00001868 FrontendOpts.ShowMacrosInCodeCompletion
1869 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001870 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001871 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1872 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001873 FrontendOpts.CodeCompletionAt.FileName = File;
1874 FrontendOpts.CodeCompletionAt.Line = Line;
1875 FrontendOpts.CodeCompletionAt.Column = Column;
1876
1877 // Set the language options appropriately.
1878 LangOpts = CCInvocation.getLangOpts();
1879
1880 CompilerInstance Clang;
1881 Clang.setInvocation(&CCInvocation);
1882 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1883
1884 // Set up diagnostics, capturing any diagnostics produced.
1885 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001886 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001887 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001888 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00001889 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001890
1891 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001892 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001893 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1894 Clang.getTargetOpts()));
1895 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001896 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001897 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001898 }
1899
1900 // Inform the target of the language options.
1901 //
1902 // FIXME: We shouldn't need to do this, the target should be immutable once
1903 // created. This complexity should be lifted elsewhere.
1904 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1905
1906 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1907 "Invocation must have exactly one source file!");
1908 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1909 "FIXME: AST inputs not yet supported here!");
1910 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1911 "IR inputs not support here!");
1912
1913
1914 // Use the source and file managers that we were given.
1915 Clang.setFileManager(&FileMgr);
1916 Clang.setSourceManager(&SourceMgr);
1917
1918 // Remap files.
1919 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001920 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001921 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001922 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1923 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001924 OwnedBuffers.push_back(RemappedFiles[I].second);
1925 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001926
Douglas Gregorb14904c2010-08-13 22:48:40 +00001927 // Use the code completion consumer we were given, but adding any cached
1928 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00001929 AugmentedCodeCompleteConsumer *AugmentedConsumer
1930 = new AugmentedCodeCompleteConsumer(*this, Consumer,
1931 FrontendOpts.ShowMacrosInCodeCompletion,
1932 FrontendOpts.ShowCodePatternsInCodeCompletion,
1933 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
1934 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001935
Douglas Gregor028d3e42010-08-09 20:45:32 +00001936 // If we have a precompiled preamble, try to use it. We only allow
1937 // the use of the precompiled preamble if we're if the completion
1938 // point is within the main file, after the end of the precompiled
1939 // preamble.
1940 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1941 if (!PreambleFile.empty()) {
1942 using llvm::sys::FileStatus;
1943 llvm::sys::PathWithStatus CompleteFilePath(File);
1944 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1945 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1946 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1947 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001948 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001949 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1950 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001951 }
1952
1953 // If the main file has been overridden due to the use of a preamble,
1954 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001955 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001956 StoredDiagnostics.insert(StoredDiagnostics.end(),
1957 this->StoredDiagnostics.begin(),
1958 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001959 if (OverrideMainBuffer) {
1960 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1961 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1962 PreprocessorOpts.PrecompiledPreambleBytes.second
1963 = PreambleEndsAtStartOfLine;
1964 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1965 PreprocessorOpts.DisablePCHValidation = true;
1966
1967 // The stored diagnostics have the old source manager. Copy them
1968 // to our output set of stored diagnostics, updating the source
1969 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001970 for (unsigned I = NumStoredDiagnosticsFromDriver,
1971 N = this->StoredDiagnostics.size();
1972 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001973 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1974 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1975 StoredDiagnostics[I].setLocation(Loc);
1976 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001977
Douglas Gregorb97b6662010-08-20 00:59:43 +00001978 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001979 } else {
1980 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1981 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001982 }
1983
Douglas Gregor8e984da2010-08-04 16:47:14 +00001984 llvm::OwningPtr<SyntaxOnlyAction> Act;
1985 Act.reset(new SyntaxOnlyAction);
1986 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1987 Clang.getFrontendOpts().Inputs[0].first)) {
1988 Act->Execute();
1989 Act->EndSourceFile();
1990 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001991
Douglas Gregor8e984da2010-08-04 16:47:14 +00001992 // Steal back our resources.
1993 Clang.takeFileManager();
1994 Clang.takeSourceManager();
1995 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001996}
Douglas Gregore9386682010-08-13 05:36:37 +00001997
1998bool ASTUnit::Save(llvm::StringRef File) {
1999 if (getDiagnostics().hasErrorOccurred())
2000 return true;
2001
2002 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2003 // unconditionally create a stat cache when we parse the file?
2004 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00002005 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2006 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00002007 if (!ErrorInfo.empty() || Out.has_error())
2008 return true;
2009
2010 std::vector<unsigned char> Buffer;
2011 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002012 ASTWriter Writer(Stream);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002013 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregore9386682010-08-13 05:36:37 +00002014
2015 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002016 if (!Buffer.empty())
2017 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00002018 Out.close();
2019 return Out.has_error();
2020}