blob: cbcb08b6fe3a58941bb1ec657e2ab82b51756d40 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000030#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000033#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Basic/TargetInfo.h"
35#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000038#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000039#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000042#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000043#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000044#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000045using namespace clang;
46
Douglas Gregor213f18b2010-10-28 15:44:59 +000047using llvm::TimeRecord;
48
49namespace {
50 class SimpleTimer {
51 bool WantTiming;
52 TimeRecord Start;
53 std::string Output;
54
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000055 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000056 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000057 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000058 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000059 }
60
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000061 void setOutput(const llvm::Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 ~SimpleTimer() {
67 if (WantTiming) {
68 TimeRecord Elapsed = TimeRecord::getCurrentTime();
69 Elapsed -= Start;
70 llvm::errs() << Output << ':';
71 Elapsed.print(Elapsed, llvm::errs());
72 llvm::errs() << '\n';
73 }
74 }
75 };
76}
77
Douglas Gregoreababfb2010-08-04 05:53:38 +000078/// \brief After failing to build a precompiled preamble (due to
79/// errors in the source that occurs in the preamble), the number of
80/// reparses during which we'll skip even trying to precompile the
81/// preamble.
82const unsigned DefaultPreambleRebuildInterval = 5;
83
Douglas Gregore3c60a72010-11-17 00:13:31 +000084/// \brief Tracks the number of ASTUnit objects that are currently active.
85///
86/// Used for debugging purposes only.
87static unsigned ActiveASTUnitObjects;
88
Douglas Gregor3687e9d2010-04-05 21:10:19 +000089ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000090 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor213f18b2010-10-28 15:44:59 +000091 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
92 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +000093 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000094 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000095 ShouldCacheCodeCompletionResults(false),
96 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000097 CacheCodeCompletionCoolDown(0),
98 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +000099 if (getenv("LIBCLANG_OBJTRACKING")) {
100 ++ActiveASTUnitObjects;
101 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
102 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000103}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000104
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000105ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000106 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000107 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000108 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000109 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000110
111 // Free the buffers associated with remapped files. We are required to
112 // perform this operation here because we explicitly request that the
113 // compiler instance *not* free these buffers for each invocation of the
114 // parser.
115 if (Invocation.get()) {
116 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
117 for (PreprocessorOptions::remapped_file_buffer_iterator
118 FB = PPOpts.remapped_file_buffer_begin(),
119 FBEnd = PPOpts.remapped_file_buffer_end();
120 FB != FBEnd;
121 ++FB)
122 delete FB->second;
123 }
Douglas Gregor28233422010-07-27 14:52:07 +0000124
125 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000126 delete PreambleBuffer;
127
Douglas Gregor213f18b2010-10-28 15:44:59 +0000128 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000129
130 if (getenv("LIBCLANG_OBJTRACKING")) {
131 --ActiveASTUnitObjects;
132 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
133 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000134}
135
136void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000137 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
138 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000139 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000140}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000141
Douglas Gregor8071e422010-08-15 06:18:01 +0000142/// \brief Determine the set of code-completion contexts in which this
143/// declaration should be shown.
144static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000145 const LangOptions &LangOpts,
146 bool &IsNestedNameSpecifier) {
147 IsNestedNameSpecifier = false;
148
Douglas Gregor8071e422010-08-15 06:18:01 +0000149 if (isa<UsingShadowDecl>(ND))
150 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
151 if (!ND)
152 return 0;
153
154 unsigned Contexts = 0;
155 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
156 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
157 // Types can appear in these contexts.
158 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
159 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
160 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
161 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
162 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000163 | (1 << (CodeCompletionContext::CCC_Type - 1))
164 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000165
166 // In C++, types can appear in expressions contexts (for functional casts).
167 if (LangOpts.CPlusPlus)
168 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
169
170 // In Objective-C, message sends can send interfaces. In Objective-C++,
171 // all types are available due to functional casts.
172 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
173 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
174
175 // Deal with tag names.
176 if (isa<EnumDecl>(ND)) {
177 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
178
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000179 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000180 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000181 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000182 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
183 if (Record->isUnion())
184 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
185 else
186 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
187
Douglas Gregor8071e422010-08-15 06:18:01 +0000188 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000189 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000190 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000192 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
193 // Values can appear in these contexts.
194 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
195 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000196 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000197 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
198 } else if (isa<ObjCProtocolDecl>(ND)) {
199 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
200 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000201 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000202
203 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000204 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000205 }
206
207 return Contexts;
208}
209
Douglas Gregor87c08a52010-08-13 22:48:40 +0000210void ASTUnit::CacheCodeCompletionResults() {
211 if (!TheSema)
212 return;
213
Douglas Gregor213f18b2010-10-28 15:44:59 +0000214 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000215 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000216
217 // Clear out the previous results.
218 ClearCachedCompletionResults();
219
220 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000221 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000222 llvm::SmallVector<Result, 8> Results;
223 TheSema->GatherGlobalCodeCompletions(Results);
224
225 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000226 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
227
Douglas Gregor87c08a52010-08-13 22:48:40 +0000228 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
229 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000230 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000231 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000232 CachedCodeCompletionResult CachedResult;
233 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
234 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000235 Ctx->getLangOptions(),
236 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000237 CachedResult.Priority = Results[I].Priority;
238 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000239 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000240
Douglas Gregorf5586f62010-08-16 18:08:11 +0000241 // Keep track of the type of this completion in an ASTContext-agnostic
242 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000243 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000244 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000245 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000246 CachedResult.Type = 0;
247 } else {
248 CanQualType CanUsageType
249 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
250 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
251
252 // Determine whether we have already seen this type. If so, we save
253 // ourselves the work of formatting the type string by using the
254 // temporary, CanQualType-based hash table to find the associated value.
255 unsigned &TypeValue = CompletionTypes[CanUsageType];
256 if (TypeValue == 0) {
257 TypeValue = CompletionTypes.size();
258 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
259 = TypeValue;
260 }
261
262 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000263 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000264
Douglas Gregor8071e422010-08-15 06:18:01 +0000265 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000266
267 /// Handle nested-name-specifiers in C++.
268 if (TheSema->Context.getLangOptions().CPlusPlus &&
269 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
270 // The contexts in which a nested-name-specifier can appear in C++.
271 unsigned NNSContexts
272 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
274 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
275 | (1 << (CodeCompletionContext::CCC_Statement - 1))
276 | (1 << (CodeCompletionContext::CCC_Expression - 1))
277 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
278 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
279 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
280 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000281 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000282 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
283 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000284
285 if (isa<NamespaceDecl>(Results[I].Declaration) ||
286 isa<NamespaceAliasDecl>(Results[I].Declaration))
287 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
288
289 if (unsigned RemainingContexts
290 = NNSContexts & ~CachedResult.ShowInContexts) {
291 // If there any contexts where this completion can be a
292 // nested-name-specifier but isn't already an option, create a
293 // nested-name-specifier completion.
294 Results[I].StartsNestedNameSpecifier = true;
295 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
296 CachedResult.ShowInContexts = RemainingContexts;
297 CachedResult.Priority = CCP_NestedNameSpecifier;
298 CachedResult.TypeClass = STC_Void;
299 CachedResult.Type = 0;
300 CachedCompletionResults.push_back(CachedResult);
301 }
302 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000303 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000304 }
305
Douglas Gregor87c08a52010-08-13 22:48:40 +0000306 case Result::RK_Keyword:
307 case Result::RK_Pattern:
308 // Ignore keywords and patterns; we don't care, since they are so
309 // easily regenerated.
310 break;
311
312 case Result::RK_Macro: {
313 CachedCodeCompletionResult CachedResult;
314 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
315 CachedResult.ShowInContexts
316 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
317 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
318 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
319 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
320 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
321 | (1 << (CodeCompletionContext::CCC_Statement - 1))
322 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000323 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000324 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000325 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
326 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
327
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000328
Douglas Gregor87c08a52010-08-13 22:48:40 +0000329 CachedResult.Priority = Results[I].Priority;
330 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000331 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000332 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000333 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000334 CachedCompletionResults.push_back(CachedResult);
335 break;
336 }
337 }
338 Results[I].Destroy();
339 }
340
Douglas Gregor727d93e2010-08-17 00:40:40 +0000341 // Make a note of the state when we performed this caching.
342 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000343}
344
345void ASTUnit::ClearCachedCompletionResults() {
346 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
347 delete CachedCompletionResults[I].Completion;
348 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000349 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350}
351
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000352namespace {
353
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000354/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000355/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000356class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000357 LangOptions &LangOpt;
358 HeaderSearch &HSI;
359 std::string &TargetTriple;
360 std::string &Predefines;
361 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000363 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000365public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000366 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000367 std::string &TargetTriple, std::string &Predefines,
368 unsigned &Counter)
369 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
370 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000372 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
373 LangOpt = LangOpts;
374 return false;
375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000377 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000378 TargetTriple = Triple;
379 return false;
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000382 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000383 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000384 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000385 Predefines = Buffers[0].Data;
386 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
387 Predefines += Buffers[I].Data;
388 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000389 return false;
390 }
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000392 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000393 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000396 virtual void ReadCounter(unsigned Value) {
397 Counter = Value;
398 }
399};
400
Douglas Gregora88084b2010-02-18 18:08:43 +0000401class StoredDiagnosticClient : public DiagnosticClient {
402 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
403
404public:
405 explicit StoredDiagnosticClient(
406 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
407 : StoredDiags(StoredDiags) { }
408
409 virtual void HandleDiagnostic(Diagnostic::Level Level,
410 const DiagnosticInfo &Info);
411};
412
413/// \brief RAII object that optionally captures diagnostics, if
414/// there is no diagnostic client to capture them already.
415class CaptureDroppedDiagnostics {
416 Diagnostic &Diags;
417 StoredDiagnosticClient Client;
418 DiagnosticClient *PreviousClient;
419
420public:
421 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000422 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000423 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000424 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000425 if (RequestCapture || Diags.getClient() == 0) {
426 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000427 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000428 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000429 }
430
431 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000432 if (Diags.getClient() == &Client) {
433 Diags.takeClient();
434 Diags.setClient(PreviousClient);
435 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000436 }
437};
438
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000439} // anonymous namespace
440
Douglas Gregora88084b2010-02-18 18:08:43 +0000441void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
442 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000443 // Default implementation (Warnings/errors count).
444 DiagnosticClient::HandleDiagnostic(Level, Info);
445
Douglas Gregora88084b2010-02-18 18:08:43 +0000446 StoredDiags.push_back(StoredDiagnostic(Level, Info));
447}
448
Steve Naroff77accc12009-09-03 18:19:54 +0000449const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000450 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000451}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000452
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000453const std::string &ASTUnit::getASTFileName() {
454 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000455 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000456}
457
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000458llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
459 std::string *ErrorStr,
Chris Lattner151466a2010-11-23 06:09:11 +0000460 int64_t FileSize) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000461 return FileMgr->getBufferForFile(Filename, FileSystemOpts,
Chris Lattner151466a2010-11-23 06:09:11 +0000462 ErrorStr, FileSize);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000463}
464
Douglas Gregore47be3e2010-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 Redl3c7f4132010-08-18 23:57:06 +0000481ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000482 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000483 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000484 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000485 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000486 unsigned NumRemappedFiles,
487 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000488 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000489 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000490
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000491 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000492 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000493 AST->Diagnostics = Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000494 AST->FileSystemOpts = FileSystemOpts;
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000495 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000496 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
497 AST->getFileManager(),
498 AST->getFileSystemOpts()));
499 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
500 AST->getFileSystemOpts()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000501
Douglas Gregor4db64a42010-01-23 00:14:00 +0000502 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
503 // Create the file entry for the file that we're mapping from.
504 const FileEntry *FromFile
505 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
506 RemappedFiles[I].second->getBufferSize(),
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000507 0,
508 AST->getFileSystemOpts());
Douglas Gregor4db64a42010-01-23 00:14:00 +0000509 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000510 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000511 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000512 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000513 continue;
514 }
515
516 // Override the contents of the "from" file with the contents of
517 // the "to" file.
518 AST->getSourceManager().overrideFileContents(FromFile,
519 RemappedFiles[I].second);
520 }
521
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000522 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000524 LangOptions LangInfo;
525 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
526 std::string TargetTriple;
527 std::string Predefines;
528 unsigned Counter;
529
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000530 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000531
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000532 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000533 AST->getFileSystemOpts(), AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000534 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000535 Predefines, Counter));
536
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000537 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000538 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000539 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000541 case ASTReader::Failure:
542 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000543 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000544 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000545 }
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000547 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
548
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000549 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000551 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000552 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000553 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000554 TargetOptions TargetOpts;
555 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000556 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000557 TargetOpts.CPU = "";
558 TargetOpts.Features.clear();
559 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000560 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
561 TargetOpts));
562 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
563 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000564 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000565 Preprocessor &PP = *AST->PP.get();
566
Daniel Dunbard5b61262009-09-21 03:03:47 +0000567 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000568 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000569 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000571 // Create and initialize the ASTContext.
572
573 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000574 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000575 *AST->Target.get(),
576 PP.getIdentifierTable(),
577 PP.getSelectorTable(),
578 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000579 /* size_reserve = */0));
580 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Daniel Dunbarcc318932009-09-03 05:59:35 +0000582 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000584 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000585 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000586 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000587 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000588 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000589 Context.setExternalSource(Source);
590
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000591 // Create an AST consumer, even though it isn't used.
592 AST->Consumer.reset(new ASTConsumer);
593
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000594 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000595 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
596 AST->TheSema->Initialize();
597 ReaderPtr->InitializeSema(*AST->TheSema);
598
Mike Stump1eb44332009-09-09 15:08:12 +0000599 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000600}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000601
602namespace {
603
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000604class TopLevelDeclTrackerConsumer : public ASTConsumer {
605 ASTUnit &Unit;
606
607public:
608 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
609
610 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000611 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
612 Decl *D = *it;
613 // FIXME: Currently ObjC method declarations are incorrectly being
614 // reported as top-level declarations, even though their DeclContext
615 // is the containing ObjC @interface/@implementation. This is a
616 // fundamental problem in the parser right now.
617 if (isa<ObjCMethodDecl>(D))
618 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000619 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000620 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000621 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000622
623 // We're not interested in "interesting" decls.
624 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000625};
626
627class TopLevelDeclTrackerAction : public ASTFrontendAction {
628public:
629 ASTUnit &Unit;
630
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000631 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
632 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000633 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000634 }
635
636public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000637 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
638
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000639 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000640 virtual bool usesCompleteTranslationUnit() {
641 return Unit.isCompleteTranslationUnit();
642 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000643};
644
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000645class PrecompilePreambleConsumer : public PCHGenerator {
646 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000647 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000648
649public:
650 PrecompilePreambleConsumer(ASTUnit &Unit,
651 const Preprocessor &PP, bool Chaining,
652 const char *isysroot, llvm::raw_ostream *Out)
653 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
654
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000655 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000656 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
657 Decl *D = *it;
658 // FIXME: Currently ObjC method declarations are incorrectly being
659 // reported as top-level declarations, even though their DeclContext
660 // is the containing ObjC @interface/@implementation. This is a
661 // fundamental problem in the parser right now.
662 if (isa<ObjCMethodDecl>(D))
663 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000664 TopLevelDecls.push_back(D);
665 }
666 }
667
668 virtual void HandleTranslationUnit(ASTContext &Ctx) {
669 PCHGenerator::HandleTranslationUnit(Ctx);
670 if (!Unit.getDiagnostics().hasErrorOccurred()) {
671 // Translate the top-level declarations we captured during
672 // parsing into declaration IDs in the precompiled
673 // preamble. This will allow us to deserialize those top-level
674 // declarations when requested.
675 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
676 Unit.addTopLevelDeclFromPreamble(
677 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000678 }
679 }
680};
681
682class PrecompilePreambleAction : public ASTFrontendAction {
683 ASTUnit &Unit;
684
685public:
686 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
687
688 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
689 llvm::StringRef InFile) {
690 std::string Sysroot;
691 llvm::raw_ostream *OS = 0;
692 bool Chaining;
693 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
694 OS, Chaining))
695 return 0;
696
697 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
698 Sysroot.c_str() : 0;
699 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
700 isysroot, OS);
701 }
702
703 virtual bool hasCodeCompletionSupport() const { return false; }
704 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000705 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000706};
707
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000708}
709
Douglas Gregorabc563f2010-07-19 21:46:24 +0000710/// Parse the source file into a translation unit using the given compiler
711/// invocation, replacing the current translation unit.
712///
713/// \returns True if a failure occurred that causes the ASTUnit not to
714/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000715bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000716 delete SavedMainFileBuffer;
717 SavedMainFileBuffer = 0;
718
Douglas Gregor671947b2010-08-19 01:33:06 +0000719 if (!Invocation.get()) {
720 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000721 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000722 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000723
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000724 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000725 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000726 Clang.setInvocation(Invocation.take());
727 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
728
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000729 // Set up diagnostics, capturing any diagnostics that would
730 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000731 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000732
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000733 // Create the target instance.
734 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
735 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000736 if (!Clang.hasTarget()) {
737 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000738 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000739 }
740
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000741 // Inform the target of the language options.
742 //
743 // FIXME: We shouldn't need to do this, the target should be immutable once
744 // created. This complexity should be lifted elsewhere.
745 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000746
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000747 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
748 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000749 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000750 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000751 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
752 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000753
Douglas Gregorabc563f2010-07-19 21:46:24 +0000754 // Configure the various subsystems.
755 // FIXME: Should we retain the previous file manager?
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000756 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000757 FileSystemOpts = Clang.getFileSystemOpts();
758 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr, FileSystemOpts));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000759 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000760 Ctx.reset();
761 PP.reset();
762
763 // Clear out old caches and data.
764 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000765 CleanTemporaryFiles();
766 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000767
Douglas Gregorf128fed2010-08-20 00:02:33 +0000768 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000769 StoredDiagnostics.erase(
770 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
771 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000772 TopLevelDeclsInPreamble.clear();
773 }
774
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000775 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000776 Clang.setFileManager(&getFileManager());
777
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000778 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000779 Clang.setSourceManager(&getSourceManager());
780
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000781 // If the main file has been overridden due to the use of a preamble,
782 // make that override happen and introduce the preamble.
783 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000784 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000785 if (OverrideMainBuffer) {
786 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
787 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
788 PreprocessorOpts.PrecompiledPreambleBytes.second
789 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000790 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000791 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000792 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000793
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000794 // The stored diagnostic has the old source manager in it; update
795 // the locations to refer into the new source manager. Since we've
796 // been careful to make sure that the source manager's state
797 // before and after are identical, so that we can reuse the source
798 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000799 for (unsigned I = NumStoredDiagnosticsFromDriver,
800 N = StoredDiagnostics.size();
801 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000802 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
803 getSourceManager());
804 StoredDiagnostics[I].setLocation(Loc);
805 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000806
807 // Keep track of the override buffer;
808 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000809 } else {
810 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
811 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000812 }
813
Douglas Gregorabc563f2010-07-19 21:46:24 +0000814 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
815 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000816 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000817 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000818 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000819
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000820 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000821
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000822 // Steal the created target, context, and preprocessor, and take back the
823 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000824 TheSema.reset(Clang.takeSema());
825 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000826 Ctx.reset(Clang.takeASTContext());
827 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000828 Clang.takeSourceManager();
829 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000830 Target.reset(Clang.takeTarget());
831
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000832 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000833
834 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000835 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000836 PreprocessorOpts.eraseRemappedFile(
837 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000838 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
839 }
840
Douglas Gregorabc563f2010-07-19 21:46:24 +0000841 Invocation.reset(Clang.takeInvocation());
842 return false;
843
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000844error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000845 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000846 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000847 PreprocessorOpts.eraseRemappedFile(
848 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000849 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000850 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000851 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000852 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000853
Douglas Gregord54eb442010-10-12 16:25:54 +0000854 StoredDiagnostics.clear();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000855 Clang.takeSourceManager();
856 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000857 Invocation.reset(Clang.takeInvocation());
858 return true;
859}
860
Douglas Gregor44c181a2010-07-23 00:33:23 +0000861/// \brief Simple function to retrieve a path for a preamble precompiled header.
862static std::string GetPreamblePCHPath() {
863 // FIXME: This is lame; sys::Path should provide this function (in particular,
864 // it should know how to find the temporary files dir).
865 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000866 // FIXME: This is a hack so that we can override the preamble file during
867 // crash-recovery testing, which is the only case where the preamble files
868 // are not necessarily cleaned up.
869 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
870 if (TmpFile)
871 return TmpFile;
872
Douglas Gregor44c181a2010-07-23 00:33:23 +0000873 std::string Error;
874 const char *TmpDir = ::getenv("TMPDIR");
875 if (!TmpDir)
876 TmpDir = ::getenv("TEMP");
877 if (!TmpDir)
878 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000879#ifdef LLVM_ON_WIN32
880 if (!TmpDir)
881 TmpDir = ::getenv("USERPROFILE");
882#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000883 if (!TmpDir)
884 TmpDir = "/tmp";
885 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000886 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000887 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000888 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000889 if (P.createTemporaryFileOnDisk())
890 return std::string();
891
Douglas Gregor44c181a2010-07-23 00:33:23 +0000892 return P.str();
893}
894
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000895/// \brief Compute the preamble for the main file, providing the source buffer
896/// that corresponds to the main file along with a pair (bytes, start-of-line)
897/// that describes the preamble.
898std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000899ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
900 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000901 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000902 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000903 = Invocation.getPreprocessorOpts();
904 CreatedBuffer = false;
905
Douglas Gregor44c181a2010-07-23 00:33:23 +0000906 // Try to determine if the main file has been remapped, either from the
907 // command line (to another file) or directly through the compiler invocation
908 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000909 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000910 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
911 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
912 // Check whether there is a file-file remapping of the main file
913 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000914 M = PreprocessorOpts.remapped_file_begin(),
915 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000916 M != E;
917 ++M) {
918 llvm::sys::PathWithStatus MPath(M->first);
919 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
920 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
921 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000922 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000923 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000924 CreatedBuffer = false;
925 }
926
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000927 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000928 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000929 return std::make_pair((llvm::MemoryBuffer*)0,
930 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000931 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000932 }
933 }
934 }
935
936 // Check whether there is a file-buffer remapping. It supercedes the
937 // file-file remapping.
938 for (PreprocessorOptions::remapped_file_buffer_iterator
939 M = PreprocessorOpts.remapped_file_buffer_begin(),
940 E = PreprocessorOpts.remapped_file_buffer_end();
941 M != E;
942 ++M) {
943 llvm::sys::PathWithStatus MPath(M->first);
944 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
945 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
946 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000947 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000948 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000949 CreatedBuffer = false;
950 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000951
Douglas Gregor175c4a92010-07-23 23:58:40 +0000952 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000953 }
954 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000955 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000956 }
957
958 // If the main source file was not remapped, load it now.
959 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000960 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000961 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000962 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000963
964 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000965 }
966
Douglas Gregordf95a132010-08-09 20:45:32 +0000967 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000968}
969
Douglas Gregor754f3492010-07-24 00:38:13 +0000970static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +0000971 unsigned NewSize,
972 llvm::StringRef NewName) {
973 llvm::MemoryBuffer *Result
974 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
975 memcpy(const_cast<char*>(Result->getBufferStart()),
976 Old->getBufferStart(), Old->getBufferSize());
977 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000978 ' ', NewSize - Old->getBufferSize() - 1);
979 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000980
Douglas Gregor754f3492010-07-24 00:38:13 +0000981 return Result;
982}
983
Douglas Gregor175c4a92010-07-23 23:58:40 +0000984/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
985/// the source file.
986///
987/// This routine will compute the preamble of the main source file. If a
988/// non-trivial preamble is found, it will precompile that preamble into a
989/// precompiled header so that the precompiled preamble can be used to reduce
990/// reparsing time. If a precompiled preamble has already been constructed,
991/// this routine will determine if it is still valid and, if so, avoid
992/// rebuilding the precompiled preamble.
993///
Douglas Gregordf95a132010-08-09 20:45:32 +0000994/// \param AllowRebuild When true (the default), this routine is
995/// allowed to rebuild the precompiled preamble if it is found to be
996/// out-of-date.
997///
998/// \param MaxLines When non-zero, the maximum number of lines that
999/// can occur within the preamble.
1000///
Douglas Gregor754f3492010-07-24 00:38:13 +00001001/// \returns If the precompiled preamble can be used, returns a newly-allocated
1002/// buffer that should be used in place of the main file when doing so.
1003/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001004llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +00001005 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +00001006 bool AllowRebuild,
1007 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001008 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1009 PreprocessorOptions &PreprocessorOpts
1010 = PreambleInvocation.getPreprocessorOpts();
1011
1012 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001013 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +00001014 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001015
Douglas Gregor73fc9122010-11-16 20:45:51 +00001016 // If ComputePreamble() Take ownership of the
1017 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1018 if (CreatedPreambleBuffer)
1019 OwnedPreambleBuffer.reset(NewPreamble.first);
1020
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001021 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001022 // We couldn't find a preamble in the main source. Clear out the current
1023 // preamble, if we have one. It's obviously no good any more.
1024 Preamble.clear();
1025 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001026 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001027 PreambleFile.clear();
1028 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001029
1030 // The next time we actually see a preamble, precompile it.
1031 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001032 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001033 }
1034
1035 if (!Preamble.empty()) {
1036 // We've previously computed a preamble. Check whether we have the same
1037 // preamble now that we did before, and that there's enough space in
1038 // the main-file buffer within the precompiled preamble to fit the
1039 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001040 if (Preamble.size() == NewPreamble.second.first &&
1041 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001042 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001043 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001044 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001045 // The preamble has not changed. We may be able to re-use the precompiled
1046 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001047
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001048 // Check that none of the files used by the preamble have changed.
1049 bool AnyFileChanged = false;
1050
1051 // First, make a record of those files that have been overridden via
1052 // remapping or unsaved_files.
1053 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1054 for (PreprocessorOptions::remapped_file_iterator
1055 R = PreprocessorOpts.remapped_file_begin(),
1056 REnd = PreprocessorOpts.remapped_file_end();
1057 !AnyFileChanged && R != REnd;
1058 ++R) {
1059 struct stat StatBuf;
1060 if (stat(R->second.c_str(), &StatBuf)) {
1061 // If we can't stat the file we're remapping to, assume that something
1062 // horrible happened.
1063 AnyFileChanged = true;
1064 break;
1065 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001066
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001067 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1068 StatBuf.st_mtime);
1069 }
1070 for (PreprocessorOptions::remapped_file_buffer_iterator
1071 R = PreprocessorOpts.remapped_file_buffer_begin(),
1072 REnd = PreprocessorOpts.remapped_file_buffer_end();
1073 !AnyFileChanged && R != REnd;
1074 ++R) {
1075 // FIXME: Should we actually compare the contents of file->buffer
1076 // remappings?
1077 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1078 0);
1079 }
1080
1081 // Check whether anything has changed.
1082 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1083 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1084 !AnyFileChanged && F != FEnd;
1085 ++F) {
1086 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1087 = OverriddenFiles.find(F->first());
1088 if (Overridden != OverriddenFiles.end()) {
1089 // This file was remapped; check whether the newly-mapped file
1090 // matches up with the previous mapping.
1091 if (Overridden->second != F->second)
1092 AnyFileChanged = true;
1093 continue;
1094 }
1095
1096 // The file was not remapped; check whether it has changed on disk.
1097 struct stat StatBuf;
1098 if (stat(F->first(), &StatBuf)) {
1099 // If we can't stat the file, assume that something horrible happened.
1100 AnyFileChanged = true;
1101 } else if (StatBuf.st_size != F->second.first ||
1102 StatBuf.st_mtime != F->second.second)
1103 AnyFileChanged = true;
1104 }
1105
1106 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001107 // Okay! We can re-use the precompiled preamble.
1108
1109 // Set the state of the diagnostic object to mimic its state
1110 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001111 // FIXME: This won't catch any #pragma push warning changes that
1112 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001113 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001114 ProcessWarningOptions(getDiagnostics(),
1115 PreambleInvocation.getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001116 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1117 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1118 StoredDiagnostics.erase(
1119 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1120 StoredDiagnostics.end());
1121
1122 // Create a version of the main file buffer that is padded to
1123 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001124 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001125 PreambleReservedSize,
1126 FrontendOpts.Inputs[0].second);
1127 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001128 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001129
1130 // If we aren't allowed to rebuild the precompiled preamble, just
1131 // return now.
1132 if (!AllowRebuild)
1133 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001134
Douglas Gregor175c4a92010-07-23 23:58:40 +00001135 // We can't reuse the previously-computed preamble. Build a new one.
1136 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001137 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001138 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001139 } else if (!AllowRebuild) {
1140 // We aren't allowed to rebuild the precompiled preamble; just
1141 // return now.
1142 return 0;
1143 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001144
1145 // If the preamble rebuild counter > 1, it's because we previously
1146 // failed to build a preamble and we're not yet ready to try
1147 // again. Decrement the counter and return a failure.
1148 if (PreambleRebuildCounter > 1) {
1149 --PreambleRebuildCounter;
1150 return 0;
1151 }
1152
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001153 // Create a temporary file for the precompiled preamble. In rare
1154 // circumstances, this can fail.
1155 std::string PreamblePCHPath = GetPreamblePCHPath();
1156 if (PreamblePCHPath.empty()) {
1157 // Try again next time.
1158 PreambleRebuildCounter = 1;
1159 return 0;
1160 }
1161
Douglas Gregor175c4a92010-07-23 23:58:40 +00001162 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001163 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001164 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001165
1166 // Create a new buffer that stores the preamble. The buffer also contains
1167 // extra space for the original contents of the file (which will be present
1168 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001169 // grows.
1170 PreambleReservedSize = NewPreamble.first->getBufferSize();
1171 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001172 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001173 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001174 PreambleReservedSize *= 2;
1175
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001176 // Save the preamble text for later; we'll need to compare against it for
1177 // subsequent reparses.
1178 Preamble.assign(NewPreamble.first->getBufferStart(),
1179 NewPreamble.first->getBufferStart()
1180 + NewPreamble.second.first);
1181 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1182
Douglas Gregor671947b2010-08-19 01:33:06 +00001183 delete PreambleBuffer;
1184 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001185 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001186 FrontendOpts.Inputs[0].second);
1187 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001188 NewPreamble.first->getBufferStart(), Preamble.size());
1189 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001190 ' ', PreambleReservedSize - Preamble.size() - 1);
1191 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192
1193 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001194 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001195 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1196
1197 // Tell the compiler invocation to generate a temporary precompiled header.
1198 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001199 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001200 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001201 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001202 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1203 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001204
1205 // Create the compiler instance to use for building the precompiled preamble.
1206 CompilerInstance Clang;
1207 Clang.setInvocation(&PreambleInvocation);
1208 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1209
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001210 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001211 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001212
1213 // Create the target instance.
1214 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1215 Clang.getTargetOpts()));
1216 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001217 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1218 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001219 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001220 PreprocessorOpts.eraseRemappedFile(
1221 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001222 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001223 }
1224
1225 // Inform the target of the language options.
1226 //
1227 // FIXME: We shouldn't need to do this, the target should be immutable once
1228 // created. This complexity should be lifted elsewhere.
1229 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1230
1231 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1232 "Invocation must have exactly one source file!");
1233 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1234 "FIXME: AST inputs not yet supported here!");
1235 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1236 "IR inputs not support here!");
1237
1238 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001239 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001240 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001241 StoredDiagnostics.erase(
1242 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1243 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001244 TopLevelDecls.clear();
1245 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246
1247 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner7ad97ff2010-11-23 07:51:02 +00001248 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001249
1250 // Create the source manager.
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001251 Clang.setSourceManager(new SourceManager(getDiagnostics(),
1252 Clang.getFileManager(),
1253 Clang.getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001254
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001255 llvm::OwningPtr<PrecompilePreambleAction> Act;
1256 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1258 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001259 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001260 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1261 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001262 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001263 PreprocessorOpts.eraseRemappedFile(
1264 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001265 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 }
1267
1268 Act->Execute();
1269 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001270 Clang.takeInvocation();
1271
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001272 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001273 // There were errors parsing the preamble, so no precompiled header was
1274 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001275 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1277 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001278 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001279 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001280 PreprocessorOpts.eraseRemappedFile(
1281 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001282 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283 }
1284
1285 // Keep track of the preamble we precompiled.
1286 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001287 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1288 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001289
1290 // Keep track of all of the files that the source manager knows about,
1291 // so we can verify whether they have changed or not.
1292 FilesInPreamble.clear();
1293 SourceManager &SourceMgr = Clang.getSourceManager();
1294 const llvm::MemoryBuffer *MainFileBuffer
1295 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1296 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1297 FEnd = SourceMgr.fileinfo_end();
1298 F != FEnd;
1299 ++F) {
1300 const FileEntry *File = F->second->Entry;
1301 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1302 continue;
1303
1304 FilesInPreamble[File->getName()]
1305 = std::make_pair(F->second->getSize(), File->getModificationTime());
1306 }
1307
Douglas Gregoreababfb2010-08-04 05:53:38 +00001308 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001309 PreprocessorOpts.eraseRemappedFile(
1310 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001311 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001312 PreambleReservedSize,
1313 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001314}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001315
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001316void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1317 std::vector<Decl *> Resolved;
1318 Resolved.reserve(TopLevelDeclsInPreamble.size());
1319 ExternalASTSource &Source = *getASTContext().getExternalSource();
1320 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1321 // Resolve the declaration ID to an actual declaration, possibly
1322 // deserializing the declaration in the process.
1323 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1324 if (D)
1325 Resolved.push_back(D);
1326 }
1327 TopLevelDeclsInPreamble.clear();
1328 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1329}
1330
1331unsigned ASTUnit::getMaxPCHLevel() const {
1332 if (!getOnlyLocalDecls())
1333 return Decl::MaxPCHLevel;
1334
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001335 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001336}
1337
Douglas Gregor213f18b2010-10-28 15:44:59 +00001338llvm::StringRef ASTUnit::getMainFileName() const {
1339 return Invocation->getFrontendOpts().Inputs[0].second;
1340}
1341
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001342bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1343 if (!Invocation)
1344 return true;
1345
1346 // We'll manage file buffers ourselves.
1347 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1348 Invocation->getFrontendOpts().DisableFree = false;
1349
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001350 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001351 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001352 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001353 OverrideMainBuffer
1354 = getMainBufferWithPrecompiledPreamble(*Invocation);
1355 }
1356
Douglas Gregor213f18b2010-10-28 15:44:59 +00001357 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001358 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001359
Douglas Gregor213f18b2010-10-28 15:44:59 +00001360 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001361}
1362
Douglas Gregorabc563f2010-07-19 21:46:24 +00001363ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1364 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1365 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001366 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001367 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001368 bool CompleteTranslationUnit,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001369 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001370 // Create the AST unit.
1371 llvm::OwningPtr<ASTUnit> AST;
1372 AST.reset(new ASTUnit(false));
Douglas Gregore47be3e2010-11-11 00:39:14 +00001373 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001374 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001375 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001376 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001377 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001378 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001379 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001380 AST->Invocation.reset(CI);
1381
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001382 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001383}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001384
1385ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1386 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001387 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001388 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001389 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001390 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001391 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001392 unsigned NumRemappedFiles,
Douglas Gregordf95a132010-08-09 20:45:32 +00001393 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001394 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001395 bool CacheCodeCompletionResults,
1396 bool CXXPrecompilePreamble,
1397 bool CXXChainedPCH) {
Douglas Gregor28019772010-04-05 23:52:57 +00001398 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001399 // No diagnostics engine was provided, so create our own diagnostics object
1400 // with the default options.
1401 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001402 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001403 }
1404
Daniel Dunbar7b556682009-12-02 03:23:45 +00001405 llvm::SmallVector<const char *, 16> Args;
1406 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1407 Args.insert(Args.end(), ArgBegin, ArgEnd);
1408
1409 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1410 // also want to force it to use clang.
1411 Args.push_back("-fsyntax-only");
1412
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001413 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1414
1415 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001416
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001417 {
Douglas Gregore47be3e2010-11-11 00:39:14 +00001418 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001419 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001420
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001421 // FIXME: We shouldn't have to pass in the path info.
1422 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1423 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001424
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001425 // Don't check that inputs exist, they have been remapped.
1426 TheDriver.setCheckInputsExist(false);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001427
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001428 llvm::OwningPtr<driver::Compilation> C(
1429 TheDriver.BuildCompilation(Args.size(), Args.data()));
1430
1431 // We expect to get back exactly one command job, if we didn't something
1432 // failed.
1433 const driver::JobList &Jobs = C->getJobs();
1434 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1435 llvm::SmallString<256> Msg;
1436 llvm::raw_svector_ostream OS(Msg);
1437 C->PrintJob(OS, C->getJobs(), "; ", true);
1438 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1439 return 0;
1440 }
1441
1442 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1443 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1444 Diags->Report(diag::err_fe_expected_clang_command);
1445 return 0;
1446 }
1447
1448 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1449 CI.reset(new CompilerInvocation);
1450 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001451 const_cast<const char **>(CCArgs.data()),
1452 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001453 CCArgs.size(),
1454 *Diags);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001455 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001456
Douglas Gregor4db64a42010-01-23 00:14:00 +00001457 // Override any files that need remapping
1458 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001459 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001460 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001461
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001462 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001463 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001464
Douglas Gregor99ba2022010-10-27 17:24:53 +00001465 // Check whether we should precompile the preamble and/or use chained PCH.
1466 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1467 if (CI->getLangOpts().CPlusPlus) {
1468 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1469
1470 if (PrecompilePreamble && !CXXChainedPCH &&
1471 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1472 PrecompilePreamble = false;
1473 }
1474
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001475 // Create the AST unit.
1476 llvm::OwningPtr<ASTUnit> AST;
1477 AST.reset(new ASTUnit(false));
Douglas Gregore47be3e2010-11-11 00:39:14 +00001478 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001479 AST->Diagnostics = Diags;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001480 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001481 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001482 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1483 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001484 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001485 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1486 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1487 AST->StoredDiagnostics.swap(StoredDiagnostics);
1488 AST->Invocation.reset(CI.take());
1489 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001490}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001491
1492bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1493 if (!Invocation.get())
1494 return true;
1495
Douglas Gregor213f18b2010-10-28 15:44:59 +00001496 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001497 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001498
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001499 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001500 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1501 for (PreprocessorOptions::remapped_file_buffer_iterator
1502 R = PPOpts.remapped_file_buffer_begin(),
1503 REnd = PPOpts.remapped_file_buffer_end();
1504 R != REnd;
1505 ++R) {
1506 delete R->second;
1507 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001508 Invocation->getPreprocessorOpts().clearRemappedFiles();
1509 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1510 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1511 RemappedFiles[I].second);
1512
Douglas Gregoreababfb2010-08-04 05:53:38 +00001513 // If we have a preamble file lying around, or if we might try to
1514 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001515 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001516 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001517 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001518
Douglas Gregorabc563f2010-07-19 21:46:24 +00001519 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001520 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001521 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001522 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1523 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001524
Douglas Gregor175c4a92010-07-23 23:58:40 +00001525 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001526 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor727d93e2010-08-17 00:40:40 +00001527
1528 if (ShouldCacheCodeCompletionResults) {
1529 if (CacheCodeCompletionCoolDown > 0)
1530 --CacheCodeCompletionCoolDown;
1531 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1532 CacheCodeCompletionResults();
1533 }
1534
Douglas Gregor175c4a92010-07-23 23:58:40 +00001535 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001536}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001537
Douglas Gregor87c08a52010-08-13 22:48:40 +00001538//----------------------------------------------------------------------------//
1539// Code completion
1540//----------------------------------------------------------------------------//
1541
1542namespace {
1543 /// \brief Code completion consumer that combines the cached code-completion
1544 /// results from an ASTUnit with the code-completion results provided to it,
1545 /// then passes the result on to
1546 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1547 unsigned NormalContexts;
1548 ASTUnit &AST;
1549 CodeCompleteConsumer &Next;
1550
1551 public:
1552 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001553 bool IncludeMacros, bool IncludeCodePatterns,
1554 bool IncludeGlobals)
1555 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001556 Next.isOutputBinary()), AST(AST), Next(Next)
1557 {
1558 // Compute the set of contexts in which we will look when we don't have
1559 // any information about the specific context.
1560 NormalContexts
1561 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1562 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1563 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1564 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1565 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1566 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1567 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1568 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001569 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001570 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1571 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001572
Douglas Gregor87c08a52010-08-13 22:48:40 +00001573 if (AST.getASTContext().getLangOptions().CPlusPlus)
1574 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1575 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1576 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1577 }
1578
1579 virtual void ProcessCodeCompleteResults(Sema &S,
1580 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001581 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001582 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001583
1584 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1585 OverloadCandidate *Candidates,
1586 unsigned NumCandidates) {
1587 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1588 }
1589 };
1590}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001591
Douglas Gregor5f808c22010-08-16 21:18:39 +00001592/// \brief Helper function that computes which global names are hidden by the
1593/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001594static void CalculateHiddenNames(const CodeCompletionContext &Context,
1595 CodeCompletionResult *Results,
1596 unsigned NumResults,
1597 ASTContext &Ctx,
1598 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001599 bool OnlyTagNames = false;
1600 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001601 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001602 case CodeCompletionContext::CCC_TopLevel:
1603 case CodeCompletionContext::CCC_ObjCInterface:
1604 case CodeCompletionContext::CCC_ObjCImplementation:
1605 case CodeCompletionContext::CCC_ObjCIvarList:
1606 case CodeCompletionContext::CCC_ClassStructUnion:
1607 case CodeCompletionContext::CCC_Statement:
1608 case CodeCompletionContext::CCC_Expression:
1609 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1610 case CodeCompletionContext::CCC_MemberAccess:
1611 case CodeCompletionContext::CCC_Namespace:
1612 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001613 case CodeCompletionContext::CCC_Name:
1614 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001615 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001616 break;
1617
1618 case CodeCompletionContext::CCC_EnumTag:
1619 case CodeCompletionContext::CCC_UnionTag:
1620 case CodeCompletionContext::CCC_ClassOrStructTag:
1621 OnlyTagNames = true;
1622 break;
1623
1624 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001625 case CodeCompletionContext::CCC_MacroName:
1626 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001627 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001628 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001629 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001630 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001631 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001632 case CodeCompletionContext::CCC_Other:
Douglas Gregor721f3592010-08-25 18:41:16 +00001633 // We're looking for nothing, or we're looking for names that cannot
1634 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001635 return;
1636 }
1637
John McCall0a2c5e22010-08-25 06:19:51 +00001638 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001639 for (unsigned I = 0; I != NumResults; ++I) {
1640 if (Results[I].Kind != Result::RK_Declaration)
1641 continue;
1642
1643 unsigned IDNS
1644 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1645
1646 bool Hiding = false;
1647 if (OnlyTagNames)
1648 Hiding = (IDNS & Decl::IDNS_Tag);
1649 else {
1650 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001651 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1652 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001653 if (Ctx.getLangOptions().CPlusPlus)
1654 HiddenIDNS |= Decl::IDNS_Tag;
1655 Hiding = (IDNS & HiddenIDNS);
1656 }
1657
1658 if (!Hiding)
1659 continue;
1660
1661 DeclarationName Name = Results[I].Declaration->getDeclName();
1662 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1663 HiddenNames.insert(Identifier->getName());
1664 else
1665 HiddenNames.insert(Name.getAsString());
1666 }
1667}
1668
1669
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001670void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1671 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001672 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001673 unsigned NumResults) {
1674 // Merge the results we were given with the results we cached.
1675 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001676 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001677 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001678 : (1 << (Context.getKind() - 1)));
1679
1680 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001681 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001682 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall0a2c5e22010-08-25 06:19:51 +00001683 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001684 llvm::SmallVector<Result, 8> AllResults;
1685 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001686 C = AST.cached_completion_begin(),
1687 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001688 C != CEnd; ++C) {
1689 // If the context we are in matches any of the contexts we are
1690 // interested in, we'll add this result.
1691 if ((C->ShowInContexts & InContexts) == 0)
1692 continue;
1693
1694 // If we haven't added any results previously, do so now.
1695 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001696 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1697 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001698 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1699 AddedResult = true;
1700 }
1701
Douglas Gregor5f808c22010-08-16 21:18:39 +00001702 // Determine whether this global completion result is hidden by a local
1703 // completion result. If so, skip it.
1704 if (C->Kind != CXCursor_MacroDefinition &&
1705 HiddenNames.count(C->Completion->getTypedText()))
1706 continue;
1707
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001708 // Adjust priority based on similar type classes.
1709 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001710 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001711 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001712 if (!Context.getPreferredType().isNull()) {
1713 if (C->Kind == CXCursor_MacroDefinition) {
1714 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001715 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001716 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001717 } else if (C->Type) {
1718 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001719 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001720 Context.getPreferredType().getUnqualifiedType());
1721 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1722 if (ExpectedSTC == C->TypeClass) {
1723 // We know this type is similar; check for an exact match.
1724 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001725 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001726 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001727 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001728 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1729 Priority /= CCF_ExactTypeMatch;
1730 else
1731 Priority /= CCF_SimilarTypeMatch;
1732 }
1733 }
1734 }
1735
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001736 // Adjust the completion string, if required.
1737 if (C->Kind == CXCursor_MacroDefinition &&
1738 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1739 // Create a new code-completion string that just contains the
1740 // macro name, without its arguments.
1741 Completion = new CodeCompletionString;
1742 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1743 StringsToDestroy.push_back(Completion);
Douglas Gregor4125c372010-08-25 18:03:13 +00001744 CursorKind = CXCursor_NotImplemented;
1745 Priority = CCP_CodePattern;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001746 }
1747
Douglas Gregor4125c372010-08-25 18:03:13 +00001748 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001749 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001750 }
1751
1752 // If we did not add any cached completion results, just forward the
1753 // results we were given to the next consumer.
1754 if (!AddedResult) {
1755 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1756 return;
1757 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001758
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001759 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1760 AllResults.size());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001761
1762 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1763 delete StringsToDestroy[I];
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001764}
1765
1766
1767
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001768void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1769 RemappedFile *RemappedFiles,
1770 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001771 bool IncludeMacros,
1772 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001773 CodeCompleteConsumer &Consumer,
1774 Diagnostic &Diag, LangOptions &LangOpts,
1775 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00001776 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1777 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001778 if (!Invocation.get())
1779 return;
1780
Douglas Gregor213f18b2010-10-28 15:44:59 +00001781 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001782 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1783 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00001784
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001785 CompilerInvocation CCInvocation(*Invocation);
1786 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1787 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001788
Douglas Gregor87c08a52010-08-13 22:48:40 +00001789 FrontendOpts.ShowMacrosInCodeCompletion
1790 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001791 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001792 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1793 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001794 FrontendOpts.CodeCompletionAt.FileName = File;
1795 FrontendOpts.CodeCompletionAt.Line = Line;
1796 FrontendOpts.CodeCompletionAt.Column = Column;
1797
1798 // Set the language options appropriately.
1799 LangOpts = CCInvocation.getLangOpts();
1800
1801 CompilerInstance Clang;
1802 Clang.setInvocation(&CCInvocation);
1803 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1804
1805 // Set up diagnostics, capturing any diagnostics produced.
1806 Clang.setDiagnostics(&Diag);
Douglas Gregor32be4a52010-10-11 21:37:58 +00001807 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001808 CaptureDroppedDiagnostics Capture(true,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001809 Clang.getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001810 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001811
1812 // Create the target instance.
1813 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1814 Clang.getTargetOpts()));
1815 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001816 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001817 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001818 }
1819
1820 // Inform the target of the language options.
1821 //
1822 // FIXME: We shouldn't need to do this, the target should be immutable once
1823 // created. This complexity should be lifted elsewhere.
1824 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1825
1826 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1827 "Invocation must have exactly one source file!");
1828 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1829 "FIXME: AST inputs not yet supported here!");
1830 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1831 "IR inputs not support here!");
1832
1833
1834 // Use the source and file managers that we were given.
1835 Clang.setFileManager(&FileMgr);
1836 Clang.setSourceManager(&SourceMgr);
1837
1838 // Remap files.
1839 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001840 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00001841 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001842 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1843 RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00001844 OwnedBuffers.push_back(RemappedFiles[I].second);
1845 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001846
Douglas Gregor87c08a52010-08-13 22:48:40 +00001847 // Use the code completion consumer we were given, but adding any cached
1848 // code-completion results.
1849 AugmentedCodeCompleteConsumer
1850 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001851 FrontendOpts.ShowCodePatternsInCodeCompletion,
1852 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001853 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001854
Douglas Gregordf95a132010-08-09 20:45:32 +00001855 // If we have a precompiled preamble, try to use it. We only allow
1856 // the use of the precompiled preamble if we're if the completion
1857 // point is within the main file, after the end of the precompiled
1858 // preamble.
1859 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1860 if (!PreambleFile.empty()) {
1861 using llvm::sys::FileStatus;
1862 llvm::sys::PathWithStatus CompleteFilePath(File);
1863 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1864 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1865 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1866 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00001867 OverrideMainBuffer
Douglas Gregorc9c29a82010-08-25 18:04:15 +00001868 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1869 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00001870 }
1871
1872 // If the main file has been overridden due to the use of a preamble,
1873 // make that override happen and introduce the preamble.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001874 StoredDiagnostics.insert(StoredDiagnostics.end(),
1875 this->StoredDiagnostics.begin(),
1876 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00001877 if (OverrideMainBuffer) {
1878 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1879 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1880 PreprocessorOpts.PrecompiledPreambleBytes.second
1881 = PreambleEndsAtStartOfLine;
1882 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1883 PreprocessorOpts.DisablePCHValidation = true;
1884
1885 // The stored diagnostics have the old source manager. Copy them
1886 // to our output set of stored diagnostics, updating the source
1887 // manager to the one we were given.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001888 for (unsigned I = NumStoredDiagnosticsFromDriver,
1889 N = this->StoredDiagnostics.size();
1890 I < N; ++I) {
Douglas Gregordf95a132010-08-09 20:45:32 +00001891 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1892 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1893 StoredDiagnostics[I].setLocation(Loc);
1894 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001895
Douglas Gregor2283d792010-08-20 00:59:43 +00001896 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001897 } else {
1898 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1899 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00001900 }
1901
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001902 llvm::OwningPtr<SyntaxOnlyAction> Act;
1903 Act.reset(new SyntaxOnlyAction);
1904 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1905 Clang.getFrontendOpts().Inputs[0].first)) {
1906 Act->Execute();
1907 Act->EndSourceFile();
1908 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001909
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001910 // Steal back our resources.
1911 Clang.takeFileManager();
1912 Clang.takeSourceManager();
1913 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001914 Clang.takeCodeCompletionConsumer();
1915}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001916
1917bool ASTUnit::Save(llvm::StringRef File) {
1918 if (getDiagnostics().hasErrorOccurred())
1919 return true;
1920
1921 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1922 // unconditionally create a stat cache when we parse the file?
1923 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001924 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1925 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001926 if (!ErrorInfo.empty() || Out.has_error())
1927 return true;
1928
1929 std::vector<unsigned char> Buffer;
1930 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001931 ASTWriter Writer(Stream);
1932 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001933
1934 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001935 if (!Buffer.empty())
1936 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001937 Out.close();
1938 return Out.has_error();
1939}