blob: b6c4eaac5ff39764d8d7dd8d4b684dd20fccb5a7 [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"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregoreababfb2010-08-04 05:53:38 +000046/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
Douglas Gregor3687e9d2010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000060}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000061
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000067
68 // Free the buffers associated with remapped files. We are required to
69 // perform this operation here because we explicitly request that the
70 // compiler instance *not* free these buffers for each invocation of the
71 // parser.
72 if (Invocation.get()) {
73 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
74 for (PreprocessorOptions::remapped_file_buffer_iterator
75 FB = PPOpts.remapped_file_buffer_begin(),
76 FBEnd = PPOpts.remapped_file_buffer_end();
77 FB != FBEnd;
78 ++FB)
79 delete FB->second;
80 }
Douglas Gregor28233422010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +000083 delete PreambleBuffer;
84
Douglas Gregor87c08a52010-08-13 22:48:40 +000085 ClearCachedCompletionResults();
86
Douglas Gregor385103b2010-07-30 20:58:08 +000087 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
88 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000089}
90
91void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000092 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
93 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000094 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000095}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000096
Douglas Gregor8071e422010-08-15 06:18:01 +000097/// \brief Determine the set of code-completion contexts in which this
98/// declaration should be shown.
99static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000100 const LangOptions &LangOpts,
101 bool &IsNestedNameSpecifier) {
102 IsNestedNameSpecifier = false;
103
Douglas Gregor8071e422010-08-15 06:18:01 +0000104 if (isa<UsingShadowDecl>(ND))
105 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
106 if (!ND)
107 return 0;
108
109 unsigned Contexts = 0;
110 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
111 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
112 // Types can appear in these contexts.
113 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
114 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
115 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
116 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
117 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000118 | (1 << (CodeCompletionContext::CCC_Type - 1))
119 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000120
121 // In C++, types can appear in expressions contexts (for functional casts).
122 if (LangOpts.CPlusPlus)
123 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
124
125 // In Objective-C, message sends can send interfaces. In Objective-C++,
126 // all types are available due to functional casts.
127 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
128 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
129
130 // Deal with tag names.
131 if (isa<EnumDecl>(ND)) {
132 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
133
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000134 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000135 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000136 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000137 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
138 if (Record->isUnion())
139 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
140 else
141 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
142
Douglas Gregor8071e422010-08-15 06:18:01 +0000143 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000144 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000145 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000146 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000147 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
148 // Values can appear in these contexts.
149 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
150 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000151 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000152 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
153 } else if (isa<ObjCProtocolDecl>(ND)) {
154 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
155 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000156 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000157
158 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000159 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000160 }
161
162 return Contexts;
163}
164
Douglas Gregor87c08a52010-08-13 22:48:40 +0000165void ASTUnit::CacheCodeCompletionResults() {
166 if (!TheSema)
167 return;
168
169 llvm::Timer *CachingTimer = 0;
170 if (TimerGroup.get()) {
171 CachingTimer = new llvm::Timer("Cache global code completions",
172 *TimerGroup);
173 CachingTimer->startTimer();
174 Timers.push_back(CachingTimer);
175 }
176
177 // Clear out the previous results.
178 ClearCachedCompletionResults();
179
180 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000181 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000182 llvm::SmallVector<Result, 8> Results;
183 TheSema->GatherGlobalCodeCompletions(Results);
184
185 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000186 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
187
Douglas Gregor87c08a52010-08-13 22:48:40 +0000188 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
189 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000190 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000192 CachedCodeCompletionResult CachedResult;
193 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
194 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000195 Ctx->getLangOptions(),
196 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000197 CachedResult.Priority = Results[I].Priority;
198 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000199 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000200
Douglas Gregorf5586f62010-08-16 18:08:11 +0000201 // Keep track of the type of this completion in an ASTContext-agnostic
202 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000203 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000204 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000205 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000206 CachedResult.Type = 0;
207 } else {
208 CanQualType CanUsageType
209 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
210 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
211
212 // Determine whether we have already seen this type. If so, we save
213 // ourselves the work of formatting the type string by using the
214 // temporary, CanQualType-based hash table to find the associated value.
215 unsigned &TypeValue = CompletionTypes[CanUsageType];
216 if (TypeValue == 0) {
217 TypeValue = CompletionTypes.size();
218 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
219 = TypeValue;
220 }
221
222 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000223 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000224
Douglas Gregor8071e422010-08-15 06:18:01 +0000225 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000226
227 /// Handle nested-name-specifiers in C++.
228 if (TheSema->Context.getLangOptions().CPlusPlus &&
229 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
230 // The contexts in which a nested-name-specifier can appear in C++.
231 unsigned NNSContexts
232 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
233 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
234 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
235 | (1 << (CodeCompletionContext::CCC_Statement - 1))
236 | (1 << (CodeCompletionContext::CCC_Expression - 1))
237 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
238 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
239 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
240 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000241 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000242 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
243 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000244
245 if (isa<NamespaceDecl>(Results[I].Declaration) ||
246 isa<NamespaceAliasDecl>(Results[I].Declaration))
247 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
248
249 if (unsigned RemainingContexts
250 = NNSContexts & ~CachedResult.ShowInContexts) {
251 // If there any contexts where this completion can be a
252 // nested-name-specifier but isn't already an option, create a
253 // nested-name-specifier completion.
254 Results[I].StartsNestedNameSpecifier = true;
255 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
256 CachedResult.ShowInContexts = RemainingContexts;
257 CachedResult.Priority = CCP_NestedNameSpecifier;
258 CachedResult.TypeClass = STC_Void;
259 CachedResult.Type = 0;
260 CachedCompletionResults.push_back(CachedResult);
261 }
262 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000263 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000264 }
265
Douglas Gregor87c08a52010-08-13 22:48:40 +0000266 case Result::RK_Keyword:
267 case Result::RK_Pattern:
268 // Ignore keywords and patterns; we don't care, since they are so
269 // easily regenerated.
270 break;
271
272 case Result::RK_Macro: {
273 CachedCodeCompletionResult CachedResult;
274 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
275 CachedResult.ShowInContexts
276 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
277 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
278 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
279 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
280 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
281 | (1 << (CodeCompletionContext::CCC_Statement - 1))
282 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000283 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000284 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000285 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
286 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
287
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000288
Douglas Gregor87c08a52010-08-13 22:48:40 +0000289 CachedResult.Priority = Results[I].Priority;
290 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000291 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000292 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000293 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000294 CachedCompletionResults.push_back(CachedResult);
295 break;
296 }
297 }
298 Results[I].Destroy();
299 }
300
301 if (CachingTimer)
302 CachingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +0000303
304 // Make a note of the state when we performed this caching.
305 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
306 CacheCodeCompletionCoolDown = 15;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000307}
308
309void ASTUnit::ClearCachedCompletionResults() {
310 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
311 delete CachedCompletionResults[I].Completion;
312 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000313 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000314}
315
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000316namespace {
317
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000318/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000319/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000320class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000321 LangOptions &LangOpt;
322 HeaderSearch &HSI;
323 std::string &TargetTriple;
324 std::string &Predefines;
325 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000327 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000329public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000330 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000331 std::string &TargetTriple, std::string &Predefines,
332 unsigned &Counter)
333 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
334 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000336 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
337 LangOpt = LangOpts;
338 return false;
339 }
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000341 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000342 TargetTriple = Triple;
343 return false;
344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000346 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000347 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000348 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000349 Predefines = Buffers[0].Data;
350 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
351 Predefines += Buffers[I].Data;
352 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000353 return false;
354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000356 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000357 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
358 }
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000360 virtual void ReadCounter(unsigned Value) {
361 Counter = Value;
362 }
363};
364
Douglas Gregora88084b2010-02-18 18:08:43 +0000365class StoredDiagnosticClient : public DiagnosticClient {
366 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
367
368public:
369 explicit StoredDiagnosticClient(
370 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
371 : StoredDiags(StoredDiags) { }
372
373 virtual void HandleDiagnostic(Diagnostic::Level Level,
374 const DiagnosticInfo &Info);
375};
376
377/// \brief RAII object that optionally captures diagnostics, if
378/// there is no diagnostic client to capture them already.
379class CaptureDroppedDiagnostics {
380 Diagnostic &Diags;
381 StoredDiagnosticClient Client;
382 DiagnosticClient *PreviousClient;
383
384public:
385 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
386 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000387 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000388 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000389 if (RequestCapture || Diags.getClient() == 0) {
390 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000391 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000392 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000393 }
394
395 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000396 if (Diags.getClient() == &Client) {
397 Diags.takeClient();
398 Diags.setClient(PreviousClient);
399 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000400 }
401};
402
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000403} // anonymous namespace
404
Douglas Gregora88084b2010-02-18 18:08:43 +0000405void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
406 const DiagnosticInfo &Info) {
407 StoredDiags.push_back(StoredDiagnostic(Level, Info));
408}
409
Steve Naroff77accc12009-09-03 18:19:54 +0000410const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000411 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000412}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000413
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000414const std::string &ASTUnit::getASTFileName() {
415 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000416 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000417}
418
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000419ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000420 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000421 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000422 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000423 unsigned NumRemappedFiles,
424 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000425 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
426
Douglas Gregor28019772010-04-05 23:52:57 +0000427 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000428 // No diagnostics engine was provided, so create our own diagnostics object
429 // with the default options.
430 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000431 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000432 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000433
434 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000435 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000436 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000437 AST->FileMgr.reset(new FileManager);
438 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000439 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000440
Douglas Gregora88084b2010-02-18 18:08:43 +0000441 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000442 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000443 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000444
Douglas Gregor4db64a42010-01-23 00:14:00 +0000445 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
446 // Create the file entry for the file that we're mapping from.
447 const FileEntry *FromFile
448 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
449 RemappedFiles[I].second->getBufferSize(),
450 0);
451 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000452 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000453 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000454 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000455 continue;
456 }
457
458 // Override the contents of the "from" file with the contents of
459 // the "to" file.
460 AST->getSourceManager().overrideFileContents(FromFile,
461 RemappedFiles[I].second);
462 }
463
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000464 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000466 LangOptions LangInfo;
467 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
468 std::string TargetTriple;
469 std::string Predefines;
470 unsigned Counter;
471
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000472 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000473
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000474 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000475 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000476 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000477 Predefines, Counter));
478
Sebastian Redl571db7f2010-08-18 23:56:56 +0000479 switch (Reader->ReadAST(Filename)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000480 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000481 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000483 case ASTReader::Failure:
484 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000485 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000486 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000489 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
490
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000491 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000493 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000494 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000495 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000496 TargetOptions TargetOpts;
497 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000498 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000499 TargetOpts.CPU = "";
500 TargetOpts.Features.clear();
501 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000502 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
503 TargetOpts));
504 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
505 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000506 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507 Preprocessor &PP = *AST->PP.get();
508
Daniel Dunbard5b61262009-09-21 03:03:47 +0000509 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000511 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 // Create and initialize the ASTContext.
514
515 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000516 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000517 *AST->Target.get(),
518 PP.getIdentifierTable(),
519 PP.getSelectorTable(),
520 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000521 /* size_reserve = */0));
522 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Daniel Dunbarcc318932009-09-03 05:59:35 +0000524 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000526 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000527 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000528 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000529 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000530 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000531 Context.setExternalSource(Source);
532
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000533 // Create an AST consumer, even though it isn't used.
534 AST->Consumer.reset(new ASTConsumer);
535
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000536 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000537 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
538 AST->TheSema->Initialize();
539 ReaderPtr->InitializeSema(*AST->TheSema);
540
Mike Stump1eb44332009-09-09 15:08:12 +0000541 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000542}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000543
544namespace {
545
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000546class TopLevelDeclTrackerConsumer : public ASTConsumer {
547 ASTUnit &Unit;
548
549public:
550 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
551
552 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000553 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
554 Decl *D = *it;
555 // FIXME: Currently ObjC method declarations are incorrectly being
556 // reported as top-level declarations, even though their DeclContext
557 // is the containing ObjC @interface/@implementation. This is a
558 // fundamental problem in the parser right now.
559 if (isa<ObjCMethodDecl>(D))
560 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000561 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000562 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000563 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000564
565 // We're not interested in "interesting" decls.
566 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000567};
568
569class TopLevelDeclTrackerAction : public ASTFrontendAction {
570public:
571 ASTUnit &Unit;
572
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000573 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
574 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000575 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000576 }
577
578public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000579 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
580
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000581 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000582 virtual bool usesCompleteTranslationUnit() {
583 return Unit.isCompleteTranslationUnit();
584 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000585};
586
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000587class PrecompilePreambleConsumer : public PCHGenerator {
588 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000589 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000590
591public:
592 PrecompilePreambleConsumer(ASTUnit &Unit,
593 const Preprocessor &PP, bool Chaining,
594 const char *isysroot, llvm::raw_ostream *Out)
595 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
596
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000597 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000598 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
599 Decl *D = *it;
600 // FIXME: Currently ObjC method declarations are incorrectly being
601 // reported as top-level declarations, even though their DeclContext
602 // is the containing ObjC @interface/@implementation. This is a
603 // fundamental problem in the parser right now.
604 if (isa<ObjCMethodDecl>(D))
605 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000606 TopLevelDecls.push_back(D);
607 }
608 }
609
610 virtual void HandleTranslationUnit(ASTContext &Ctx) {
611 PCHGenerator::HandleTranslationUnit(Ctx);
612 if (!Unit.getDiagnostics().hasErrorOccurred()) {
613 // Translate the top-level declarations we captured during
614 // parsing into declaration IDs in the precompiled
615 // preamble. This will allow us to deserialize those top-level
616 // declarations when requested.
617 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
618 Unit.addTopLevelDeclFromPreamble(
619 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000620 }
621 }
622};
623
624class PrecompilePreambleAction : public ASTFrontendAction {
625 ASTUnit &Unit;
626
627public:
628 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
629
630 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
631 llvm::StringRef InFile) {
632 std::string Sysroot;
633 llvm::raw_ostream *OS = 0;
634 bool Chaining;
635 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
636 OS, Chaining))
637 return 0;
638
639 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
640 Sysroot.c_str() : 0;
641 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
642 isysroot, OS);
643 }
644
645 virtual bool hasCodeCompletionSupport() const { return false; }
646 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000647 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000648};
649
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000650}
651
Douglas Gregorabc563f2010-07-19 21:46:24 +0000652/// Parse the source file into a translation unit using the given compiler
653/// invocation, replacing the current translation unit.
654///
655/// \returns True if a failure occurred that causes the ASTUnit not to
656/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000657bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000658 delete SavedMainFileBuffer;
659 SavedMainFileBuffer = 0;
660
Douglas Gregor671947b2010-08-19 01:33:06 +0000661 if (!Invocation.get()) {
662 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000663 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000664 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000665
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000666 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000667 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000668 Clang.setInvocation(Invocation.take());
669 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
670
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000671 // Set up diagnostics, capturing any diagnostics that would
672 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000673 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000674 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
675 getDiagnostics(),
676 StoredDiagnostics);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000677
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000678 // Create the target instance.
679 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
680 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000681 if (!Clang.hasTarget()) {
682 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000683 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000684 }
685
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000686 // Inform the target of the language options.
687 //
688 // FIXME: We shouldn't need to do this, the target should be immutable once
689 // created. This complexity should be lifted elsewhere.
690 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000691
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000692 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
693 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000694 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000695 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000696 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
697 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000698
Douglas Gregorabc563f2010-07-19 21:46:24 +0000699 // Configure the various subsystems.
700 // FIXME: Should we retain the previous file manager?
701 FileMgr.reset(new FileManager);
702 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000703 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000704 Ctx.reset();
705 PP.reset();
706
707 // Clear out old caches and data.
708 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000709 CleanTemporaryFiles();
710 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000711
Douglas Gregorf128fed2010-08-20 00:02:33 +0000712 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000713 StoredDiagnostics.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000714 TopLevelDeclsInPreamble.clear();
715 }
716
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000717 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000718 Clang.setFileManager(&getFileManager());
719
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000720 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000721 Clang.setSourceManager(&getSourceManager());
722
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000723 // If the main file has been overridden due to the use of a preamble,
724 // make that override happen and introduce the preamble.
725 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000726 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000727 if (OverrideMainBuffer) {
728 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
729 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
730 PreprocessorOpts.PrecompiledPreambleBytes.second
731 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000732 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000733 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000734 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000735
736 // Keep track of the override buffer;
737 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000738
739 // The stored diagnostic has the old source manager in it; update
740 // the locations to refer into the new source manager. Since we've
741 // been careful to make sure that the source manager's state
742 // before and after are identical, so that we can reuse the source
743 // location itself.
744 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
745 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
746 getSourceManager());
747 StoredDiagnostics[I].setLocation(Loc);
748 }
Douglas Gregorf128fed2010-08-20 00:02:33 +0000749 } else {
750 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
751 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000752 }
753
Douglas Gregorabc563f2010-07-19 21:46:24 +0000754 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
755 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000756 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000757 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000758 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000759
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000760 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000761
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000762 // Steal the created target, context, and preprocessor, and take back the
763 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000764 TheSema.reset(Clang.takeSema());
765 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000766 Ctx.reset(Clang.takeASTContext());
767 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000768 Clang.takeSourceManager();
769 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000770 Target.reset(Clang.takeTarget());
771
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000772 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000773
774 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000775 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000776 PreprocessorOpts.eraseRemappedFile(
777 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000778 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
779 }
780
Douglas Gregorabc563f2010-07-19 21:46:24 +0000781 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000782
783 // If we were asked to cache code-completion results and don't have any
784 // results yet, do so now.
785 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
786 CacheCodeCompletionResults();
787
Douglas Gregorabc563f2010-07-19 21:46:24 +0000788 return false;
789
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000790error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000791 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000792 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000793 PreprocessorOpts.eraseRemappedFile(
794 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000795 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000796 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000797 delete OverrideMainBuffer;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000798 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000799
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000800 Clang.takeSourceManager();
801 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000802 Invocation.reset(Clang.takeInvocation());
803 return true;
804}
805
Douglas Gregor44c181a2010-07-23 00:33:23 +0000806/// \brief Simple function to retrieve a path for a preamble precompiled header.
807static std::string GetPreamblePCHPath() {
808 // FIXME: This is lame; sys::Path should provide this function (in particular,
809 // it should know how to find the temporary files dir).
810 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000811 // FIXME: This is a hack so that we can override the preamble file during
812 // crash-recovery testing, which is the only case where the preamble files
813 // are not necessarily cleaned up.
814 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
815 if (TmpFile)
816 return TmpFile;
817
Douglas Gregor44c181a2010-07-23 00:33:23 +0000818 std::string Error;
819 const char *TmpDir = ::getenv("TMPDIR");
820 if (!TmpDir)
821 TmpDir = ::getenv("TEMP");
822 if (!TmpDir)
823 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000824#ifdef LLVM_ON_WIN32
825 if (!TmpDir)
826 TmpDir = ::getenv("USERPROFILE");
827#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000828 if (!TmpDir)
829 TmpDir = "/tmp";
830 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000831 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000832 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000833 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000834 if (P.createTemporaryFileOnDisk())
835 return std::string();
836
Douglas Gregor44c181a2010-07-23 00:33:23 +0000837 return P.str();
838}
839
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000840/// \brief Compute the preamble for the main file, providing the source buffer
841/// that corresponds to the main file along with a pair (bytes, start-of-line)
842/// that describes the preamble.
843std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000844ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
845 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000846 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000847 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000848 = Invocation.getPreprocessorOpts();
849 CreatedBuffer = false;
850
Douglas Gregor44c181a2010-07-23 00:33:23 +0000851 // Try to determine if the main file has been remapped, either from the
852 // command line (to another file) or directly through the compiler invocation
853 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000854 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000855 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
856 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
857 // Check whether there is a file-file remapping of the main file
858 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000859 M = PreprocessorOpts.remapped_file_begin(),
860 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000861 M != E;
862 ++M) {
863 llvm::sys::PathWithStatus MPath(M->first);
864 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
865 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
866 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000867 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000868 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000869 CreatedBuffer = false;
870 }
871
Douglas Gregor44c181a2010-07-23 00:33:23 +0000872 Buffer = llvm::MemoryBuffer::getFile(M->second);
873 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000874 return std::make_pair((llvm::MemoryBuffer*)0,
875 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000876 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000877
Douglas Gregor175c4a92010-07-23 23:58:40 +0000878 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000879 M = PreprocessorOpts.eraseRemappedFile(M);
880 E = PreprocessorOpts.remapped_file_end();
Daniel Dunbarc1cf1582010-08-19 19:40:40 +0000881 if (M == E)
882 break;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000883 }
884 }
885 }
886
887 // Check whether there is a file-buffer remapping. It supercedes the
888 // file-file remapping.
889 for (PreprocessorOptions::remapped_file_buffer_iterator
890 M = PreprocessorOpts.remapped_file_buffer_begin(),
891 E = PreprocessorOpts.remapped_file_buffer_end();
892 M != E;
893 ++M) {
894 llvm::sys::PathWithStatus MPath(M->first);
895 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
896 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
897 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000898 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000899 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000900 CreatedBuffer = false;
901 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000902
Douglas Gregor175c4a92010-07-23 23:58:40 +0000903 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
904
905 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000906 M = PreprocessorOpts.eraseRemappedFile(M);
907 E = PreprocessorOpts.remapped_file_buffer_end();
Daniel Dunbarc1cf1582010-08-19 19:40:40 +0000908 if (M == E)
909 break;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000910 }
911 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000912 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000913 }
914
915 // If the main source file was not remapped, load it now.
916 if (!Buffer) {
917 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
918 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000919 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000920
921 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000922 }
923
Douglas Gregordf95a132010-08-09 20:45:32 +0000924 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000925}
926
Douglas Gregor754f3492010-07-24 00:38:13 +0000927static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
928 bool DeleteOld,
929 unsigned NewSize,
930 llvm::StringRef NewName) {
931 llvm::MemoryBuffer *Result
932 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
933 memcpy(const_cast<char*>(Result->getBufferStart()),
934 Old->getBufferStart(), Old->getBufferSize());
935 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000936 ' ', NewSize - Old->getBufferSize() - 1);
937 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000938
939 if (DeleteOld)
940 delete Old;
941
942 return Result;
943}
944
Douglas Gregor175c4a92010-07-23 23:58:40 +0000945/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
946/// the source file.
947///
948/// This routine will compute the preamble of the main source file. If a
949/// non-trivial preamble is found, it will precompile that preamble into a
950/// precompiled header so that the precompiled preamble can be used to reduce
951/// reparsing time. If a precompiled preamble has already been constructed,
952/// this routine will determine if it is still valid and, if so, avoid
953/// rebuilding the precompiled preamble.
954///
Douglas Gregordf95a132010-08-09 20:45:32 +0000955/// \param AllowRebuild When true (the default), this routine is
956/// allowed to rebuild the precompiled preamble if it is found to be
957/// out-of-date.
958///
959/// \param MaxLines When non-zero, the maximum number of lines that
960/// can occur within the preamble.
961///
Douglas Gregor754f3492010-07-24 00:38:13 +0000962/// \returns If the precompiled preamble can be used, returns a newly-allocated
963/// buffer that should be used in place of the main file when doing so.
964/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000965llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +0000966 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +0000967 bool AllowRebuild,
968 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000969 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
970 PreprocessorOptions &PreprocessorOpts
971 = PreambleInvocation.getPreprocessorOpts();
972
973 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000974 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000975 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000976
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000977 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000978 // We couldn't find a preamble in the main source. Clear out the current
979 // preamble, if we have one. It's obviously no good any more.
980 Preamble.clear();
981 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000982 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000983 PreambleFile.clear();
984 }
985 if (CreatedPreambleBuffer)
986 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000987
988 // The next time we actually see a preamble, precompile it.
989 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000990 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000991 }
992
993 if (!Preamble.empty()) {
994 // We've previously computed a preamble. Check whether we have the same
995 // preamble now that we did before, and that there's enough space in
996 // the main-file buffer within the precompiled preamble to fit the
997 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000998 if (Preamble.size() == NewPreamble.second.first &&
999 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001000 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001001 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001002 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001003 // The preamble has not changed. We may be able to re-use the precompiled
1004 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001005
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001006 // Check that none of the files used by the preamble have changed.
1007 bool AnyFileChanged = false;
1008
1009 // First, make a record of those files that have been overridden via
1010 // remapping or unsaved_files.
1011 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1012 for (PreprocessorOptions::remapped_file_iterator
1013 R = PreprocessorOpts.remapped_file_begin(),
1014 REnd = PreprocessorOpts.remapped_file_end();
1015 !AnyFileChanged && R != REnd;
1016 ++R) {
1017 struct stat StatBuf;
1018 if (stat(R->second.c_str(), &StatBuf)) {
1019 // If we can't stat the file we're remapping to, assume that something
1020 // horrible happened.
1021 AnyFileChanged = true;
1022 break;
1023 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001024
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001025 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1026 StatBuf.st_mtime);
1027 }
1028 for (PreprocessorOptions::remapped_file_buffer_iterator
1029 R = PreprocessorOpts.remapped_file_buffer_begin(),
1030 REnd = PreprocessorOpts.remapped_file_buffer_end();
1031 !AnyFileChanged && R != REnd;
1032 ++R) {
1033 // FIXME: Should we actually compare the contents of file->buffer
1034 // remappings?
1035 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1036 0);
1037 }
1038
1039 // Check whether anything has changed.
1040 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1041 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1042 !AnyFileChanged && F != FEnd;
1043 ++F) {
1044 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1045 = OverriddenFiles.find(F->first());
1046 if (Overridden != OverriddenFiles.end()) {
1047 // This file was remapped; check whether the newly-mapped file
1048 // matches up with the previous mapping.
1049 if (Overridden->second != F->second)
1050 AnyFileChanged = true;
1051 continue;
1052 }
1053
1054 // The file was not remapped; check whether it has changed on disk.
1055 struct stat StatBuf;
1056 if (stat(F->first(), &StatBuf)) {
1057 // If we can't stat the file, assume that something horrible happened.
1058 AnyFileChanged = true;
1059 } else if (StatBuf.st_size != F->second.first ||
1060 StatBuf.st_mtime != F->second.second)
1061 AnyFileChanged = true;
1062 }
1063
1064 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001065 // Okay! We can re-use the precompiled preamble.
1066
1067 // Set the state of the diagnostic object to mimic its state
1068 // after parsing the preamble.
1069 getDiagnostics().Reset();
1070 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1071 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1072 StoredDiagnostics.erase(
1073 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1074 StoredDiagnostics.end());
1075
1076 // Create a version of the main file buffer that is padded to
1077 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001078 return CreatePaddedMainFileBuffer(NewPreamble.first,
1079 CreatedPreambleBuffer,
1080 PreambleReservedSize,
1081 FrontendOpts.Inputs[0].second);
1082 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001083 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001084
1085 // If we aren't allowed to rebuild the precompiled preamble, just
1086 // return now.
1087 if (!AllowRebuild)
1088 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001089
1090 // We can't reuse the previously-computed preamble. Build a new one.
1091 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001092 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001093 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001094 } else if (!AllowRebuild) {
1095 // We aren't allowed to rebuild the precompiled preamble; just
1096 // return now.
1097 return 0;
1098 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001099
1100 // If the preamble rebuild counter > 1, it's because we previously
1101 // failed to build a preamble and we're not yet ready to try
1102 // again. Decrement the counter and return a failure.
1103 if (PreambleRebuildCounter > 1) {
1104 --PreambleRebuildCounter;
1105 return 0;
1106 }
1107
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001108 // Create a temporary file for the precompiled preamble. In rare
1109 // circumstances, this can fail.
1110 std::string PreamblePCHPath = GetPreamblePCHPath();
1111 if (PreamblePCHPath.empty()) {
1112 // Try again next time.
1113 PreambleRebuildCounter = 1;
1114 return 0;
1115 }
1116
Douglas Gregor175c4a92010-07-23 23:58:40 +00001117 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001118 llvm::Timer *PreambleTimer = 0;
1119 if (TimerGroup.get()) {
1120 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1121 PreambleTimer->startTimer();
1122 Timers.push_back(PreambleTimer);
1123 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001124
1125 // Create a new buffer that stores the preamble. The buffer also contains
1126 // extra space for the original contents of the file (which will be present
1127 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001128 // grows.
1129 PreambleReservedSize = NewPreamble.first->getBufferSize();
1130 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001131 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001132 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001133 PreambleReservedSize *= 2;
1134
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001135 // Save the preamble text for later; we'll need to compare against it for
1136 // subsequent reparses.
1137 Preamble.assign(NewPreamble.first->getBufferStart(),
1138 NewPreamble.first->getBufferStart()
1139 + NewPreamble.second.first);
1140 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1141
Douglas Gregor671947b2010-08-19 01:33:06 +00001142 delete PreambleBuffer;
1143 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001144 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001145 FrontendOpts.Inputs[0].second);
1146 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001147 NewPreamble.first->getBufferStart(), Preamble.size());
1148 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001149 ' ', PreambleReservedSize - Preamble.size() - 1);
1150 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001151
1152 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001153 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001154 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1155
1156 // Tell the compiler invocation to generate a temporary precompiled header.
1157 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001158 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1159 if (::getenv("LIBCLANG_CHAINING"))
1160 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001161 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001162 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001163
1164 // Create the compiler instance to use for building the precompiled preamble.
1165 CompilerInstance Clang;
1166 Clang.setInvocation(&PreambleInvocation);
1167 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1168
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001169 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001170 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001171 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1172 getDiagnostics(),
1173 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001174
1175 // Create the target instance.
1176 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1177 Clang.getTargetOpts()));
1178 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001179 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1180 Preamble.clear();
1181 if (CreatedPreambleBuffer)
1182 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001183 if (PreambleTimer)
1184 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001185 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001186 PreprocessorOpts.eraseRemappedFile(
1187 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001188 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001189 }
1190
1191 // Inform the target of the language options.
1192 //
1193 // FIXME: We shouldn't need to do this, the target should be immutable once
1194 // created. This complexity should be lifted elsewhere.
1195 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1196
1197 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1198 "Invocation must have exactly one source file!");
1199 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1200 "FIXME: AST inputs not yet supported here!");
1201 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1202 "IR inputs not support here!");
1203
1204 // Clear out old caches and data.
1205 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001206 TopLevelDecls.clear();
1207 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001208
1209 // Create a file manager object to provide access to and cache the filesystem.
1210 Clang.setFileManager(new FileManager);
1211
1212 // Create the source manager.
1213 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1214
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001215 llvm::OwningPtr<PrecompilePreambleAction> Act;
1216 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1218 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001220 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1221 Preamble.clear();
1222 if (CreatedPreambleBuffer)
1223 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001224 if (PreambleTimer)
1225 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001226 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001227 PreprocessorOpts.eraseRemappedFile(
1228 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001229 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001230 }
1231
1232 Act->Execute();
1233 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001234 Clang.takeInvocation();
1235
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001236 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001237 // There were errors parsing the preamble, so no precompiled header was
1238 // generated. Forget that we even tried.
1239 // FIXME: Should we leave a note for ourselves to try again?
1240 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1241 Preamble.clear();
1242 if (CreatedPreambleBuffer)
1243 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001244 if (PreambleTimer)
1245 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001246 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001247 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001248 PreprocessorOpts.eraseRemappedFile(
1249 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001250 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001251 }
1252
1253 // Keep track of the preamble we precompiled.
1254 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001255 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1256 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001257
1258 // Keep track of all of the files that the source manager knows about,
1259 // so we can verify whether they have changed or not.
1260 FilesInPreamble.clear();
1261 SourceManager &SourceMgr = Clang.getSourceManager();
1262 const llvm::MemoryBuffer *MainFileBuffer
1263 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1264 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1265 FEnd = SourceMgr.fileinfo_end();
1266 F != FEnd;
1267 ++F) {
1268 const FileEntry *File = F->second->Entry;
1269 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1270 continue;
1271
1272 FilesInPreamble[File->getName()]
1273 = std::make_pair(F->second->getSize(), File->getModificationTime());
1274 }
1275
Douglas Gregor385103b2010-07-30 20:58:08 +00001276 if (PreambleTimer)
1277 PreambleTimer->stopTimer();
1278
Douglas Gregoreababfb2010-08-04 05:53:38 +00001279 PreambleRebuildCounter = 1;
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 CreatePaddedMainFileBuffer(NewPreamble.first,
1283 CreatedPreambleBuffer,
1284 PreambleReservedSize,
1285 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001287
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001288void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1289 std::vector<Decl *> Resolved;
1290 Resolved.reserve(TopLevelDeclsInPreamble.size());
1291 ExternalASTSource &Source = *getASTContext().getExternalSource();
1292 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1293 // Resolve the declaration ID to an actual declaration, possibly
1294 // deserializing the declaration in the process.
1295 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1296 if (D)
1297 Resolved.push_back(D);
1298 }
1299 TopLevelDeclsInPreamble.clear();
1300 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1301}
1302
1303unsigned ASTUnit::getMaxPCHLevel() const {
1304 if (!getOnlyLocalDecls())
1305 return Decl::MaxPCHLevel;
1306
1307 unsigned Result = 0;
1308 if (isMainFileAST() || SavedMainFileBuffer)
1309 ++Result;
1310 return Result;
1311}
1312
Douglas Gregorabc563f2010-07-19 21:46:24 +00001313ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1314 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1315 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001316 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001317 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001318 bool CompleteTranslationUnit,
1319 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001320 if (!Diags.getPtr()) {
1321 // No diagnostics engine was provided, so create our own diagnostics object
1322 // with the default options.
1323 DiagnosticOptions DiagOpts;
1324 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1325 }
1326
1327 // Create the AST unit.
1328 llvm::OwningPtr<ASTUnit> AST;
1329 AST.reset(new ASTUnit(false));
1330 AST->Diagnostics = Diags;
1331 AST->CaptureDiagnostics = CaptureDiagnostics;
1332 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001333 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001334 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001335 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001336 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001337
Douglas Gregor385103b2010-07-30 20:58:08 +00001338 if (getenv("LIBCLANG_TIMING"))
1339 AST->TimerGroup.reset(
1340 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1341
1342
Douglas Gregor754f3492010-07-24 00:38:13 +00001343 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001344 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001345 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1346 AST->PreambleRebuildCounter = 1;
Douglas Gregor2283d792010-08-20 00:59:43 +00001347 OverrideMainBuffer
1348 = AST->getMainBufferWithPrecompiledPreamble(*AST->Invocation);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001349 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001350
Douglas Gregor385103b2010-07-30 20:58:08 +00001351 llvm::Timer *ParsingTimer = 0;
1352 if (AST->TimerGroup.get()) {
1353 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1354 ParsingTimer->startTimer();
1355 AST->Timers.push_back(ParsingTimer);
1356 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001357
Douglas Gregor385103b2010-07-30 20:58:08 +00001358 bool Failed = AST->Parse(OverrideMainBuffer);
1359 if (ParsingTimer)
1360 ParsingTimer->stopTimer();
1361
1362 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001363}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001364
1365ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1366 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001367 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001368 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001369 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001370 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001371 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001372 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001373 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001374 bool CompleteTranslationUnit,
1375 bool CacheCodeCompletionResults) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001376 bool CreatedDiagnosticsObject = false;
1377
Douglas Gregor28019772010-04-05 23:52:57 +00001378 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001379 // No diagnostics engine was provided, so create our own diagnostics object
1380 // with the default options.
1381 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001382 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001383 CreatedDiagnosticsObject = true;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001384 }
1385
Daniel Dunbar7b556682009-12-02 03:23:45 +00001386 llvm::SmallVector<const char *, 16> Args;
1387 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1388 Args.insert(Args.end(), ArgBegin, ArgEnd);
1389
1390 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1391 // also want to force it to use clang.
1392 Args.push_back("-fsyntax-only");
1393
Daniel Dunbar869824e2009-12-13 03:46:13 +00001394 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001395 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001396 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001397
1398 // Don't check that inputs exist, they have been remapped.
1399 TheDriver.setCheckInputsExist(false);
1400
Daniel Dunbar7b556682009-12-02 03:23:45 +00001401 llvm::OwningPtr<driver::Compilation> C(
1402 TheDriver.BuildCompilation(Args.size(), Args.data()));
1403
1404 // We expect to get back exactly one command job, if we didn't something
1405 // failed.
1406 const driver::JobList &Jobs = C->getJobs();
1407 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1408 llvm::SmallString<256> Msg;
1409 llvm::raw_svector_ostream OS(Msg);
1410 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001411 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001412 return 0;
1413 }
1414
1415 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1416 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001417 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001418 return 0;
1419 }
1420
1421 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001422 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001423 CompilerInvocation::CreateFromArgs(*CI,
1424 const_cast<const char **>(CCArgs.data()),
1425 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001426 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001427 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001428
Douglas Gregor4db64a42010-01-23 00:14:00 +00001429 // Override any files that need remapping
1430 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001431 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001432 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001433
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001434 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001435 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001436
Douglas Gregorf4210892010-08-18 23:38:21 +00001437 CI->getFrontendOpts().DisableFree = false;
Douglas Gregora88084b2010-02-18 18:08:43 +00001438 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001439 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001440 CompleteTranslationUnit,
1441 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001442}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001443
1444bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1445 if (!Invocation.get())
1446 return true;
1447
Douglas Gregor385103b2010-07-30 20:58:08 +00001448 llvm::Timer *ReparsingTimer = 0;
1449 if (TimerGroup.get()) {
1450 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1451 ReparsingTimer->startTimer();
1452 Timers.push_back(ReparsingTimer);
1453 }
1454
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001455 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001456 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1457 for (PreprocessorOptions::remapped_file_buffer_iterator
1458 R = PPOpts.remapped_file_buffer_begin(),
1459 REnd = PPOpts.remapped_file_buffer_end();
1460 R != REnd;
1461 ++R) {
1462 delete R->second;
1463 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001464 Invocation->getPreprocessorOpts().clearRemappedFiles();
1465 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1466 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1467 RemappedFiles[I].second);
1468
Douglas Gregoreababfb2010-08-04 05:53:38 +00001469 // If we have a preamble file lying around, or if we might try to
1470 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001471 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001472 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001473 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001474
Douglas Gregorabc563f2010-07-19 21:46:24 +00001475 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001476 if (!OverrideMainBuffer)
1477 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001478
Douglas Gregor175c4a92010-07-23 23:58:40 +00001479 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001480 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001481 if (ReparsingTimer)
1482 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001483
1484 if (ShouldCacheCodeCompletionResults) {
1485 if (CacheCodeCompletionCoolDown > 0)
1486 --CacheCodeCompletionCoolDown;
1487 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1488 CacheCodeCompletionResults();
1489 }
1490
Douglas Gregor175c4a92010-07-23 23:58:40 +00001491 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001492}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001493
Douglas Gregor87c08a52010-08-13 22:48:40 +00001494//----------------------------------------------------------------------------//
1495// Code completion
1496//----------------------------------------------------------------------------//
1497
1498namespace {
1499 /// \brief Code completion consumer that combines the cached code-completion
1500 /// results from an ASTUnit with the code-completion results provided to it,
1501 /// then passes the result on to
1502 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1503 unsigned NormalContexts;
1504 ASTUnit &AST;
1505 CodeCompleteConsumer &Next;
1506
1507 public:
1508 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001509 bool IncludeMacros, bool IncludeCodePatterns,
1510 bool IncludeGlobals)
1511 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001512 Next.isOutputBinary()), AST(AST), Next(Next)
1513 {
1514 // Compute the set of contexts in which we will look when we don't have
1515 // any information about the specific context.
1516 NormalContexts
1517 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1518 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1519 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1520 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1521 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1522 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1523 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1524 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001525 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001526 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1527 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001528
Douglas Gregor87c08a52010-08-13 22:48:40 +00001529 if (AST.getASTContext().getLangOptions().CPlusPlus)
1530 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1531 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1532 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1533 }
1534
1535 virtual void ProcessCodeCompleteResults(Sema &S,
1536 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001537 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001538 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001539
1540 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1541 OverloadCandidate *Candidates,
1542 unsigned NumCandidates) {
1543 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1544 }
1545 };
1546}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001547
Douglas Gregor5f808c22010-08-16 21:18:39 +00001548/// \brief Helper function that computes which global names are hidden by the
1549/// local code-completion results.
1550void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001551 CodeCompletionResult *Results,
Douglas Gregor5f808c22010-08-16 21:18:39 +00001552 unsigned NumResults,
1553 ASTContext &Ctx,
1554 llvm::StringSet<> &HiddenNames) {
1555 bool OnlyTagNames = false;
1556 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001557 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001558 case CodeCompletionContext::CCC_TopLevel:
1559 case CodeCompletionContext::CCC_ObjCInterface:
1560 case CodeCompletionContext::CCC_ObjCImplementation:
1561 case CodeCompletionContext::CCC_ObjCIvarList:
1562 case CodeCompletionContext::CCC_ClassStructUnion:
1563 case CodeCompletionContext::CCC_Statement:
1564 case CodeCompletionContext::CCC_Expression:
1565 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1566 case CodeCompletionContext::CCC_MemberAccess:
1567 case CodeCompletionContext::CCC_Namespace:
1568 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001569 case CodeCompletionContext::CCC_Name:
1570 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001571 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001572 break;
1573
1574 case CodeCompletionContext::CCC_EnumTag:
1575 case CodeCompletionContext::CCC_UnionTag:
1576 case CodeCompletionContext::CCC_ClassOrStructTag:
1577 OnlyTagNames = true;
1578 break;
1579
1580 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001581 case CodeCompletionContext::CCC_MacroName:
1582 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001583 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001584 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001585 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001586 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001587 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001588 case CodeCompletionContext::CCC_Other:
Douglas Gregor721f3592010-08-25 18:41:16 +00001589 // We're looking for nothing, or we're looking for names that cannot
1590 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001591 return;
1592 }
1593
John McCall0a2c5e22010-08-25 06:19:51 +00001594 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001595 for (unsigned I = 0; I != NumResults; ++I) {
1596 if (Results[I].Kind != Result::RK_Declaration)
1597 continue;
1598
1599 unsigned IDNS
1600 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1601
1602 bool Hiding = false;
1603 if (OnlyTagNames)
1604 Hiding = (IDNS & Decl::IDNS_Tag);
1605 else {
1606 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001607 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1608 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001609 if (Ctx.getLangOptions().CPlusPlus)
1610 HiddenIDNS |= Decl::IDNS_Tag;
1611 Hiding = (IDNS & HiddenIDNS);
1612 }
1613
1614 if (!Hiding)
1615 continue;
1616
1617 DeclarationName Name = Results[I].Declaration->getDeclName();
1618 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1619 HiddenNames.insert(Identifier->getName());
1620 else
1621 HiddenNames.insert(Name.getAsString());
1622 }
1623}
1624
1625
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001626void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1627 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001628 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001629 unsigned NumResults) {
1630 // Merge the results we were given with the results we cached.
1631 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001632 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001633 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001634 : (1 << (Context.getKind() - 1)));
1635
1636 // Contains the set of names that are hidden by "local" completion results.
1637 llvm::StringSet<> HiddenNames;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001638 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall0a2c5e22010-08-25 06:19:51 +00001639 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001640 llvm::SmallVector<Result, 8> AllResults;
1641 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001642 C = AST.cached_completion_begin(),
1643 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001644 C != CEnd; ++C) {
1645 // If the context we are in matches any of the contexts we are
1646 // interested in, we'll add this result.
1647 if ((C->ShowInContexts & InContexts) == 0)
1648 continue;
1649
1650 // If we haven't added any results previously, do so now.
1651 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001652 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1653 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001654 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1655 AddedResult = true;
1656 }
1657
Douglas Gregor5f808c22010-08-16 21:18:39 +00001658 // Determine whether this global completion result is hidden by a local
1659 // completion result. If so, skip it.
1660 if (C->Kind != CXCursor_MacroDefinition &&
1661 HiddenNames.count(C->Completion->getTypedText()))
1662 continue;
1663
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001664 // Adjust priority based on similar type classes.
1665 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001666 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001667 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001668 if (!Context.getPreferredType().isNull()) {
1669 if (C->Kind == CXCursor_MacroDefinition) {
1670 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001671 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001672 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001673 } else if (C->Type) {
1674 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001675 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001676 Context.getPreferredType().getUnqualifiedType());
1677 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1678 if (ExpectedSTC == C->TypeClass) {
1679 // We know this type is similar; check for an exact match.
1680 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001681 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001682 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001683 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001684 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1685 Priority /= CCF_ExactTypeMatch;
1686 else
1687 Priority /= CCF_SimilarTypeMatch;
1688 }
1689 }
1690 }
1691
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001692 // Adjust the completion string, if required.
1693 if (C->Kind == CXCursor_MacroDefinition &&
1694 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1695 // Create a new code-completion string that just contains the
1696 // macro name, without its arguments.
1697 Completion = new CodeCompletionString;
1698 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1699 StringsToDestroy.push_back(Completion);
Douglas Gregor4125c372010-08-25 18:03:13 +00001700 CursorKind = CXCursor_NotImplemented;
1701 Priority = CCP_CodePattern;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001702 }
1703
Douglas Gregor4125c372010-08-25 18:03:13 +00001704 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001705 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001706 }
1707
1708 // If we did not add any cached completion results, just forward the
1709 // results we were given to the next consumer.
1710 if (!AddedResult) {
1711 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1712 return;
1713 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001714
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001715 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1716 AllResults.size());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001717
1718 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1719 delete StringsToDestroy[I];
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001720}
1721
1722
1723
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001724void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1725 RemappedFile *RemappedFiles,
1726 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001727 bool IncludeMacros,
1728 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001729 CodeCompleteConsumer &Consumer,
1730 Diagnostic &Diag, LangOptions &LangOpts,
1731 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00001732 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1733 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001734 if (!Invocation.get())
1735 return;
1736
Douglas Gregordf95a132010-08-09 20:45:32 +00001737 llvm::Timer *CompletionTimer = 0;
1738 if (TimerGroup.get()) {
1739 llvm::SmallString<128> TimerName;
1740 llvm::raw_svector_ostream TimerNameOut(TimerName);
1741 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1742 << Column;
1743 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1744 CompletionTimer->startTimer();
1745 Timers.push_back(CompletionTimer);
1746 }
1747
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001748 CompilerInvocation CCInvocation(*Invocation);
1749 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1750 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001751
Douglas Gregor87c08a52010-08-13 22:48:40 +00001752 FrontendOpts.ShowMacrosInCodeCompletion
1753 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001754 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001755 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1756 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001757 FrontendOpts.CodeCompletionAt.FileName = File;
1758 FrontendOpts.CodeCompletionAt.Line = Line;
1759 FrontendOpts.CodeCompletionAt.Column = Column;
1760
Douglas Gregorcee235c2010-08-05 09:09:23 +00001761 // Turn on spell-checking when performing code completion. It leads
1762 // to better results.
1763 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1764 CCInvocation.getLangOpts().SpellChecking = 1;
1765
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001766 // Set the language options appropriately.
1767 LangOpts = CCInvocation.getLangOpts();
1768
1769 CompilerInstance Clang;
1770 Clang.setInvocation(&CCInvocation);
1771 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1772
1773 // Set up diagnostics, capturing any diagnostics produced.
1774 Clang.setDiagnostics(&Diag);
1775 CaptureDroppedDiagnostics Capture(true,
1776 Clang.getDiagnostics(),
1777 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001778
1779 // Create the target instance.
1780 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1781 Clang.getTargetOpts()));
1782 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001783 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001784 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1785 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001786 }
1787
1788 // Inform the target of the language options.
1789 //
1790 // FIXME: We shouldn't need to do this, the target should be immutable once
1791 // created. This complexity should be lifted elsewhere.
1792 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1793
1794 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1795 "Invocation must have exactly one source file!");
1796 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1797 "FIXME: AST inputs not yet supported here!");
1798 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1799 "IR inputs not support here!");
1800
1801
1802 // Use the source and file managers that we were given.
1803 Clang.setFileManager(&FileMgr);
1804 Clang.setSourceManager(&SourceMgr);
1805
1806 // Remap files.
1807 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001808 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00001809 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001810 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1811 RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00001812 OwnedBuffers.push_back(RemappedFiles[I].second);
1813 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001814
Douglas Gregor87c08a52010-08-13 22:48:40 +00001815 // Use the code completion consumer we were given, but adding any cached
1816 // code-completion results.
1817 AugmentedCodeCompleteConsumer
1818 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001819 FrontendOpts.ShowCodePatternsInCodeCompletion,
1820 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001821 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001822
Douglas Gregordf95a132010-08-09 20:45:32 +00001823 // If we have a precompiled preamble, try to use it. We only allow
1824 // the use of the precompiled preamble if we're if the completion
1825 // point is within the main file, after the end of the precompiled
1826 // preamble.
1827 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1828 if (!PreambleFile.empty()) {
1829 using llvm::sys::FileStatus;
1830 llvm::sys::PathWithStatus CompleteFilePath(File);
1831 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1832 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1833 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1834 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00001835 OverrideMainBuffer
Douglas Gregorc9c29a82010-08-25 18:04:15 +00001836 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1837 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00001838 }
1839
1840 // If the main file has been overridden due to the use of a preamble,
1841 // make that override happen and introduce the preamble.
1842 if (OverrideMainBuffer) {
1843 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1844 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1845 PreprocessorOpts.PrecompiledPreambleBytes.second
1846 = PreambleEndsAtStartOfLine;
1847 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1848 PreprocessorOpts.DisablePCHValidation = true;
1849
1850 // The stored diagnostics have the old source manager. Copy them
1851 // to our output set of stored diagnostics, updating the source
1852 // manager to the one we were given.
1853 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1854 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1855 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1856 StoredDiagnostics[I].setLocation(Loc);
1857 }
Douglas Gregor2283d792010-08-20 00:59:43 +00001858
1859 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001860 } else {
1861 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1862 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00001863 }
1864
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001865 llvm::OwningPtr<SyntaxOnlyAction> Act;
1866 Act.reset(new SyntaxOnlyAction);
1867 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1868 Clang.getFrontendOpts().Inputs[0].first)) {
1869 Act->Execute();
1870 Act->EndSourceFile();
1871 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001872
1873 if (CompletionTimer)
1874 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001875
1876 // Steal back our resources.
1877 Clang.takeFileManager();
1878 Clang.takeSourceManager();
1879 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001880 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001881 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001882}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001883
1884bool ASTUnit::Save(llvm::StringRef File) {
1885 if (getDiagnostics().hasErrorOccurred())
1886 return true;
1887
1888 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1889 // unconditionally create a stat cache when we parse the file?
1890 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001891 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1892 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001893 if (!ErrorInfo.empty() || Out.has_error())
1894 return true;
1895
1896 std::vector<unsigned char> Buffer;
1897 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001898 ASTWriter Writer(Stream);
1899 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001900
1901 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001902 if (!Buffer.empty())
1903 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001904 Out.close();
1905 return Out.has_error();
1906}