blob: 586002daef563c54e53aa825dfe5e62683e6ebd1 [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 Gregoraa98ed92010-01-23 00:14:00 +000038#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000039#include "llvm/Support/Host.h"
40#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000042#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000043#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000044#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000045#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000046using namespace clang;
47
Douglas Gregor16896c42010-10-28 15:44:59 +000048using llvm::TimeRecord;
49
50namespace {
51 class SimpleTimer {
52 bool WantTiming;
53 TimeRecord Start;
54 std::string Output;
55
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000056 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000057 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000058 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000059 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000060 }
61
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000062 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Douglas Gregor16896c42010-10-28 15:44:59 +000067 ~SimpleTimer() {
68 if (WantTiming) {
69 TimeRecord Elapsed = TimeRecord::getCurrentTime();
70 Elapsed -= Start;
71 llvm::errs() << Output << ':';
72 Elapsed.print(Elapsed, llvm::errs());
73 llvm::errs() << '\n';
74 }
75 }
76 };
77}
78
Douglas Gregorbb420ab2010-08-04 05:53:38 +000079/// \brief After failing to build a precompiled preamble (due to
80/// errors in the source that occurs in the preamble), the number of
81/// reparses during which we'll skip even trying to precompile the
82/// preamble.
83const unsigned DefaultPreambleRebuildInterval = 5;
84
Douglas Gregor68dbaea2010-11-17 00:13:31 +000085/// \brief Tracks the number of ASTUnit objects that are currently active.
86///
87/// Used for debugging purposes only.
88static unsigned ActiveASTUnitObjects;
89
Douglas Gregord03e8232010-04-05 21:10:19 +000090ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000091 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000092 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
93 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000094 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000095 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000096 ShouldCacheCodeCompletionResults(false),
97 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000098 CacheCodeCompletionCoolDown(0),
99 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000100 if (getenv("LIBCLANG_OBJTRACKING")) {
101 ++ActiveASTUnitObjects;
102 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
103 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000104}
Douglas Gregord03e8232010-04-05 21:10:19 +0000105
Daniel Dunbar764c0822009-12-01 09:51:01 +0000106ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000107 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000108 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000109 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000110 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000111
112 // Free the buffers associated with remapped files. We are required to
113 // perform this operation here because we explicitly request that the
114 // compiler instance *not* free these buffers for each invocation of the
115 // parser.
116 if (Invocation.get()) {
117 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
118 for (PreprocessorOptions::remapped_file_buffer_iterator
119 FB = PPOpts.remapped_file_buffer_begin(),
120 FBEnd = PPOpts.remapped_file_buffer_end();
121 FB != FBEnd;
122 ++FB)
123 delete FB->second;
124 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000125
126 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000127 delete PreambleBuffer;
128
Douglas Gregor16896c42010-10-28 15:44:59 +0000129 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000130
131 if (getenv("LIBCLANG_OBJTRACKING")) {
132 --ActiveASTUnitObjects;
133 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
134 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000135}
136
137void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000138 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
139 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000140 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000141}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000142
Douglas Gregor39982192010-08-15 06:18:01 +0000143/// \brief Determine the set of code-completion contexts in which this
144/// declaration should be shown.
145static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000146 const LangOptions &LangOpts,
147 bool &IsNestedNameSpecifier) {
148 IsNestedNameSpecifier = false;
149
Douglas Gregor39982192010-08-15 06:18:01 +0000150 if (isa<UsingShadowDecl>(ND))
151 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
152 if (!ND)
153 return 0;
154
155 unsigned Contexts = 0;
156 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
157 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
158 // Types can appear in these contexts.
159 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
160 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
161 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
162 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
163 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000164 | (1 << (CodeCompletionContext::CCC_Type - 1))
165 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000166
167 // In C++, types can appear in expressions contexts (for functional casts).
168 if (LangOpts.CPlusPlus)
169 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
170
171 // In Objective-C, message sends can send interfaces. In Objective-C++,
172 // all types are available due to functional casts.
173 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
174 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
175
176 // Deal with tag names.
177 if (isa<EnumDecl>(ND)) {
178 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
179
Douglas Gregor59cab552010-08-16 23:05:20 +0000180 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000181 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000182 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000183 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
184 if (Record->isUnion())
185 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
186 else
187 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
188
Douglas Gregor39982192010-08-15 06:18:01 +0000189 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000190 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000191 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000192 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000193 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
194 // Values can appear in these contexts.
195 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
196 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000197 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000198 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
199 } else if (isa<ObjCProtocolDecl>(ND)) {
200 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
201 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000202 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000203
204 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000205 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000206 }
207
208 return Contexts;
209}
210
Douglas Gregorb14904c2010-08-13 22:48:40 +0000211void ASTUnit::CacheCodeCompletionResults() {
212 if (!TheSema)
213 return;
214
Douglas Gregor16896c42010-10-28 15:44:59 +0000215 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000216 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000217
218 // Clear out the previous results.
219 ClearCachedCompletionResults();
220
221 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000222 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000223 llvm::SmallVector<Result, 8> Results;
224 TheSema->GatherGlobalCodeCompletions(Results);
225
226 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000227 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
228
Douglas Gregorb14904c2010-08-13 22:48:40 +0000229 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
230 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000231 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000232 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000233 CachedCodeCompletionResult CachedResult;
234 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
235 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000236 Ctx->getLangOptions(),
237 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000238 CachedResult.Priority = Results[I].Priority;
239 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000240 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000241
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000242 // Keep track of the type of this completion in an ASTContext-agnostic
243 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000244 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000245 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000246 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000247 CachedResult.Type = 0;
248 } else {
249 CanQualType CanUsageType
250 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
251 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
252
253 // Determine whether we have already seen this type. If so, we save
254 // ourselves the work of formatting the type string by using the
255 // temporary, CanQualType-based hash table to find the associated value.
256 unsigned &TypeValue = CompletionTypes[CanUsageType];
257 if (TypeValue == 0) {
258 TypeValue = CompletionTypes.size();
259 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
260 = TypeValue;
261 }
262
263 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000264 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000265
Douglas Gregor39982192010-08-15 06:18:01 +0000266 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000267
268 /// Handle nested-name-specifiers in C++.
269 if (TheSema->Context.getLangOptions().CPlusPlus &&
270 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
271 // The contexts in which a nested-name-specifier can appear in C++.
272 unsigned NNSContexts
273 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
274 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
275 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
276 | (1 << (CodeCompletionContext::CCC_Statement - 1))
277 | (1 << (CodeCompletionContext::CCC_Expression - 1))
278 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
279 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
280 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
281 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000282 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000283 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
284 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000285
286 if (isa<NamespaceDecl>(Results[I].Declaration) ||
287 isa<NamespaceAliasDecl>(Results[I].Declaration))
288 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
289
290 if (unsigned RemainingContexts
291 = NNSContexts & ~CachedResult.ShowInContexts) {
292 // If there any contexts where this completion can be a
293 // nested-name-specifier but isn't already an option, create a
294 // nested-name-specifier completion.
295 Results[I].StartsNestedNameSpecifier = true;
296 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
297 CachedResult.ShowInContexts = RemainingContexts;
298 CachedResult.Priority = CCP_NestedNameSpecifier;
299 CachedResult.TypeClass = STC_Void;
300 CachedResult.Type = 0;
301 CachedCompletionResults.push_back(CachedResult);
302 }
303 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000304 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000305 }
306
Douglas Gregorb14904c2010-08-13 22:48:40 +0000307 case Result::RK_Keyword:
308 case Result::RK_Pattern:
309 // Ignore keywords and patterns; we don't care, since they are so
310 // easily regenerated.
311 break;
312
313 case Result::RK_Macro: {
314 CachedCodeCompletionResult CachedResult;
315 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
316 CachedResult.ShowInContexts
317 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
318 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
319 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
320 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
321 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
322 | (1 << (CodeCompletionContext::CCC_Statement - 1))
323 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000324 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000325 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000326 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
327 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
328
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000329
Douglas Gregorb14904c2010-08-13 22:48:40 +0000330 CachedResult.Priority = Results[I].Priority;
331 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000332 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000333 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000334 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000335 CachedCompletionResults.push_back(CachedResult);
336 break;
337 }
338 }
339 Results[I].Destroy();
340 }
341
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000342 // Make a note of the state when we performed this caching.
343 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000344}
345
346void ASTUnit::ClearCachedCompletionResults() {
347 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
348 delete CachedCompletionResults[I].Completion;
349 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000350 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000351}
352
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000353namespace {
354
Sebastian Redl2c499f62010-08-18 23:56:43 +0000355/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000356/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000357class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000358 LangOptions &LangOpt;
359 HeaderSearch &HSI;
360 std::string &TargetTriple;
361 std::string &Predefines;
362 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000363
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000364 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000365
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000366public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000367 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000368 std::string &TargetTriple, std::string &Predefines,
369 unsigned &Counter)
370 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
371 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000372
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000373 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
374 LangOpt = LangOpts;
375 return false;
376 }
Mike Stump11289f42009-09-09 15:08:12 +0000377
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000378 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000379 TargetTriple = Triple;
380 return false;
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Sebastian Redl8b41f302010-07-14 23:29:55 +0000383 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000384 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000385 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000386 Predefines = Buffers[0].Data;
387 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
388 Predefines += Buffers[I].Data;
389 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000390 return false;
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregora2f49452010-03-16 19:09:18 +0000393 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000394 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000397 virtual void ReadCounter(unsigned Value) {
398 Counter = Value;
399 }
400};
401
Douglas Gregor33cdd812010-02-18 18:08:43 +0000402class StoredDiagnosticClient : public DiagnosticClient {
403 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
404
405public:
406 explicit StoredDiagnosticClient(
407 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
408 : StoredDiags(StoredDiags) { }
409
410 virtual void HandleDiagnostic(Diagnostic::Level Level,
411 const DiagnosticInfo &Info);
412};
413
414/// \brief RAII object that optionally captures diagnostics, if
415/// there is no diagnostic client to capture them already.
416class CaptureDroppedDiagnostics {
417 Diagnostic &Diags;
418 StoredDiagnosticClient Client;
419 DiagnosticClient *PreviousClient;
420
421public:
422 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000423 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000424 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000425 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000426 if (RequestCapture || Diags.getClient() == 0) {
427 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000428 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000429 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000430 }
431
432 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000433 if (Diags.getClient() == &Client) {
434 Diags.takeClient();
435 Diags.setClient(PreviousClient);
436 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000437 }
438};
439
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000440} // anonymous namespace
441
Douglas Gregor33cdd812010-02-18 18:08:43 +0000442void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
443 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000444 // Default implementation (Warnings/errors count).
445 DiagnosticClient::HandleDiagnostic(Level, Info);
446
Douglas Gregor33cdd812010-02-18 18:08:43 +0000447 StoredDiags.push_back(StoredDiagnostic(Level, Info));
448}
449
Steve Naroffc0683b92009-09-03 18:19:54 +0000450const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000451 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000452}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000453
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000454const std::string &ASTUnit::getASTFileName() {
455 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000456 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000457}
458
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000459llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000460 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000461 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000462 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000463}
464
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000465/// \brief Configure the diagnostics object for use with ASTUnit.
466void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
467 ASTUnit &AST, bool CaptureDiagnostics) {
468 if (!Diags.getPtr()) {
469 // No diagnostics engine was provided, so create our own diagnostics object
470 // with the default options.
471 DiagnosticOptions DiagOpts;
472 DiagnosticClient *Client = 0;
473 if (CaptureDiagnostics)
474 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
475 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0, Client);
476 } else if (CaptureDiagnostics) {
477 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
478 }
479}
480
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000481ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000482 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000483 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000484 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000485 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000486 unsigned NumRemappedFiles,
487 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000488 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000489 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000490
Douglas Gregor16bef852009-10-16 20:01:17 +0000491 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000492 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000493 AST->Diagnostics = Diags;
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000494 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000495 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +0000496 AST->getFileManager()));
497 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000498
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000499 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
500 // Create the file entry for the file that we're mapping from.
501 const FileEntry *FromFile
502 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
503 RemappedFiles[I].second->getBufferSize(),
Chris Lattner5159f612010-11-23 08:35:12 +0000504 0);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000505 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000506 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000507 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000508 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000509 continue;
510 }
511
512 // Override the contents of the "from" file with the contents of
513 // the "to" file.
514 AST->getSourceManager().overrideFileContents(FromFile,
515 RemappedFiles[I].second);
516 }
517
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000518 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000519
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 LangOptions LangInfo;
521 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
522 std::string TargetTriple;
523 std::string Predefines;
524 unsigned Counter;
525
Sebastian Redl2c499f62010-08-18 23:56:43 +0000526 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000527
Sebastian Redl2c499f62010-08-18 23:56:43 +0000528 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000529 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000530 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000531 Predefines, Counter));
532
Sebastian Redl009e7f22010-10-05 16:15:19 +0000533 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000534 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000535 break;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Sebastian Redl2c499f62010-08-18 23:56:43 +0000537 case ASTReader::Failure:
538 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000539 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000540 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000541 }
Mike Stump11289f42009-09-09 15:08:12 +0000542
Daniel Dunbara8a50932009-12-02 08:44:16 +0000543 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
544
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000545 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000546
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000547 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000548 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000549 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000550 TargetOptions TargetOpts;
551 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000552 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000553 TargetOpts.CPU = "";
554 TargetOpts.Features.clear();
555 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000556 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
557 TargetOpts));
558 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
559 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000560 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000561 Preprocessor &PP = *AST->PP.get();
562
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000563 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000564 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000565 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000566
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000567 // Create and initialize the ASTContext.
568
569 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000570 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000571 *AST->Target.get(),
572 PP.getIdentifierTable(),
573 PP.getSelectorTable(),
574 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000575 /* size_reserve = */0));
576 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000577
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000578 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000579
Sebastian Redl2c499f62010-08-18 23:56:43 +0000580 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000581 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000582 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000583 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000584 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000585 Context.setExternalSource(Source);
586
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000587 // Create an AST consumer, even though it isn't used.
588 AST->Consumer.reset(new ASTConsumer);
589
Sebastian Redl2c499f62010-08-18 23:56:43 +0000590 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000591 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
592 AST->TheSema->Initialize();
593 ReaderPtr->InitializeSema(*AST->TheSema);
594
Mike Stump11289f42009-09-09 15:08:12 +0000595 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000596}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000597
598namespace {
599
Daniel Dunbar644dca02009-12-04 08:17:33 +0000600class TopLevelDeclTrackerConsumer : public ASTConsumer {
601 ASTUnit &Unit;
602
603public:
604 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
605
606 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000607 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
608 Decl *D = *it;
609 // FIXME: Currently ObjC method declarations are incorrectly being
610 // reported as top-level declarations, even though their DeclContext
611 // is the containing ObjC @interface/@implementation. This is a
612 // fundamental problem in the parser right now.
613 if (isa<ObjCMethodDecl>(D))
614 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000615 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000616 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000617 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000618
619 // We're not interested in "interesting" decls.
620 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000621};
622
623class TopLevelDeclTrackerAction : public ASTFrontendAction {
624public:
625 ASTUnit &Unit;
626
Daniel Dunbar764c0822009-12-01 09:51:01 +0000627 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
628 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000629 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000630 }
631
632public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000633 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
634
Daniel Dunbar764c0822009-12-01 09:51:01 +0000635 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000636 virtual bool usesCompleteTranslationUnit() {
637 return Unit.isCompleteTranslationUnit();
638 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000639};
640
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000641class PrecompilePreambleConsumer : public PCHGenerator,
642 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000643 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000644 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000645
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000646public:
647 PrecompilePreambleConsumer(ASTUnit &Unit,
648 const Preprocessor &PP, bool Chaining,
649 const char *isysroot, llvm::raw_ostream *Out)
650 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
651
Douglas Gregore9db88f2010-08-03 19:06:41 +0000652 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000653 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
654 Decl *D = *it;
655 // FIXME: Currently ObjC method declarations are incorrectly being
656 // reported as top-level declarations, even though their DeclContext
657 // is the containing ObjC @interface/@implementation. This is a
658 // fundamental problem in the parser right now.
659 if (isa<ObjCMethodDecl>(D))
660 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000661 TopLevelDecls.push_back(D);
662 }
663 }
664
665 virtual void HandleTranslationUnit(ASTContext &Ctx) {
666 PCHGenerator::HandleTranslationUnit(Ctx);
667 if (!Unit.getDiagnostics().hasErrorOccurred()) {
668 // Translate the top-level declarations we captured during
669 // parsing into declaration IDs in the precompiled
670 // preamble. This will allow us to deserialize those top-level
671 // declarations when requested.
672 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
673 Unit.addTopLevelDeclFromPreamble(
674 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000675 }
676 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000677
678 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
679 uint64_t Offset) {
680 Unit.addPreprocessedEntityFromPreamble(Offset);
681 }
682
683 virtual ASTSerializationListener *GetASTSerializationListener() {
684 return this;
685 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000686};
687
688class PrecompilePreambleAction : public ASTFrontendAction {
689 ASTUnit &Unit;
690
691public:
692 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
693
694 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
695 llvm::StringRef InFile) {
696 std::string Sysroot;
697 llvm::raw_ostream *OS = 0;
698 bool Chaining;
699 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
700 OS, Chaining))
701 return 0;
702
703 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
704 Sysroot.c_str() : 0;
705 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
706 isysroot, OS);
707 }
708
709 virtual bool hasCodeCompletionSupport() const { return false; }
710 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000711 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000712};
713
Daniel Dunbar764c0822009-12-01 09:51:01 +0000714}
715
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000716/// Parse the source file into a translation unit using the given compiler
717/// invocation, replacing the current translation unit.
718///
719/// \returns True if a failure occurred that causes the ASTUnit not to
720/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000721bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000722 delete SavedMainFileBuffer;
723 SavedMainFileBuffer = 0;
724
Douglas Gregora0734c52010-08-19 01:33:06 +0000725 if (!Invocation.get()) {
726 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000727 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000728 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000729
Daniel Dunbar764c0822009-12-01 09:51:01 +0000730 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000731 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000732 Clang.setInvocation(Invocation.take());
733 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
734
Douglas Gregor8e984da2010-08-04 16:47:14 +0000735 // Set up diagnostics, capturing any diagnostics that would
736 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000737 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000738
Daniel Dunbar764c0822009-12-01 09:51:01 +0000739 // Create the target instance.
740 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
741 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000742 if (!Clang.hasTarget()) {
743 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000744 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000745 }
746
Daniel Dunbar764c0822009-12-01 09:51:01 +0000747 // Inform the target of the language options.
748 //
749 // FIXME: We shouldn't need to do this, the target should be immutable once
750 // created. This complexity should be lifted elsewhere.
751 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000752
Daniel Dunbar764c0822009-12-01 09:51:01 +0000753 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
754 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000755 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000756 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000757 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
758 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000759
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000760 // Configure the various subsystems.
761 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000762 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000763 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
764 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000765 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000766 Ctx.reset();
767 PP.reset();
768
769 // Clear out old caches and data.
770 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000771 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000772 CleanTemporaryFiles();
773 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000774
Douglas Gregor7b02b582010-08-20 00:02:33 +0000775 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000776 StoredDiagnostics.erase(
777 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
778 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000779 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000780 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000781 }
782
Daniel Dunbar764c0822009-12-01 09:51:01 +0000783 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000784 Clang.setFileManager(&getFileManager());
785
Daniel Dunbar764c0822009-12-01 09:51:01 +0000786 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000787 Clang.setSourceManager(&getSourceManager());
788
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000789 // If the main file has been overridden due to the use of a preamble,
790 // make that override happen and introduce the preamble.
791 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000792 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000793 if (OverrideMainBuffer) {
794 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
795 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
796 PreprocessorOpts.PrecompiledPreambleBytes.second
797 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000798 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000799 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000800 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000801
Douglas Gregord9a30af2010-08-02 20:51:39 +0000802 // The stored diagnostic has the old source manager in it; update
803 // the locations to refer into the new source manager. Since we've
804 // been careful to make sure that the source manager's state
805 // before and after are identical, so that we can reuse the source
806 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000807 for (unsigned I = NumStoredDiagnosticsFromDriver,
808 N = StoredDiagnostics.size();
809 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000810 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
811 getSourceManager());
812 StoredDiagnostics[I].setLocation(Loc);
813 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000814
815 // Keep track of the override buffer;
816 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000817 } else {
818 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
819 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000820 }
821
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000822 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
823 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000824 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000825 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000826 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000827
Daniel Dunbar644dca02009-12-04 08:17:33 +0000828 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000829
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000830 // Steal the created target, context, and preprocessor, and take back the
831 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000832 TheSema.reset(Clang.takeSema());
833 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000834 Ctx.reset(Clang.takeASTContext());
835 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000836 Clang.takeSourceManager();
837 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000838 Target.reset(Clang.takeTarget());
839
Daniel Dunbar644dca02009-12-04 08:17:33 +0000840 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000841
842 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000843 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000844 PreprocessorOpts.eraseRemappedFile(
845 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000846 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
847 }
848
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000849 Invocation.reset(Clang.takeInvocation());
850 return false;
851
Daniel Dunbar764c0822009-12-01 09:51:01 +0000852error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000853 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000854 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000855 PreprocessorOpts.eraseRemappedFile(
856 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000857 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000858 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000859 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000860 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000861
Douglas Gregorefc46952010-10-12 16:25:54 +0000862 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000863 Clang.takeSourceManager();
864 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000865 Invocation.reset(Clang.takeInvocation());
866 return true;
867}
868
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000869/// \brief Simple function to retrieve a path for a preamble precompiled header.
870static std::string GetPreamblePCHPath() {
871 // FIXME: This is lame; sys::Path should provide this function (in particular,
872 // it should know how to find the temporary files dir).
873 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000874 // FIXME: This is a hack so that we can override the preamble file during
875 // crash-recovery testing, which is the only case where the preamble files
876 // are not necessarily cleaned up.
877 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
878 if (TmpFile)
879 return TmpFile;
880
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000881 std::string Error;
882 const char *TmpDir = ::getenv("TMPDIR");
883 if (!TmpDir)
884 TmpDir = ::getenv("TEMP");
885 if (!TmpDir)
886 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000887#ifdef LLVM_ON_WIN32
888 if (!TmpDir)
889 TmpDir = ::getenv("USERPROFILE");
890#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000891 if (!TmpDir)
892 TmpDir = "/tmp";
893 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000894 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000895 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000896 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000897 if (P.createTemporaryFileOnDisk())
898 return std::string();
899
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000900 return P.str();
901}
902
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000903/// \brief Compute the preamble for the main file, providing the source buffer
904/// that corresponds to the main file along with a pair (bytes, start-of-line)
905/// that describes the preamble.
906std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000907ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
908 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000909 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000910 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000911 CreatedBuffer = false;
912
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000913 // Try to determine if the main file has been remapped, either from the
914 // command line (to another file) or directly through the compiler invocation
915 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000916 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000917 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
918 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
919 // Check whether there is a file-file remapping of the main file
920 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000921 M = PreprocessorOpts.remapped_file_begin(),
922 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000923 M != E;
924 ++M) {
925 llvm::sys::PathWithStatus MPath(M->first);
926 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
927 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
928 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000929 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000930 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000931 CreatedBuffer = false;
932 }
933
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000934 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000935 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000936 return std::make_pair((llvm::MemoryBuffer*)0,
937 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000938 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000939 }
940 }
941 }
942
943 // Check whether there is a file-buffer remapping. It supercedes the
944 // file-file remapping.
945 for (PreprocessorOptions::remapped_file_buffer_iterator
946 M = PreprocessorOpts.remapped_file_buffer_begin(),
947 E = PreprocessorOpts.remapped_file_buffer_end();
948 M != E;
949 ++M) {
950 llvm::sys::PathWithStatus MPath(M->first);
951 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
952 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
953 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000954 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000955 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000956 CreatedBuffer = false;
957 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000958
Douglas Gregor4dde7492010-07-23 23:58:40 +0000959 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000960 }
961 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000962 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000963 }
964
965 // If the main source file was not remapped, load it now.
966 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000967 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000968 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000969 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000970
971 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000972 }
973
Douglas Gregor028d3e42010-08-09 20:45:32 +0000974 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000975}
976
Douglas Gregor6481ef12010-07-24 00:38:13 +0000977static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +0000978 unsigned NewSize,
979 llvm::StringRef NewName) {
980 llvm::MemoryBuffer *Result
981 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
982 memcpy(const_cast<char*>(Result->getBufferStart()),
983 Old->getBufferStart(), Old->getBufferSize());
984 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000985 ' ', NewSize - Old->getBufferSize() - 1);
986 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000987
Douglas Gregor6481ef12010-07-24 00:38:13 +0000988 return Result;
989}
990
Douglas Gregor4dde7492010-07-23 23:58:40 +0000991/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
992/// the source file.
993///
994/// This routine will compute the preamble of the main source file. If a
995/// non-trivial preamble is found, it will precompile that preamble into a
996/// precompiled header so that the precompiled preamble can be used to reduce
997/// reparsing time. If a precompiled preamble has already been constructed,
998/// this routine will determine if it is still valid and, if so, avoid
999/// rebuilding the precompiled preamble.
1000///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001001/// \param AllowRebuild When true (the default), this routine is
1002/// allowed to rebuild the precompiled preamble if it is found to be
1003/// out-of-date.
1004///
1005/// \param MaxLines When non-zero, the maximum number of lines that
1006/// can occur within the preamble.
1007///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001008/// \returns If the precompiled preamble can be used, returns a newly-allocated
1009/// buffer that should be used in place of the main file when doing so.
1010/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001011llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001012 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001013 bool AllowRebuild,
1014 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001015 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1016 PreprocessorOptions &PreprocessorOpts
1017 = PreambleInvocation.getPreprocessorOpts();
1018
1019 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001020 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001021 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001022
Douglas Gregor3edb1672010-11-16 20:45:51 +00001023 // If ComputePreamble() Take ownership of the
1024 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1025 if (CreatedPreambleBuffer)
1026 OwnedPreambleBuffer.reset(NewPreamble.first);
1027
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001028 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001029 // We couldn't find a preamble in the main source. Clear out the current
1030 // preamble, if we have one. It's obviously no good any more.
1031 Preamble.clear();
1032 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001033 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001034 PreambleFile.clear();
1035 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001036
1037 // The next time we actually see a preamble, precompile it.
1038 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001039 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001040 }
1041
1042 if (!Preamble.empty()) {
1043 // We've previously computed a preamble. Check whether we have the same
1044 // preamble now that we did before, and that there's enough space in
1045 // the main-file buffer within the precompiled preamble to fit the
1046 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001047 if (Preamble.size() == NewPreamble.second.first &&
1048 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001049 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001050 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001051 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001052 // The preamble has not changed. We may be able to re-use the precompiled
1053 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001054
Douglas Gregor0e119552010-07-31 00:40:00 +00001055 // Check that none of the files used by the preamble have changed.
1056 bool AnyFileChanged = false;
1057
1058 // First, make a record of those files that have been overridden via
1059 // remapping or unsaved_files.
1060 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1061 for (PreprocessorOptions::remapped_file_iterator
1062 R = PreprocessorOpts.remapped_file_begin(),
1063 REnd = PreprocessorOpts.remapped_file_end();
1064 !AnyFileChanged && R != REnd;
1065 ++R) {
1066 struct stat StatBuf;
1067 if (stat(R->second.c_str(), &StatBuf)) {
1068 // If we can't stat the file we're remapping to, assume that something
1069 // horrible happened.
1070 AnyFileChanged = true;
1071 break;
1072 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001073
Douglas Gregor0e119552010-07-31 00:40:00 +00001074 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1075 StatBuf.st_mtime);
1076 }
1077 for (PreprocessorOptions::remapped_file_buffer_iterator
1078 R = PreprocessorOpts.remapped_file_buffer_begin(),
1079 REnd = PreprocessorOpts.remapped_file_buffer_end();
1080 !AnyFileChanged && R != REnd;
1081 ++R) {
1082 // FIXME: Should we actually compare the contents of file->buffer
1083 // remappings?
1084 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1085 0);
1086 }
1087
1088 // Check whether anything has changed.
1089 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1090 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1091 !AnyFileChanged && F != FEnd;
1092 ++F) {
1093 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1094 = OverriddenFiles.find(F->first());
1095 if (Overridden != OverriddenFiles.end()) {
1096 // This file was remapped; check whether the newly-mapped file
1097 // matches up with the previous mapping.
1098 if (Overridden->second != F->second)
1099 AnyFileChanged = true;
1100 continue;
1101 }
1102
1103 // The file was not remapped; check whether it has changed on disk.
1104 struct stat StatBuf;
1105 if (stat(F->first(), &StatBuf)) {
1106 // If we can't stat the file, assume that something horrible happened.
1107 AnyFileChanged = true;
1108 } else if (StatBuf.st_size != F->second.first ||
1109 StatBuf.st_mtime != F->second.second)
1110 AnyFileChanged = true;
1111 }
1112
1113 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001114 // Okay! We can re-use the precompiled preamble.
1115
1116 // Set the state of the diagnostic object to mimic its state
1117 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001118 // FIXME: This won't catch any #pragma push warning changes that
1119 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001120 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001121 ProcessWarningOptions(getDiagnostics(),
1122 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001123 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1124 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1125 StoredDiagnostics.erase(
1126 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1127 StoredDiagnostics.end());
1128
1129 // Create a version of the main file buffer that is padded to
1130 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001131 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001132 PreambleReservedSize,
1133 FrontendOpts.Inputs[0].second);
1134 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001135 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001136
1137 // If we aren't allowed to rebuild the precompiled preamble, just
1138 // return now.
1139 if (!AllowRebuild)
1140 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001141
Douglas Gregor4dde7492010-07-23 23:58:40 +00001142 // We can't reuse the previously-computed preamble. Build a new one.
1143 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001144 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001145 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001146 } else if (!AllowRebuild) {
1147 // We aren't allowed to rebuild the precompiled preamble; just
1148 // return now.
1149 return 0;
1150 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001151
1152 // If the preamble rebuild counter > 1, it's because we previously
1153 // failed to build a preamble and we're not yet ready to try
1154 // again. Decrement the counter and return a failure.
1155 if (PreambleRebuildCounter > 1) {
1156 --PreambleRebuildCounter;
1157 return 0;
1158 }
1159
Douglas Gregore10f0e52010-09-11 17:56:52 +00001160 // Create a temporary file for the precompiled preamble. In rare
1161 // circumstances, this can fail.
1162 std::string PreamblePCHPath = GetPreamblePCHPath();
1163 if (PreamblePCHPath.empty()) {
1164 // Try again next time.
1165 PreambleRebuildCounter = 1;
1166 return 0;
1167 }
1168
Douglas Gregor4dde7492010-07-23 23:58:40 +00001169 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001170 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001171 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001172
1173 // Create a new buffer that stores the preamble. The buffer also contains
1174 // extra space for the original contents of the file (which will be present
1175 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001176 // grows.
1177 PreambleReservedSize = NewPreamble.first->getBufferSize();
1178 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001179 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001180 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001181 PreambleReservedSize *= 2;
1182
Douglas Gregord9a30af2010-08-02 20:51:39 +00001183 // Save the preamble text for later; we'll need to compare against it for
1184 // subsequent reparses.
1185 Preamble.assign(NewPreamble.first->getBufferStart(),
1186 NewPreamble.first->getBufferStart()
1187 + NewPreamble.second.first);
1188 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1189
Douglas Gregora0734c52010-08-19 01:33:06 +00001190 delete PreambleBuffer;
1191 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001192 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001193 FrontendOpts.Inputs[0].second);
1194 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001195 NewPreamble.first->getBufferStart(), Preamble.size());
1196 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001197 ' ', PreambleReservedSize - Preamble.size() - 1);
1198 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001199
1200 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001201 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001202 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1203
1204 // Tell the compiler invocation to generate a temporary precompiled header.
1205 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001206 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001208 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001209 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1210 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001211
1212 // Create the compiler instance to use for building the precompiled preamble.
1213 CompilerInstance Clang;
1214 Clang.setInvocation(&PreambleInvocation);
1215 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1216
Douglas Gregor8e984da2010-08-04 16:47:14 +00001217 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001218 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219
1220 // Create the target instance.
1221 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1222 Clang.getTargetOpts()));
1223 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001224 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1225 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001226 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001227 PreprocessorOpts.eraseRemappedFile(
1228 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001229 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001230 }
1231
1232 // Inform the target of the language options.
1233 //
1234 // FIXME: We shouldn't need to do this, the target should be immutable once
1235 // created. This complexity should be lifted elsewhere.
1236 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1237
1238 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1239 "Invocation must have exactly one source file!");
1240 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1241 "FIXME: AST inputs not yet supported here!");
1242 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1243 "IR inputs not support here!");
1244
1245 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001246 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001247 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001248 StoredDiagnostics.erase(
1249 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1250 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001251 TopLevelDecls.clear();
1252 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001253 PreprocessedEntities.clear();
1254 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001255
1256 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner3f5a9ef2010-11-23 07:51:02 +00001257 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001258
1259 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001260 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +00001261 Clang.getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001262
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001263 llvm::OwningPtr<PrecompilePreambleAction> Act;
1264 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001265 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1266 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001267 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001268 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1269 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001270 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001271 PreprocessorOpts.eraseRemappedFile(
1272 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001273 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001274 }
1275
1276 Act->Execute();
1277 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001278 Clang.takeInvocation();
1279
Douglas Gregore9db88f2010-08-03 19:06:41 +00001280 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001281 // There were errors parsing the preamble, so no precompiled header was
1282 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001283 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001284 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1285 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001286 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001287 PreprocessedEntities.clear();
1288 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001289 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001290 PreprocessorOpts.eraseRemappedFile(
1291 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001292 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001293 }
1294
1295 // Keep track of the preamble we precompiled.
1296 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001297 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1298 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001299
1300 // Keep track of all of the files that the source manager knows about,
1301 // so we can verify whether they have changed or not.
1302 FilesInPreamble.clear();
1303 SourceManager &SourceMgr = Clang.getSourceManager();
1304 const llvm::MemoryBuffer *MainFileBuffer
1305 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1306 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1307 FEnd = SourceMgr.fileinfo_end();
1308 F != FEnd;
1309 ++F) {
1310 const FileEntry *File = F->second->Entry;
1311 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1312 continue;
1313
1314 FilesInPreamble[File->getName()]
1315 = std::make_pair(F->second->getSize(), File->getModificationTime());
1316 }
1317
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001318 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001319 PreprocessorOpts.eraseRemappedFile(
1320 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001321 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001322 PreambleReservedSize,
1323 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001324}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001325
Douglas Gregore9db88f2010-08-03 19:06:41 +00001326void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1327 std::vector<Decl *> Resolved;
1328 Resolved.reserve(TopLevelDeclsInPreamble.size());
1329 ExternalASTSource &Source = *getASTContext().getExternalSource();
1330 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1331 // Resolve the declaration ID to an actual declaration, possibly
1332 // deserializing the declaration in the process.
1333 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1334 if (D)
1335 Resolved.push_back(D);
1336 }
1337 TopLevelDeclsInPreamble.clear();
1338 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1339}
1340
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001341void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1342 if (!PP)
1343 return;
1344
1345 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1346 if (!PPRec)
1347 return;
1348
1349 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1350 if (!External)
1351 return;
1352
1353 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1354 if (PreprocessedEntity *PE
1355 = External->ReadPreprocessedEntity(PreprocessedEntitiesInPreamble[I]))
1356 PreprocessedEntities.push_back(PE);
1357 }
1358
1359 if (PreprocessedEntities.empty())
1360 return;
1361
1362 PreprocessedEntities.insert(PreprocessedEntities.end(),
1363 PPRec->begin(true), PPRec->end(true));
1364}
1365
1366ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1367 if (!PreprocessedEntitiesInPreamble.empty() &&
1368 PreprocessedEntities.empty())
1369 RealizePreprocessedEntitiesFromPreamble();
1370
1371 if (PreprocessedEntities.empty())
1372 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1373 return PPRec->begin(true);
1374
1375 return PreprocessedEntities.begin();
1376}
1377
1378ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1379 if (!PreprocessedEntitiesInPreamble.empty() &&
1380 PreprocessedEntities.empty())
1381 RealizePreprocessedEntitiesFromPreamble();
1382
1383 if (PreprocessedEntities.empty())
1384 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1385 return PPRec->end(true);
1386
1387 return PreprocessedEntities.end();
1388}
1389
Douglas Gregore9db88f2010-08-03 19:06:41 +00001390unsigned ASTUnit::getMaxPCHLevel() const {
1391 if (!getOnlyLocalDecls())
1392 return Decl::MaxPCHLevel;
1393
Sebastian Redl009e7f22010-10-05 16:15:19 +00001394 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001395}
1396
Douglas Gregor16896c42010-10-28 15:44:59 +00001397llvm::StringRef ASTUnit::getMainFileName() const {
1398 return Invocation->getFrontendOpts().Inputs[0].second;
1399}
1400
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001401bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1402 if (!Invocation)
1403 return true;
1404
1405 // We'll manage file buffers ourselves.
1406 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1407 Invocation->getFrontendOpts().DisableFree = false;
1408
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001409 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001410 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001411 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001412 OverrideMainBuffer
1413 = getMainBufferWithPrecompiledPreamble(*Invocation);
1414 }
1415
Douglas Gregor16896c42010-10-28 15:44:59 +00001416 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001417 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001418
Douglas Gregor16896c42010-10-28 15:44:59 +00001419 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001420}
1421
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001422ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1423 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1424 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001425 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001426 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001427 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001428 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001429 // Create the AST unit.
1430 llvm::OwningPtr<ASTUnit> AST;
1431 AST.reset(new ASTUnit(false));
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001432 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001433 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001434 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001435 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001436 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001437 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001438 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001439 AST->Invocation.reset(CI);
1440
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001441 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001442}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001443
1444ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1445 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001446 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001447 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001448 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001449 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001450 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001451 unsigned NumRemappedFiles,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001452 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001453 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001454 bool CacheCodeCompletionResults,
1455 bool CXXPrecompilePreamble,
1456 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001457 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001458 // No diagnostics engine was provided, so create our own diagnostics object
1459 // with the default options.
1460 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001461 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +00001462 }
1463
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001464 llvm::SmallVector<const char *, 16> Args;
1465 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1466 Args.insert(Args.end(), ArgBegin, ArgEnd);
1467
1468 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1469 // also want to force it to use clang.
1470 Args.push_back("-fsyntax-only");
1471
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001472 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1473
1474 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001475
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001476 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001477 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001478 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001479
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001480 // FIXME: We shouldn't have to pass in the path info.
1481 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1482 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001483
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001484 // Don't check that inputs exist, they have been remapped.
1485 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001486
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001487 llvm::OwningPtr<driver::Compilation> C(
1488 TheDriver.BuildCompilation(Args.size(), Args.data()));
1489
1490 // We expect to get back exactly one command job, if we didn't something
1491 // failed.
1492 const driver::JobList &Jobs = C->getJobs();
1493 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1494 llvm::SmallString<256> Msg;
1495 llvm::raw_svector_ostream OS(Msg);
1496 C->PrintJob(OS, C->getJobs(), "; ", true);
1497 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1498 return 0;
1499 }
1500
1501 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1502 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1503 Diags->Report(diag::err_fe_expected_clang_command);
1504 return 0;
1505 }
1506
1507 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1508 CI.reset(new CompilerInvocation);
1509 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001510 const_cast<const char **>(CCArgs.data()),
1511 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001512 CCArgs.size(),
1513 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001514 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001515
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001516 // Override any files that need remapping
1517 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001518 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001519 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001520
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001521 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001522 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001523
Douglas Gregorf5a18542010-10-27 17:24:53 +00001524 // Check whether we should precompile the preamble and/or use chained PCH.
1525 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1526 if (CI->getLangOpts().CPlusPlus) {
1527 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1528
1529 if (PrecompilePreamble && !CXXChainedPCH &&
1530 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1531 PrecompilePreamble = false;
1532 }
1533
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001534 // Create the AST unit.
1535 llvm::OwningPtr<ASTUnit> AST;
1536 AST.reset(new ASTUnit(false));
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001537 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001538 AST->Diagnostics = Diags;
Chris Lattner5159f612010-11-23 08:35:12 +00001539
1540 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001541 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001542 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001543 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1544 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001545 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001546 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1547 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1548 AST->StoredDiagnostics.swap(StoredDiagnostics);
1549 AST->Invocation.reset(CI.take());
Chris Lattner5159f612010-11-23 08:35:12 +00001550 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001551}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001552
1553bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1554 if (!Invocation.get())
1555 return true;
1556
Douglas Gregor16896c42010-10-28 15:44:59 +00001557 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001558 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001559
Douglas Gregor0e119552010-07-31 00:40:00 +00001560 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001561 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1562 for (PreprocessorOptions::remapped_file_buffer_iterator
1563 R = PPOpts.remapped_file_buffer_begin(),
1564 REnd = PPOpts.remapped_file_buffer_end();
1565 R != REnd;
1566 ++R) {
1567 delete R->second;
1568 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001569 Invocation->getPreprocessorOpts().clearRemappedFiles();
1570 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1571 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1572 RemappedFiles[I].second);
1573
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001574 // If we have a preamble file lying around, or if we might try to
1575 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001576 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001577 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001578 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001579
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001580 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001581 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001582 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001583 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1584 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001585
Douglas Gregor4dde7492010-07-23 23:58:40 +00001586 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001587 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001588
1589 if (ShouldCacheCodeCompletionResults) {
1590 if (CacheCodeCompletionCoolDown > 0)
1591 --CacheCodeCompletionCoolDown;
1592 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1593 CacheCodeCompletionResults();
1594 }
1595
Douglas Gregor4dde7492010-07-23 23:58:40 +00001596 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001597}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001598
Douglas Gregorb14904c2010-08-13 22:48:40 +00001599//----------------------------------------------------------------------------//
1600// Code completion
1601//----------------------------------------------------------------------------//
1602
1603namespace {
1604 /// \brief Code completion consumer that combines the cached code-completion
1605 /// results from an ASTUnit with the code-completion results provided to it,
1606 /// then passes the result on to
1607 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1608 unsigned NormalContexts;
1609 ASTUnit &AST;
1610 CodeCompleteConsumer &Next;
1611
1612 public:
1613 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001614 bool IncludeMacros, bool IncludeCodePatterns,
1615 bool IncludeGlobals)
1616 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001617 Next.isOutputBinary()), AST(AST), Next(Next)
1618 {
1619 // Compute the set of contexts in which we will look when we don't have
1620 // any information about the specific context.
1621 NormalContexts
1622 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1623 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1624 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1625 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1626 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1627 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1628 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1629 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001630 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001631 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1632 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001633
Douglas Gregorb14904c2010-08-13 22:48:40 +00001634 if (AST.getASTContext().getLangOptions().CPlusPlus)
1635 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1636 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1637 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1638 }
1639
1640 virtual void ProcessCodeCompleteResults(Sema &S,
1641 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001642 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001643 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001644
1645 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1646 OverloadCandidate *Candidates,
1647 unsigned NumCandidates) {
1648 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1649 }
1650 };
1651}
Douglas Gregord46cf182010-08-16 20:01:48 +00001652
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001653/// \brief Helper function that computes which global names are hidden by the
1654/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001655static void CalculateHiddenNames(const CodeCompletionContext &Context,
1656 CodeCompletionResult *Results,
1657 unsigned NumResults,
1658 ASTContext &Ctx,
1659 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001660 bool OnlyTagNames = false;
1661 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001662 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001663 case CodeCompletionContext::CCC_TopLevel:
1664 case CodeCompletionContext::CCC_ObjCInterface:
1665 case CodeCompletionContext::CCC_ObjCImplementation:
1666 case CodeCompletionContext::CCC_ObjCIvarList:
1667 case CodeCompletionContext::CCC_ClassStructUnion:
1668 case CodeCompletionContext::CCC_Statement:
1669 case CodeCompletionContext::CCC_Expression:
1670 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1671 case CodeCompletionContext::CCC_MemberAccess:
1672 case CodeCompletionContext::CCC_Namespace:
1673 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001674 case CodeCompletionContext::CCC_Name:
1675 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001676 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001677 break;
1678
1679 case CodeCompletionContext::CCC_EnumTag:
1680 case CodeCompletionContext::CCC_UnionTag:
1681 case CodeCompletionContext::CCC_ClassOrStructTag:
1682 OnlyTagNames = true;
1683 break;
1684
1685 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001686 case CodeCompletionContext::CCC_MacroName:
1687 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001688 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001689 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001690 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001691 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001692 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001693 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001694 // We're looking for nothing, or we're looking for names that cannot
1695 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001696 return;
1697 }
1698
John McCall276321a2010-08-25 06:19:51 +00001699 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001700 for (unsigned I = 0; I != NumResults; ++I) {
1701 if (Results[I].Kind != Result::RK_Declaration)
1702 continue;
1703
1704 unsigned IDNS
1705 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1706
1707 bool Hiding = false;
1708 if (OnlyTagNames)
1709 Hiding = (IDNS & Decl::IDNS_Tag);
1710 else {
1711 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001712 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1713 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001714 if (Ctx.getLangOptions().CPlusPlus)
1715 HiddenIDNS |= Decl::IDNS_Tag;
1716 Hiding = (IDNS & HiddenIDNS);
1717 }
1718
1719 if (!Hiding)
1720 continue;
1721
1722 DeclarationName Name = Results[I].Declaration->getDeclName();
1723 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1724 HiddenNames.insert(Identifier->getName());
1725 else
1726 HiddenNames.insert(Name.getAsString());
1727 }
1728}
1729
1730
Douglas Gregord46cf182010-08-16 20:01:48 +00001731void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1732 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001733 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001734 unsigned NumResults) {
1735 // Merge the results we were given with the results we cached.
1736 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001737 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001738 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001739 : (1 << (Context.getKind() - 1)));
1740
1741 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001742 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001743 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001744 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001745 llvm::SmallVector<Result, 8> AllResults;
1746 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001747 C = AST.cached_completion_begin(),
1748 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001749 C != CEnd; ++C) {
1750 // If the context we are in matches any of the contexts we are
1751 // interested in, we'll add this result.
1752 if ((C->ShowInContexts & InContexts) == 0)
1753 continue;
1754
1755 // If we haven't added any results previously, do so now.
1756 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001757 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1758 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001759 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1760 AddedResult = true;
1761 }
1762
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001763 // Determine whether this global completion result is hidden by a local
1764 // completion result. If so, skip it.
1765 if (C->Kind != CXCursor_MacroDefinition &&
1766 HiddenNames.count(C->Completion->getTypedText()))
1767 continue;
1768
Douglas Gregord46cf182010-08-16 20:01:48 +00001769 // Adjust priority based on similar type classes.
1770 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001771 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001772 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001773 if (!Context.getPreferredType().isNull()) {
1774 if (C->Kind == CXCursor_MacroDefinition) {
1775 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001776 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001777 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001778 } else if (C->Type) {
1779 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001780 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001781 Context.getPreferredType().getUnqualifiedType());
1782 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1783 if (ExpectedSTC == C->TypeClass) {
1784 // We know this type is similar; check for an exact match.
1785 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001786 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001787 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001788 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001789 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1790 Priority /= CCF_ExactTypeMatch;
1791 else
1792 Priority /= CCF_SimilarTypeMatch;
1793 }
1794 }
1795 }
1796
Douglas Gregor12785102010-08-24 20:21:13 +00001797 // Adjust the completion string, if required.
1798 if (C->Kind == CXCursor_MacroDefinition &&
1799 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1800 // Create a new code-completion string that just contains the
1801 // macro name, without its arguments.
1802 Completion = new CodeCompletionString;
1803 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1804 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001805 CursorKind = CXCursor_NotImplemented;
1806 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001807 }
1808
Douglas Gregor8850aa32010-08-25 18:03:13 +00001809 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001810 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001811 }
1812
1813 // If we did not add any cached completion results, just forward the
1814 // results we were given to the next consumer.
1815 if (!AddedResult) {
1816 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1817 return;
1818 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001819
Douglas Gregord46cf182010-08-16 20:01:48 +00001820 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1821 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001822
1823 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1824 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001825}
1826
1827
1828
Douglas Gregor8e984da2010-08-04 16:47:14 +00001829void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1830 RemappedFile *RemappedFiles,
1831 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001832 bool IncludeMacros,
1833 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001834 CodeCompleteConsumer &Consumer,
1835 Diagnostic &Diag, LangOptions &LangOpts,
1836 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001837 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1838 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001839 if (!Invocation.get())
1840 return;
1841
Douglas Gregor16896c42010-10-28 15:44:59 +00001842 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001843 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1844 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00001845
Douglas Gregor8e984da2010-08-04 16:47:14 +00001846 CompilerInvocation CCInvocation(*Invocation);
1847 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1848 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001849
Douglas Gregorb14904c2010-08-13 22:48:40 +00001850 FrontendOpts.ShowMacrosInCodeCompletion
1851 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001852 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001853 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1854 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001855 FrontendOpts.CodeCompletionAt.FileName = File;
1856 FrontendOpts.CodeCompletionAt.Line = Line;
1857 FrontendOpts.CodeCompletionAt.Column = Column;
1858
1859 // Set the language options appropriately.
1860 LangOpts = CCInvocation.getLangOpts();
1861
1862 CompilerInstance Clang;
1863 Clang.setInvocation(&CCInvocation);
1864 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1865
1866 // Set up diagnostics, capturing any diagnostics produced.
1867 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001868 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001869 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001870 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00001871 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001872
1873 // Create the target instance.
1874 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1875 Clang.getTargetOpts()));
1876 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001877 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001878 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001879 }
1880
1881 // Inform the target of the language options.
1882 //
1883 // FIXME: We shouldn't need to do this, the target should be immutable once
1884 // created. This complexity should be lifted elsewhere.
1885 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1886
1887 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1888 "Invocation must have exactly one source file!");
1889 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1890 "FIXME: AST inputs not yet supported here!");
1891 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1892 "IR inputs not support here!");
1893
1894
1895 // Use the source and file managers that we were given.
1896 Clang.setFileManager(&FileMgr);
1897 Clang.setSourceManager(&SourceMgr);
1898
1899 // Remap files.
1900 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001901 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001902 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001903 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1904 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001905 OwnedBuffers.push_back(RemappedFiles[I].second);
1906 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001907
Douglas Gregorb14904c2010-08-13 22:48:40 +00001908 // Use the code completion consumer we were given, but adding any cached
1909 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00001910 AugmentedCodeCompleteConsumer *AugmentedConsumer
1911 = new AugmentedCodeCompleteConsumer(*this, Consumer,
1912 FrontendOpts.ShowMacrosInCodeCompletion,
1913 FrontendOpts.ShowCodePatternsInCodeCompletion,
1914 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
1915 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001916
Douglas Gregor028d3e42010-08-09 20:45:32 +00001917 // If we have a precompiled preamble, try to use it. We only allow
1918 // the use of the precompiled preamble if we're if the completion
1919 // point is within the main file, after the end of the precompiled
1920 // preamble.
1921 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1922 if (!PreambleFile.empty()) {
1923 using llvm::sys::FileStatus;
1924 llvm::sys::PathWithStatus CompleteFilePath(File);
1925 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1926 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1927 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1928 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001929 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001930 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1931 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001932 }
1933
1934 // If the main file has been overridden due to the use of a preamble,
1935 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001936 StoredDiagnostics.insert(StoredDiagnostics.end(),
1937 this->StoredDiagnostics.begin(),
1938 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001939 if (OverrideMainBuffer) {
1940 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1941 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1942 PreprocessorOpts.PrecompiledPreambleBytes.second
1943 = PreambleEndsAtStartOfLine;
1944 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1945 PreprocessorOpts.DisablePCHValidation = true;
1946
1947 // The stored diagnostics have the old source manager. Copy them
1948 // to our output set of stored diagnostics, updating the source
1949 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001950 for (unsigned I = NumStoredDiagnosticsFromDriver,
1951 N = this->StoredDiagnostics.size();
1952 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001953 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1954 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1955 StoredDiagnostics[I].setLocation(Loc);
1956 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001957
Douglas Gregorb97b6662010-08-20 00:59:43 +00001958 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001959 } else {
1960 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1961 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001962 }
1963
Douglas Gregor8e984da2010-08-04 16:47:14 +00001964 llvm::OwningPtr<SyntaxOnlyAction> Act;
1965 Act.reset(new SyntaxOnlyAction);
1966 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1967 Clang.getFrontendOpts().Inputs[0].first)) {
1968 Act->Execute();
1969 Act->EndSourceFile();
1970 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001971
Douglas Gregor8e984da2010-08-04 16:47:14 +00001972 // Steal back our resources.
1973 Clang.takeFileManager();
1974 Clang.takeSourceManager();
1975 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001976}
Douglas Gregore9386682010-08-13 05:36:37 +00001977
1978bool ASTUnit::Save(llvm::StringRef File) {
1979 if (getDiagnostics().hasErrorOccurred())
1980 return true;
1981
1982 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1983 // unconditionally create a stat cache when we parse the file?
1984 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001985 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1986 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001987 if (!ErrorInfo.empty() || Out.has_error())
1988 return true;
1989
1990 std::vector<unsigned char> Buffer;
1991 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001992 ASTWriter Writer(Stream);
1993 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001994
1995 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001996 if (!Buffer.empty())
1997 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001998 Out.close();
1999 return Out.has_error();
2000}