blob: 384edb4502b1c7169846e1a9ca117b8bd1698bab [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregorbb420ab2010-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 Gregord03e8232010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor028d3e42010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000060}
Douglas Gregord03e8232010-04-05 21:10:19 +000061
Daniel Dunbar764c0822009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-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 Gregor96c04262010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +000083 delete PreambleBuffer;
84
Douglas Gregorb14904c2010-08-13 22:48:40 +000085 ClearCachedCompletionResults();
86
Douglas Gregor15ba0b32010-07-30 20:58:08 +000087 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
88 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089}
90
91void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000092 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
93 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000095}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000096
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000100 const LangOptions &LangOpts,
101 bool &IsNestedNameSpecifier) {
102 IsNestedNameSpecifier = false;
103
Douglas Gregor39982192010-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))
118 | (1 << (CodeCompletionContext::CCC_Type - 1));
119
120 // In C++, types can appear in expressions contexts (for functional casts).
121 if (LangOpts.CPlusPlus)
122 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
123
124 // In Objective-C, message sends can send interfaces. In Objective-C++,
125 // all types are available due to functional casts.
126 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
127 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
128
129 // Deal with tag names.
130 if (isa<EnumDecl>(ND)) {
131 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
132
Douglas Gregor59cab552010-08-16 23:05:20 +0000133 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000134 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000135 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000136 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
137 if (Record->isUnion())
138 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
139 else
140 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
141
Douglas Gregor39982192010-08-15 06:18:01 +0000142 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000143 IsNestedNameSpecifier = true;
144 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
145 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000146 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
147 // Values can appear in these contexts.
148 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
149 | (1 << (CodeCompletionContext::CCC_Expression - 1))
150 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
151 } else if (isa<ObjCProtocolDecl>(ND)) {
152 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
153 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000154 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000155
156 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000157 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000158 }
159
160 return Contexts;
161}
162
Douglas Gregorb14904c2010-08-13 22:48:40 +0000163void ASTUnit::CacheCodeCompletionResults() {
164 if (!TheSema)
165 return;
166
167 llvm::Timer *CachingTimer = 0;
168 if (TimerGroup.get()) {
169 CachingTimer = new llvm::Timer("Cache global code completions",
170 *TimerGroup);
171 CachingTimer->startTimer();
172 Timers.push_back(CachingTimer);
173 }
174
175 // Clear out the previous results.
176 ClearCachedCompletionResults();
177
178 // Gather the set of global code completions.
179 typedef CodeCompleteConsumer::Result Result;
180 llvm::SmallVector<Result, 8> Results;
181 TheSema->GatherGlobalCodeCompletions(Results);
182
183 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000184 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
185
Douglas Gregorb14904c2010-08-13 22:48:40 +0000186 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
187 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000188 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000189 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000190 CachedCodeCompletionResult CachedResult;
191 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
192 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 Ctx->getLangOptions(),
194 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000195 CachedResult.Priority = Results[I].Priority;
196 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000197 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000198
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000199 // Keep track of the type of this completion in an ASTContext-agnostic
200 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000201 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000202 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000203 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000204 CachedResult.Type = 0;
205 } else {
206 CanQualType CanUsageType
207 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
208 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
209
210 // Determine whether we have already seen this type. If so, we save
211 // ourselves the work of formatting the type string by using the
212 // temporary, CanQualType-based hash table to find the associated value.
213 unsigned &TypeValue = CompletionTypes[CanUsageType];
214 if (TypeValue == 0) {
215 TypeValue = CompletionTypes.size();
216 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
217 = TypeValue;
218 }
219
220 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000221 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000222
Douglas Gregor39982192010-08-15 06:18:01 +0000223 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000224
225 /// Handle nested-name-specifiers in C++.
226 if (TheSema->Context.getLangOptions().CPlusPlus &&
227 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
228 // The contexts in which a nested-name-specifier can appear in C++.
229 unsigned NNSContexts
230 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
231 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
232 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
233 | (1 << (CodeCompletionContext::CCC_Statement - 1))
234 | (1 << (CodeCompletionContext::CCC_Expression - 1))
235 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
236 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
237 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
238 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000239 | (1 << (CodeCompletionContext::CCC_Type - 1))
240 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000241
242 if (isa<NamespaceDecl>(Results[I].Declaration) ||
243 isa<NamespaceAliasDecl>(Results[I].Declaration))
244 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
245
246 if (unsigned RemainingContexts
247 = NNSContexts & ~CachedResult.ShowInContexts) {
248 // If there any contexts where this completion can be a
249 // nested-name-specifier but isn't already an option, create a
250 // nested-name-specifier completion.
251 Results[I].StartsNestedNameSpecifier = true;
252 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
253 CachedResult.ShowInContexts = RemainingContexts;
254 CachedResult.Priority = CCP_NestedNameSpecifier;
255 CachedResult.TypeClass = STC_Void;
256 CachedResult.Type = 0;
257 CachedCompletionResults.push_back(CachedResult);
258 }
259 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000260 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000261 }
262
Douglas Gregorb14904c2010-08-13 22:48:40 +0000263 case Result::RK_Keyword:
264 case Result::RK_Pattern:
265 // Ignore keywords and patterns; we don't care, since they are so
266 // easily regenerated.
267 break;
268
269 case Result::RK_Macro: {
270 CachedCodeCompletionResult CachedResult;
271 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
272 CachedResult.ShowInContexts
273 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
274 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
275 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
276 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
277 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
278 | (1 << (CodeCompletionContext::CCC_Statement - 1))
279 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000280 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
281 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000282
Douglas Gregorb14904c2010-08-13 22:48:40 +0000283 CachedResult.Priority = Results[I].Priority;
284 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000285 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000286 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000287 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000288 CachedCompletionResults.push_back(CachedResult);
289 break;
290 }
291 }
292 Results[I].Destroy();
293 }
294
295 if (CachingTimer)
296 CachingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000297
298 // Make a note of the state when we performed this caching.
299 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
300 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000301}
302
303void ASTUnit::ClearCachedCompletionResults() {
304 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
305 delete CachedCompletionResults[I].Completion;
306 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000307 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000308}
309
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000310namespace {
311
Sebastian Redl2c499f62010-08-18 23:56:43 +0000312/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000313/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000314class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000315 LangOptions &LangOpt;
316 HeaderSearch &HSI;
317 std::string &TargetTriple;
318 std::string &Predefines;
319 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000320
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000321 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000322
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000323public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000324 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000325 std::string &TargetTriple, std::string &Predefines,
326 unsigned &Counter)
327 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
328 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000329
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000330 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
331 LangOpt = LangOpts;
332 return false;
333 }
Mike Stump11289f42009-09-09 15:08:12 +0000334
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000335 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000336 TargetTriple = Triple;
337 return false;
338 }
Mike Stump11289f42009-09-09 15:08:12 +0000339
Sebastian Redl8b41f302010-07-14 23:29:55 +0000340 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000341 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000342 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000343 Predefines = Buffers[0].Data;
344 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
345 Predefines += Buffers[I].Data;
346 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000347 return false;
348 }
Mike Stump11289f42009-09-09 15:08:12 +0000349
Douglas Gregora2f49452010-03-16 19:09:18 +0000350 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000351 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
352 }
Mike Stump11289f42009-09-09 15:08:12 +0000353
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000354 virtual void ReadCounter(unsigned Value) {
355 Counter = Value;
356 }
357};
358
Douglas Gregor33cdd812010-02-18 18:08:43 +0000359class StoredDiagnosticClient : public DiagnosticClient {
360 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
361
362public:
363 explicit StoredDiagnosticClient(
364 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
365 : StoredDiags(StoredDiags) { }
366
367 virtual void HandleDiagnostic(Diagnostic::Level Level,
368 const DiagnosticInfo &Info);
369};
370
371/// \brief RAII object that optionally captures diagnostics, if
372/// there is no diagnostic client to capture them already.
373class CaptureDroppedDiagnostics {
374 Diagnostic &Diags;
375 StoredDiagnosticClient Client;
376 DiagnosticClient *PreviousClient;
377
378public:
379 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
380 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000381 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000382 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000383 if (RequestCapture || Diags.getClient() == 0) {
384 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000385 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000386 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000387 }
388
389 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000390 if (Diags.getClient() == &Client) {
391 Diags.takeClient();
392 Diags.setClient(PreviousClient);
393 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000394 }
395};
396
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000397} // anonymous namespace
398
Douglas Gregor33cdd812010-02-18 18:08:43 +0000399void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
400 const DiagnosticInfo &Info) {
401 StoredDiags.push_back(StoredDiagnostic(Level, Info));
402}
403
Steve Naroffc0683b92009-09-03 18:19:54 +0000404const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000405 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000406}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000407
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000408const std::string &ASTUnit::getASTFileName() {
409 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000410 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000411}
412
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000413ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000414 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000415 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000416 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000417 unsigned NumRemappedFiles,
418 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000419 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
420
Douglas Gregor7f95d262010-04-05 23:52:57 +0000421 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000422 // No diagnostics engine was provided, so create our own diagnostics object
423 // with the default options.
424 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000425 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000426 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000427
428 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000429 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000430 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000431 AST->FileMgr.reset(new FileManager);
432 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000433 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000434
Douglas Gregor33cdd812010-02-18 18:08:43 +0000435 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000436 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000437 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000438
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000439 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
440 // Create the file entry for the file that we're mapping from.
441 const FileEntry *FromFile
442 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
443 RemappedFiles[I].second->getBufferSize(),
444 0);
445 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000446 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000447 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000448 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000449 continue;
450 }
451
452 // Override the contents of the "from" file with the contents of
453 // the "to" file.
454 AST->getSourceManager().overrideFileContents(FromFile,
455 RemappedFiles[I].second);
456 }
457
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000458 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000459
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000460 LangOptions LangInfo;
461 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
462 std::string TargetTriple;
463 std::string Predefines;
464 unsigned Counter;
465
Sebastian Redl2c499f62010-08-18 23:56:43 +0000466 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000467
Sebastian Redl2c499f62010-08-18 23:56:43 +0000468 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000469 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000470 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000471 Predefines, Counter));
472
Sebastian Redl3e31c722010-08-18 23:56:56 +0000473 switch (Reader->ReadAST(Filename)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000474 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000475 break;
Mike Stump11289f42009-09-09 15:08:12 +0000476
Sebastian Redl2c499f62010-08-18 23:56:43 +0000477 case ASTReader::Failure:
478 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000479 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000480 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Daniel Dunbara8a50932009-12-02 08:44:16 +0000483 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
484
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000485 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000486
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000487 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000488 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000489 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000490 TargetOptions TargetOpts;
491 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000492 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000493 TargetOpts.CPU = "";
494 TargetOpts.Features.clear();
495 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000496 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
497 TargetOpts));
498 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
499 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000500 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000501 Preprocessor &PP = *AST->PP.get();
502
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000503 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000504 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000505 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000506
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000507 // Create and initialize the ASTContext.
508
509 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000510 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000511 *AST->Target.get(),
512 PP.getIdentifierTable(),
513 PP.getSelectorTable(),
514 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000515 /* size_reserve = */0));
516 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000517
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000518 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000519
Sebastian Redl2c499f62010-08-18 23:56:43 +0000520 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000521 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000522 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000523 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000524 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000525 Context.setExternalSource(Source);
526
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000527 // Create an AST consumer, even though it isn't used.
528 AST->Consumer.reset(new ASTConsumer);
529
Sebastian Redl2c499f62010-08-18 23:56:43 +0000530 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000531 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
532 AST->TheSema->Initialize();
533 ReaderPtr->InitializeSema(*AST->TheSema);
534
Mike Stump11289f42009-09-09 15:08:12 +0000535 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000536}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000537
538namespace {
539
Daniel Dunbar644dca02009-12-04 08:17:33 +0000540class TopLevelDeclTrackerConsumer : public ASTConsumer {
541 ASTUnit &Unit;
542
543public:
544 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
545
546 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000547 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
548 Decl *D = *it;
549 // FIXME: Currently ObjC method declarations are incorrectly being
550 // reported as top-level declarations, even though their DeclContext
551 // is the containing ObjC @interface/@implementation. This is a
552 // fundamental problem in the parser right now.
553 if (isa<ObjCMethodDecl>(D))
554 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000555 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000556 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000557 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000558
559 // We're not interested in "interesting" decls.
560 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000561};
562
563class TopLevelDeclTrackerAction : public ASTFrontendAction {
564public:
565 ASTUnit &Unit;
566
Daniel Dunbar764c0822009-12-01 09:51:01 +0000567 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
568 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000569 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000570 }
571
572public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000573 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
574
Daniel Dunbar764c0822009-12-01 09:51:01 +0000575 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000576 virtual bool usesCompleteTranslationUnit() {
577 return Unit.isCompleteTranslationUnit();
578 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000579};
580
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000581class PrecompilePreambleConsumer : public PCHGenerator {
582 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000583 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000584
585public:
586 PrecompilePreambleConsumer(ASTUnit &Unit,
587 const Preprocessor &PP, bool Chaining,
588 const char *isysroot, llvm::raw_ostream *Out)
589 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
590
Douglas Gregore9db88f2010-08-03 19:06:41 +0000591 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000592 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
593 Decl *D = *it;
594 // FIXME: Currently ObjC method declarations are incorrectly being
595 // reported as top-level declarations, even though their DeclContext
596 // is the containing ObjC @interface/@implementation. This is a
597 // fundamental problem in the parser right now.
598 if (isa<ObjCMethodDecl>(D))
599 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000600 TopLevelDecls.push_back(D);
601 }
602 }
603
604 virtual void HandleTranslationUnit(ASTContext &Ctx) {
605 PCHGenerator::HandleTranslationUnit(Ctx);
606 if (!Unit.getDiagnostics().hasErrorOccurred()) {
607 // Translate the top-level declarations we captured during
608 // parsing into declaration IDs in the precompiled
609 // preamble. This will allow us to deserialize those top-level
610 // declarations when requested.
611 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
612 Unit.addTopLevelDeclFromPreamble(
613 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000614 }
615 }
616};
617
618class PrecompilePreambleAction : public ASTFrontendAction {
619 ASTUnit &Unit;
620
621public:
622 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
623
624 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
625 llvm::StringRef InFile) {
626 std::string Sysroot;
627 llvm::raw_ostream *OS = 0;
628 bool Chaining;
629 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
630 OS, Chaining))
631 return 0;
632
633 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
634 Sysroot.c_str() : 0;
635 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
636 isysroot, OS);
637 }
638
639 virtual bool hasCodeCompletionSupport() const { return false; }
640 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000641 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000642};
643
Daniel Dunbar764c0822009-12-01 09:51:01 +0000644}
645
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000646/// Parse the source file into a translation unit using the given compiler
647/// invocation, replacing the current translation unit.
648///
649/// \returns True if a failure occurred that causes the ASTUnit not to
650/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000651bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000652 delete SavedMainFileBuffer;
653 SavedMainFileBuffer = 0;
654
Douglas Gregora0734c52010-08-19 01:33:06 +0000655 if (!Invocation.get()) {
656 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000657 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000658 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000659
Daniel Dunbar764c0822009-12-01 09:51:01 +0000660 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000661 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000662 Clang.setInvocation(Invocation.take());
663 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
664
Douglas Gregor8e984da2010-08-04 16:47:14 +0000665 // Set up diagnostics, capturing any diagnostics that would
666 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000667 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000668 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
669 getDiagnostics(),
670 StoredDiagnostics);
Douglas Gregord03e8232010-04-05 21:10:19 +0000671
Daniel Dunbar764c0822009-12-01 09:51:01 +0000672 // Create the target instance.
673 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
674 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000675 if (!Clang.hasTarget()) {
676 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000677 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000678 }
679
Daniel Dunbar764c0822009-12-01 09:51:01 +0000680 // Inform the target of the language options.
681 //
682 // FIXME: We shouldn't need to do this, the target should be immutable once
683 // created. This complexity should be lifted elsewhere.
684 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000685
Daniel Dunbar764c0822009-12-01 09:51:01 +0000686 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
687 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000688 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000689 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000690 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
691 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000692
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000693 // Configure the various subsystems.
694 // FIXME: Should we retain the previous file manager?
695 FileMgr.reset(new FileManager);
696 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000697 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000698 Ctx.reset();
699 PP.reset();
700
701 // Clear out old caches and data.
702 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000703 CleanTemporaryFiles();
704 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000705
Douglas Gregor7b02b582010-08-20 00:02:33 +0000706 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000707 StoredDiagnostics.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000708 TopLevelDeclsInPreamble.clear();
709 }
710
Daniel Dunbar764c0822009-12-01 09:51:01 +0000711 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000712 Clang.setFileManager(&getFileManager());
713
Daniel Dunbar764c0822009-12-01 09:51:01 +0000714 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000715 Clang.setSourceManager(&getSourceManager());
716
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000717 // If the main file has been overridden due to the use of a preamble,
718 // make that override happen and introduce the preamble.
719 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000720 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000721 if (OverrideMainBuffer) {
722 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
723 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
724 PreprocessorOpts.PrecompiledPreambleBytes.second
725 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000726 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000727 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000728 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000729
730 // Keep track of the override buffer;
731 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000732
733 // The stored diagnostic has the old source manager in it; update
734 // the locations to refer into the new source manager. Since we've
735 // been careful to make sure that the source manager's state
736 // before and after are identical, so that we can reuse the source
737 // location itself.
738 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
739 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
740 getSourceManager());
741 StoredDiagnostics[I].setLocation(Loc);
742 }
Douglas Gregor7b02b582010-08-20 00:02:33 +0000743 } else {
744 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
745 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000746 }
747
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000748 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
749 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000750 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000751 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000752 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000753
Daniel Dunbar644dca02009-12-04 08:17:33 +0000754 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000755
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000756 // Steal the created target, context, and preprocessor, and take back the
757 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000758 TheSema.reset(Clang.takeSema());
759 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000760 Ctx.reset(Clang.takeASTContext());
761 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000762 Clang.takeSourceManager();
763 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000764 Target.reset(Clang.takeTarget());
765
Daniel Dunbar644dca02009-12-04 08:17:33 +0000766 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000767
768 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000769 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000770 PreprocessorOpts.eraseRemappedFile(
771 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000772 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
773 }
774
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000775 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000776
777 // If we were asked to cache code-completion results and don't have any
778 // results yet, do so now.
779 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
780 CacheCodeCompletionResults();
781
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000782 return false;
783
Daniel Dunbar764c0822009-12-01 09:51:01 +0000784error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000785 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000786 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000787 PreprocessorOpts.eraseRemappedFile(
788 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000789 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000790 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000791 delete OverrideMainBuffer;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000792 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000793
Daniel Dunbar764c0822009-12-01 09:51:01 +0000794 Clang.takeSourceManager();
795 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000796 Invocation.reset(Clang.takeInvocation());
797 return true;
798}
799
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000800/// \brief Simple function to retrieve a path for a preamble precompiled header.
801static std::string GetPreamblePCHPath() {
802 // FIXME: This is lame; sys::Path should provide this function (in particular,
803 // it should know how to find the temporary files dir).
804 // FIXME: This is really lame. I copied this code from the Driver!
805 std::string Error;
806 const char *TmpDir = ::getenv("TMPDIR");
807 if (!TmpDir)
808 TmpDir = ::getenv("TEMP");
809 if (!TmpDir)
810 TmpDir = ::getenv("TMP");
811 if (!TmpDir)
812 TmpDir = "/tmp";
813 llvm::sys::Path P(TmpDir);
814 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000815 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000816 if (P.createTemporaryFileOnDisk())
817 return std::string();
818
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000819 return P.str();
820}
821
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000822/// \brief Compute the preamble for the main file, providing the source buffer
823/// that corresponds to the main file along with a pair (bytes, start-of-line)
824/// that describes the preamble.
825std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000826ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
827 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000828 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000829 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000830 = Invocation.getPreprocessorOpts();
831 CreatedBuffer = false;
832
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000833 // Try to determine if the main file has been remapped, either from the
834 // command line (to another file) or directly through the compiler invocation
835 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000836 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000837 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
838 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
839 // Check whether there is a file-file remapping of the main file
840 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000841 M = PreprocessorOpts.remapped_file_begin(),
842 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000843 M != E;
844 ++M) {
845 llvm::sys::PathWithStatus MPath(M->first);
846 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
847 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
848 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000849 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000850 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000851 CreatedBuffer = false;
852 }
853
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000854 Buffer = llvm::MemoryBuffer::getFile(M->second);
855 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000856 return std::make_pair((llvm::MemoryBuffer*)0,
857 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000858 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000859
Douglas Gregor4dde7492010-07-23 23:58:40 +0000860 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000861 M = PreprocessorOpts.eraseRemappedFile(M);
862 E = PreprocessorOpts.remapped_file_end();
Daniel Dunbar438c7722010-08-19 19:40:40 +0000863 if (M == E)
864 break;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000865 }
866 }
867 }
868
869 // Check whether there is a file-buffer remapping. It supercedes the
870 // file-file remapping.
871 for (PreprocessorOptions::remapped_file_buffer_iterator
872 M = PreprocessorOpts.remapped_file_buffer_begin(),
873 E = PreprocessorOpts.remapped_file_buffer_end();
874 M != E;
875 ++M) {
876 llvm::sys::PathWithStatus MPath(M->first);
877 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
878 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
879 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000880 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000881 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000882 CreatedBuffer = false;
883 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000884
Douglas Gregor4dde7492010-07-23 23:58:40 +0000885 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
886
887 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000888 M = PreprocessorOpts.eraseRemappedFile(M);
889 E = PreprocessorOpts.remapped_file_buffer_end();
Daniel Dunbar438c7722010-08-19 19:40:40 +0000890 if (M == E)
891 break;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000892 }
893 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000894 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000895 }
896
897 // If the main source file was not remapped, load it now.
898 if (!Buffer) {
899 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
900 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000901 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000902
903 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000904 }
905
Douglas Gregor028d3e42010-08-09 20:45:32 +0000906 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000907}
908
Douglas Gregor6481ef12010-07-24 00:38:13 +0000909static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
910 bool DeleteOld,
911 unsigned NewSize,
912 llvm::StringRef NewName) {
913 llvm::MemoryBuffer *Result
914 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
915 memcpy(const_cast<char*>(Result->getBufferStart()),
916 Old->getBufferStart(), Old->getBufferSize());
917 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000918 ' ', NewSize - Old->getBufferSize() - 1);
919 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000920
921 if (DeleteOld)
922 delete Old;
923
924 return Result;
925}
926
Douglas Gregor4dde7492010-07-23 23:58:40 +0000927/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
928/// the source file.
929///
930/// This routine will compute the preamble of the main source file. If a
931/// non-trivial preamble is found, it will precompile that preamble into a
932/// precompiled header so that the precompiled preamble can be used to reduce
933/// reparsing time. If a precompiled preamble has already been constructed,
934/// this routine will determine if it is still valid and, if so, avoid
935/// rebuilding the precompiled preamble.
936///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000937/// \param AllowRebuild When true (the default), this routine is
938/// allowed to rebuild the precompiled preamble if it is found to be
939/// out-of-date.
940///
941/// \param MaxLines When non-zero, the maximum number of lines that
942/// can occur within the preamble.
943///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000944/// \returns If the precompiled preamble can be used, returns a newly-allocated
945/// buffer that should be used in place of the main file when doing so.
946/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000947llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +0000948 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +0000949 bool AllowRebuild,
950 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000951 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
952 PreprocessorOptions &PreprocessorOpts
953 = PreambleInvocation.getPreprocessorOpts();
954
955 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000956 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +0000957 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000958
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000959 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000960 // We couldn't find a preamble in the main source. Clear out the current
961 // preamble, if we have one. It's obviously no good any more.
962 Preamble.clear();
963 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000964 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000965 PreambleFile.clear();
966 }
967 if (CreatedPreambleBuffer)
968 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000969
970 // The next time we actually see a preamble, precompile it.
971 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000972 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000973 }
974
975 if (!Preamble.empty()) {
976 // We've previously computed a preamble. Check whether we have the same
977 // preamble now that we did before, and that there's enough space in
978 // the main-file buffer within the precompiled preamble to fit the
979 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000980 if (Preamble.size() == NewPreamble.second.first &&
981 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000982 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000983 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000984 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000985 // The preamble has not changed. We may be able to re-use the precompiled
986 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000987
Douglas Gregor0e119552010-07-31 00:40:00 +0000988 // Check that none of the files used by the preamble have changed.
989 bool AnyFileChanged = false;
990
991 // First, make a record of those files that have been overridden via
992 // remapping or unsaved_files.
993 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
994 for (PreprocessorOptions::remapped_file_iterator
995 R = PreprocessorOpts.remapped_file_begin(),
996 REnd = PreprocessorOpts.remapped_file_end();
997 !AnyFileChanged && R != REnd;
998 ++R) {
999 struct stat StatBuf;
1000 if (stat(R->second.c_str(), &StatBuf)) {
1001 // If we can't stat the file we're remapping to, assume that something
1002 // horrible happened.
1003 AnyFileChanged = true;
1004 break;
1005 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001006
Douglas Gregor0e119552010-07-31 00:40:00 +00001007 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1008 StatBuf.st_mtime);
1009 }
1010 for (PreprocessorOptions::remapped_file_buffer_iterator
1011 R = PreprocessorOpts.remapped_file_buffer_begin(),
1012 REnd = PreprocessorOpts.remapped_file_buffer_end();
1013 !AnyFileChanged && R != REnd;
1014 ++R) {
1015 // FIXME: Should we actually compare the contents of file->buffer
1016 // remappings?
1017 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1018 0);
1019 }
1020
1021 // Check whether anything has changed.
1022 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1023 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1024 !AnyFileChanged && F != FEnd;
1025 ++F) {
1026 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1027 = OverriddenFiles.find(F->first());
1028 if (Overridden != OverriddenFiles.end()) {
1029 // This file was remapped; check whether the newly-mapped file
1030 // matches up with the previous mapping.
1031 if (Overridden->second != F->second)
1032 AnyFileChanged = true;
1033 continue;
1034 }
1035
1036 // The file was not remapped; check whether it has changed on disk.
1037 struct stat StatBuf;
1038 if (stat(F->first(), &StatBuf)) {
1039 // If we can't stat the file, assume that something horrible happened.
1040 AnyFileChanged = true;
1041 } else if (StatBuf.st_size != F->second.first ||
1042 StatBuf.st_mtime != F->second.second)
1043 AnyFileChanged = true;
1044 }
1045
1046 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001047 // Okay! We can re-use the precompiled preamble.
1048
1049 // Set the state of the diagnostic object to mimic its state
1050 // after parsing the preamble.
1051 getDiagnostics().Reset();
1052 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1053 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1054 StoredDiagnostics.erase(
1055 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1056 StoredDiagnostics.end());
1057
1058 // Create a version of the main file buffer that is padded to
1059 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001060 return CreatePaddedMainFileBuffer(NewPreamble.first,
1061 CreatedPreambleBuffer,
1062 PreambleReservedSize,
1063 FrontendOpts.Inputs[0].second);
1064 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001065 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001066
1067 // If we aren't allowed to rebuild the precompiled preamble, just
1068 // return now.
1069 if (!AllowRebuild)
1070 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001071
1072 // We can't reuse the previously-computed preamble. Build a new one.
1073 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001074 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001075 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001076 } else if (!AllowRebuild) {
1077 // We aren't allowed to rebuild the precompiled preamble; just
1078 // return now.
1079 return 0;
1080 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001081
1082 // If the preamble rebuild counter > 1, it's because we previously
1083 // failed to build a preamble and we're not yet ready to try
1084 // again. Decrement the counter and return a failure.
1085 if (PreambleRebuildCounter > 1) {
1086 --PreambleRebuildCounter;
1087 return 0;
1088 }
1089
Douglas Gregor4dde7492010-07-23 23:58:40 +00001090 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001091 llvm::Timer *PreambleTimer = 0;
1092 if (TimerGroup.get()) {
1093 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1094 PreambleTimer->startTimer();
1095 Timers.push_back(PreambleTimer);
1096 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001097
1098 // Create a new buffer that stores the preamble. The buffer also contains
1099 // extra space for the original contents of the file (which will be present
1100 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001101 // grows.
1102 PreambleReservedSize = NewPreamble.first->getBufferSize();
1103 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001104 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001105 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001106 PreambleReservedSize *= 2;
1107
Douglas Gregord9a30af2010-08-02 20:51:39 +00001108 // Save the preamble text for later; we'll need to compare against it for
1109 // subsequent reparses.
1110 Preamble.assign(NewPreamble.first->getBufferStart(),
1111 NewPreamble.first->getBufferStart()
1112 + NewPreamble.second.first);
1113 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1114
Douglas Gregora0734c52010-08-19 01:33:06 +00001115 delete PreambleBuffer;
1116 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001117 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001118 FrontendOpts.Inputs[0].second);
1119 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001120 NewPreamble.first->getBufferStart(), Preamble.size());
1121 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001122 ' ', PreambleReservedSize - Preamble.size() - 1);
1123 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001124
1125 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001126 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001127 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1128
1129 // Tell the compiler invocation to generate a temporary precompiled header.
1130 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redle98428d2010-08-06 00:35:11 +00001131 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1132 if (::getenv("LIBCLANG_CHAINING"))
1133 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001134 // FIXME: Generate the precompiled header into memory?
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001135 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001136
1137 // Create the compiler instance to use for building the precompiled preamble.
1138 CompilerInstance Clang;
1139 Clang.setInvocation(&PreambleInvocation);
1140 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1141
Douglas Gregor8e984da2010-08-04 16:47:14 +00001142 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001143 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001144 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1145 getDiagnostics(),
1146 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001147
1148 // Create the target instance.
1149 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1150 Clang.getTargetOpts()));
1151 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001152 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1153 Preamble.clear();
1154 if (CreatedPreambleBuffer)
1155 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001156 if (PreambleTimer)
1157 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001158 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001159 PreprocessorOpts.eraseRemappedFile(
1160 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001161 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001162 }
1163
1164 // Inform the target of the language options.
1165 //
1166 // FIXME: We shouldn't need to do this, the target should be immutable once
1167 // created. This complexity should be lifted elsewhere.
1168 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1169
1170 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1171 "Invocation must have exactly one source file!");
1172 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1173 "FIXME: AST inputs not yet supported here!");
1174 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1175 "IR inputs not support here!");
1176
1177 // Clear out old caches and data.
1178 StoredDiagnostics.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001179 TopLevelDecls.clear();
1180 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001181
1182 // Create a file manager object to provide access to and cache the filesystem.
1183 Clang.setFileManager(new FileManager);
1184
1185 // Create the source manager.
1186 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1187
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001188 llvm::OwningPtr<PrecompilePreambleAction> Act;
1189 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001190 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1191 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001192 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001193 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1194 Preamble.clear();
1195 if (CreatedPreambleBuffer)
1196 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001197 if (PreambleTimer)
1198 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001199 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001200 PreprocessorOpts.eraseRemappedFile(
1201 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001202 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001203 }
1204
1205 Act->Execute();
1206 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207 Clang.takeInvocation();
1208
Douglas Gregore9db88f2010-08-03 19:06:41 +00001209 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210 // There were errors parsing the preamble, so no precompiled header was
1211 // generated. Forget that we even tried.
1212 // FIXME: Should we leave a note for ourselves to try again?
1213 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1214 Preamble.clear();
1215 if (CreatedPreambleBuffer)
1216 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001217 if (PreambleTimer)
1218 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001219 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001220 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001221 PreprocessorOpts.eraseRemappedFile(
1222 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001223 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001224 }
1225
1226 // Keep track of the preamble we precompiled.
1227 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001228 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1229 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001230
1231 // Keep track of all of the files that the source manager knows about,
1232 // so we can verify whether they have changed or not.
1233 FilesInPreamble.clear();
1234 SourceManager &SourceMgr = Clang.getSourceManager();
1235 const llvm::MemoryBuffer *MainFileBuffer
1236 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1237 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1238 FEnd = SourceMgr.fileinfo_end();
1239 F != FEnd;
1240 ++F) {
1241 const FileEntry *File = F->second->Entry;
1242 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1243 continue;
1244
1245 FilesInPreamble[File->getName()]
1246 = std::make_pair(F->second->getSize(), File->getModificationTime());
1247 }
1248
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001249 if (PreambleTimer)
1250 PreambleTimer->stopTimer();
1251
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001252 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001253 PreprocessorOpts.eraseRemappedFile(
1254 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001255 return CreatePaddedMainFileBuffer(NewPreamble.first,
1256 CreatedPreambleBuffer,
1257 PreambleReservedSize,
1258 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001259}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001260
Douglas Gregore9db88f2010-08-03 19:06:41 +00001261void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1262 std::vector<Decl *> Resolved;
1263 Resolved.reserve(TopLevelDeclsInPreamble.size());
1264 ExternalASTSource &Source = *getASTContext().getExternalSource();
1265 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1266 // Resolve the declaration ID to an actual declaration, possibly
1267 // deserializing the declaration in the process.
1268 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1269 if (D)
1270 Resolved.push_back(D);
1271 }
1272 TopLevelDeclsInPreamble.clear();
1273 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1274}
1275
1276unsigned ASTUnit::getMaxPCHLevel() const {
1277 if (!getOnlyLocalDecls())
1278 return Decl::MaxPCHLevel;
1279
1280 unsigned Result = 0;
1281 if (isMainFileAST() || SavedMainFileBuffer)
1282 ++Result;
1283 return Result;
1284}
1285
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001286ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1287 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1288 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001289 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001290 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001291 bool CompleteTranslationUnit,
1292 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001293 if (!Diags.getPtr()) {
1294 // No diagnostics engine was provided, so create our own diagnostics object
1295 // with the default options.
1296 DiagnosticOptions DiagOpts;
1297 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1298 }
1299
1300 // Create the AST unit.
1301 llvm::OwningPtr<ASTUnit> AST;
1302 AST.reset(new ASTUnit(false));
1303 AST->Diagnostics = Diags;
1304 AST->CaptureDiagnostics = CaptureDiagnostics;
1305 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001306 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001307 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001308 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001309 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001310
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001311 if (getenv("LIBCLANG_TIMING"))
1312 AST->TimerGroup.reset(
1313 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1314
1315
Douglas Gregor6481ef12010-07-24 00:38:13 +00001316 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregora5fd5222010-07-28 22:12:37 +00001317 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001318 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1319 AST->PreambleRebuildCounter = 1;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001320 OverrideMainBuffer
1321 = AST->getMainBufferWithPrecompiledPreamble(*AST->Invocation);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001322 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001323
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001324 llvm::Timer *ParsingTimer = 0;
1325 if (AST->TimerGroup.get()) {
1326 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1327 ParsingTimer->startTimer();
1328 AST->Timers.push_back(ParsingTimer);
1329 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001330
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001331 bool Failed = AST->Parse(OverrideMainBuffer);
1332 if (ParsingTimer)
1333 ParsingTimer->stopTimer();
1334
1335 return Failed? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001336}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001337
1338ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1339 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001340 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001341 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001342 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001343 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001344 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001345 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001346 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001347 bool CompleteTranslationUnit,
1348 bool CacheCodeCompletionResults) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001349 bool CreatedDiagnosticsObject = false;
1350
Douglas Gregor7f95d262010-04-05 23:52:57 +00001351 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001352 // No diagnostics engine was provided, so create our own diagnostics object
1353 // with the default options.
1354 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001355 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001356 CreatedDiagnosticsObject = true;
Douglas Gregord03e8232010-04-05 21:10:19 +00001357 }
1358
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001359 llvm::SmallVector<const char *, 16> Args;
1360 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1361 Args.insert(Args.end(), ArgBegin, ArgEnd);
1362
1363 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1364 // also want to force it to use clang.
1365 Args.push_back("-fsyntax-only");
1366
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001367 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +00001368 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001369 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001370
1371 // Don't check that inputs exist, they have been remapped.
1372 TheDriver.setCheckInputsExist(false);
1373
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001374 llvm::OwningPtr<driver::Compilation> C(
1375 TheDriver.BuildCompilation(Args.size(), Args.data()));
1376
1377 // We expect to get back exactly one command job, if we didn't something
1378 // failed.
1379 const driver::JobList &Jobs = C->getJobs();
1380 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1381 llvm::SmallString<256> Msg;
1382 llvm::raw_svector_ostream OS(Msg);
1383 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +00001384 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001385 return 0;
1386 }
1387
1388 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1389 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +00001390 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001391 return 0;
1392 }
1393
1394 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001395 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +00001396 CompilerInvocation::CreateFromArgs(*CI,
1397 const_cast<const char **>(CCArgs.data()),
1398 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001399 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001400 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +00001401
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001402 // Override any files that need remapping
1403 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001404 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001405 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001406
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001407 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001408 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001409
Douglas Gregor4c6ed902010-08-18 23:38:21 +00001410 CI->getFrontendOpts().DisableFree = false;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001411 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001412 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001413 CompleteTranslationUnit,
1414 CacheCodeCompletionResults);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001415}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001416
1417bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1418 if (!Invocation.get())
1419 return true;
1420
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001421 llvm::Timer *ReparsingTimer = 0;
1422 if (TimerGroup.get()) {
1423 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1424 ReparsingTimer->startTimer();
1425 Timers.push_back(ReparsingTimer);
1426 }
1427
Douglas Gregor0e119552010-07-31 00:40:00 +00001428 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001429 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1430 for (PreprocessorOptions::remapped_file_buffer_iterator
1431 R = PPOpts.remapped_file_buffer_begin(),
1432 REnd = PPOpts.remapped_file_buffer_end();
1433 R != REnd;
1434 ++R) {
1435 delete R->second;
1436 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001437 Invocation->getPreprocessorOpts().clearRemappedFiles();
1438 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1439 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1440 RemappedFiles[I].second);
1441
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001442 // If we have a preamble file lying around, or if we might try to
1443 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001444 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001445 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001446 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001447
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001448 // Clear out the diagnostics state.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001449 if (!OverrideMainBuffer)
1450 getDiagnostics().Reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001451
Douglas Gregor4dde7492010-07-23 23:58:40 +00001452 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001453 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001454 if (ReparsingTimer)
1455 ReparsingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001456
1457 if (ShouldCacheCodeCompletionResults) {
1458 if (CacheCodeCompletionCoolDown > 0)
1459 --CacheCodeCompletionCoolDown;
1460 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1461 CacheCodeCompletionResults();
1462 }
1463
Douglas Gregor4dde7492010-07-23 23:58:40 +00001464 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001465}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001466
Douglas Gregorb14904c2010-08-13 22:48:40 +00001467//----------------------------------------------------------------------------//
1468// Code completion
1469//----------------------------------------------------------------------------//
1470
1471namespace {
1472 /// \brief Code completion consumer that combines the cached code-completion
1473 /// results from an ASTUnit with the code-completion results provided to it,
1474 /// then passes the result on to
1475 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1476 unsigned NormalContexts;
1477 ASTUnit &AST;
1478 CodeCompleteConsumer &Next;
1479
1480 public:
1481 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001482 bool IncludeMacros, bool IncludeCodePatterns,
1483 bool IncludeGlobals)
1484 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001485 Next.isOutputBinary()), AST(AST), Next(Next)
1486 {
1487 // Compute the set of contexts in which we will look when we don't have
1488 // any information about the specific context.
1489 NormalContexts
1490 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1491 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1492 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1493 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1494 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1495 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1496 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1497 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1498 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1499
1500 if (AST.getASTContext().getLangOptions().CPlusPlus)
1501 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1502 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1503 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1504 }
1505
1506 virtual void ProcessCodeCompleteResults(Sema &S,
1507 CodeCompletionContext Context,
1508 Result *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001509 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001510
1511 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1512 OverloadCandidate *Candidates,
1513 unsigned NumCandidates) {
1514 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1515 }
1516 };
1517}
Douglas Gregord46cf182010-08-16 20:01:48 +00001518
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001519/// \brief Helper function that computes which global names are hidden by the
1520/// local code-completion results.
1521void CalculateHiddenNames(const CodeCompletionContext &Context,
1522 CodeCompleteConsumer::Result *Results,
1523 unsigned NumResults,
1524 ASTContext &Ctx,
1525 llvm::StringSet<> &HiddenNames) {
1526 bool OnlyTagNames = false;
1527 switch (Context.getKind()) {
1528 case CodeCompletionContext::CCC_Other:
1529 case CodeCompletionContext::CCC_TopLevel:
1530 case CodeCompletionContext::CCC_ObjCInterface:
1531 case CodeCompletionContext::CCC_ObjCImplementation:
1532 case CodeCompletionContext::CCC_ObjCIvarList:
1533 case CodeCompletionContext::CCC_ClassStructUnion:
1534 case CodeCompletionContext::CCC_Statement:
1535 case CodeCompletionContext::CCC_Expression:
1536 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1537 case CodeCompletionContext::CCC_MemberAccess:
1538 case CodeCompletionContext::CCC_Namespace:
1539 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001540 case CodeCompletionContext::CCC_Name:
1541 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001542 break;
1543
1544 case CodeCompletionContext::CCC_EnumTag:
1545 case CodeCompletionContext::CCC_UnionTag:
1546 case CodeCompletionContext::CCC_ClassOrStructTag:
1547 OnlyTagNames = true;
1548 break;
1549
1550 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001551 case CodeCompletionContext::CCC_MacroName:
1552 case CodeCompletionContext::CCC_MacroNameUse:
1553 // If we're just looking for protocol or macro names, nothing can hide them.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001554 return;
1555 }
1556
1557 typedef CodeCompleteConsumer::Result Result;
1558 for (unsigned I = 0; I != NumResults; ++I) {
1559 if (Results[I].Kind != Result::RK_Declaration)
1560 continue;
1561
1562 unsigned IDNS
1563 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1564
1565 bool Hiding = false;
1566 if (OnlyTagNames)
1567 Hiding = (IDNS & Decl::IDNS_Tag);
1568 else {
1569 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001570 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1571 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001572 if (Ctx.getLangOptions().CPlusPlus)
1573 HiddenIDNS |= Decl::IDNS_Tag;
1574 Hiding = (IDNS & HiddenIDNS);
1575 }
1576
1577 if (!Hiding)
1578 continue;
1579
1580 DeclarationName Name = Results[I].Declaration->getDeclName();
1581 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1582 HiddenNames.insert(Identifier->getName());
1583 else
1584 HiddenNames.insert(Name.getAsString());
1585 }
1586}
1587
1588
Douglas Gregord46cf182010-08-16 20:01:48 +00001589void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1590 CodeCompletionContext Context,
1591 Result *Results,
1592 unsigned NumResults) {
1593 // Merge the results we were given with the results we cached.
1594 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001595 unsigned InContexts
1596 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1597 : (1 << (Context.getKind() - 1)));
1598
1599 // Contains the set of names that are hidden by "local" completion results.
1600 llvm::StringSet<> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001601 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
Douglas Gregord46cf182010-08-16 20:01:48 +00001602 typedef CodeCompleteConsumer::Result Result;
1603 llvm::SmallVector<Result, 8> AllResults;
1604 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001605 C = AST.cached_completion_begin(),
1606 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001607 C != CEnd; ++C) {
1608 // If the context we are in matches any of the contexts we are
1609 // interested in, we'll add this result.
1610 if ((C->ShowInContexts & InContexts) == 0)
1611 continue;
1612
1613 // If we haven't added any results previously, do so now.
1614 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001615 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1616 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001617 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1618 AddedResult = true;
1619 }
1620
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001621 // Determine whether this global completion result is hidden by a local
1622 // completion result. If so, skip it.
1623 if (C->Kind != CXCursor_MacroDefinition &&
1624 HiddenNames.count(C->Completion->getTypedText()))
1625 continue;
1626
Douglas Gregord46cf182010-08-16 20:01:48 +00001627 // Adjust priority based on similar type classes.
1628 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00001629 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001630 if (!Context.getPreferredType().isNull()) {
1631 if (C->Kind == CXCursor_MacroDefinition) {
1632 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor12785102010-08-24 20:21:13 +00001633 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001634 } else if (C->Type) {
1635 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001636 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001637 Context.getPreferredType().getUnqualifiedType());
1638 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1639 if (ExpectedSTC == C->TypeClass) {
1640 // We know this type is similar; check for an exact match.
1641 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001642 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001643 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001644 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001645 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1646 Priority /= CCF_ExactTypeMatch;
1647 else
1648 Priority /= CCF_SimilarTypeMatch;
1649 }
1650 }
1651 }
1652
Douglas Gregor12785102010-08-24 20:21:13 +00001653 // Adjust the completion string, if required.
1654 if (C->Kind == CXCursor_MacroDefinition &&
1655 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1656 // Create a new code-completion string that just contains the
1657 // macro name, without its arguments.
1658 Completion = new CodeCompletionString;
1659 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1660 StringsToDestroy.push_back(Completion);
1661 }
1662
1663 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001664 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001665 }
1666
1667 // If we did not add any cached completion results, just forward the
1668 // results we were given to the next consumer.
1669 if (!AddedResult) {
1670 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1671 return;
1672 }
1673
1674 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1675 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001676
1677 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1678 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001679}
1680
1681
1682
Douglas Gregor8e984da2010-08-04 16:47:14 +00001683void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1684 RemappedFile *RemappedFiles,
1685 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001686 bool IncludeMacros,
1687 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001688 CodeCompleteConsumer &Consumer,
1689 Diagnostic &Diag, LangOptions &LangOpts,
1690 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001691 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1692 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001693 if (!Invocation.get())
1694 return;
1695
Douglas Gregor028d3e42010-08-09 20:45:32 +00001696 llvm::Timer *CompletionTimer = 0;
1697 if (TimerGroup.get()) {
1698 llvm::SmallString<128> TimerName;
1699 llvm::raw_svector_ostream TimerNameOut(TimerName);
1700 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1701 << Column;
1702 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1703 CompletionTimer->startTimer();
1704 Timers.push_back(CompletionTimer);
1705 }
1706
Douglas Gregor8e984da2010-08-04 16:47:14 +00001707 CompilerInvocation CCInvocation(*Invocation);
1708 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1709 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001710
Douglas Gregorb14904c2010-08-13 22:48:40 +00001711 FrontendOpts.ShowMacrosInCodeCompletion
1712 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001713 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001714 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1715 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001716 FrontendOpts.CodeCompletionAt.FileName = File;
1717 FrontendOpts.CodeCompletionAt.Line = Line;
1718 FrontendOpts.CodeCompletionAt.Column = Column;
1719
Douglas Gregorb68bc592010-08-05 09:09:23 +00001720 // Turn on spell-checking when performing code completion. It leads
1721 // to better results.
1722 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1723 CCInvocation.getLangOpts().SpellChecking = 1;
1724
Douglas Gregor8e984da2010-08-04 16:47:14 +00001725 // Set the language options appropriately.
1726 LangOpts = CCInvocation.getLangOpts();
1727
1728 CompilerInstance Clang;
1729 Clang.setInvocation(&CCInvocation);
1730 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1731
1732 // Set up diagnostics, capturing any diagnostics produced.
1733 Clang.setDiagnostics(&Diag);
1734 CaptureDroppedDiagnostics Capture(true,
1735 Clang.getDiagnostics(),
1736 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001737
1738 // Create the target instance.
1739 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1740 Clang.getTargetOpts()));
1741 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001742 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001743 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1744 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001745 }
1746
1747 // Inform the target of the language options.
1748 //
1749 // FIXME: We shouldn't need to do this, the target should be immutable once
1750 // created. This complexity should be lifted elsewhere.
1751 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1752
1753 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1754 "Invocation must have exactly one source file!");
1755 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1756 "FIXME: AST inputs not yet supported here!");
1757 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1758 "IR inputs not support here!");
1759
1760
1761 // Use the source and file managers that we were given.
1762 Clang.setFileManager(&FileMgr);
1763 Clang.setSourceManager(&SourceMgr);
1764
1765 // Remap files.
1766 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001767 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001768 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001769 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1770 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001771 OwnedBuffers.push_back(RemappedFiles[I].second);
1772 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001773
Douglas Gregorb14904c2010-08-13 22:48:40 +00001774 // Use the code completion consumer we were given, but adding any cached
1775 // code-completion results.
1776 AugmentedCodeCompleteConsumer
1777 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001778 FrontendOpts.ShowCodePatternsInCodeCompletion,
1779 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001780 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001781
Douglas Gregor028d3e42010-08-09 20:45:32 +00001782 // If we have a precompiled preamble, try to use it. We only allow
1783 // the use of the precompiled preamble if we're if the completion
1784 // point is within the main file, after the end of the precompiled
1785 // preamble.
1786 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1787 if (!PreambleFile.empty()) {
1788 using llvm::sys::FileStatus;
1789 llvm::sys::PathWithStatus CompleteFilePath(File);
1790 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1791 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1792 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1793 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001794 OverrideMainBuffer
1795 = getMainBufferWithPrecompiledPreamble(CCInvocation, false, Line);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001796 }
1797
1798 // If the main file has been overridden due to the use of a preamble,
1799 // make that override happen and introduce the preamble.
1800 if (OverrideMainBuffer) {
1801 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1802 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1803 PreprocessorOpts.PrecompiledPreambleBytes.second
1804 = PreambleEndsAtStartOfLine;
1805 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1806 PreprocessorOpts.DisablePCHValidation = true;
1807
1808 // The stored diagnostics have the old source manager. Copy them
1809 // to our output set of stored diagnostics, updating the source
1810 // manager to the one we were given.
1811 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1812 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1813 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1814 StoredDiagnostics[I].setLocation(Loc);
1815 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00001816
1817 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001818 } else {
1819 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1820 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001821 }
1822
Douglas Gregor8e984da2010-08-04 16:47:14 +00001823 llvm::OwningPtr<SyntaxOnlyAction> Act;
1824 Act.reset(new SyntaxOnlyAction);
1825 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1826 Clang.getFrontendOpts().Inputs[0].first)) {
1827 Act->Execute();
1828 Act->EndSourceFile();
1829 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001830
1831 if (CompletionTimer)
1832 CompletionTimer->stopTimer();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001833
1834 // Steal back our resources.
1835 Clang.takeFileManager();
1836 Clang.takeSourceManager();
1837 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001838 Clang.takeCodeCompletionConsumer();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001839 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001840}
Douglas Gregore9386682010-08-13 05:36:37 +00001841
1842bool ASTUnit::Save(llvm::StringRef File) {
1843 if (getDiagnostics().hasErrorOccurred())
1844 return true;
1845
1846 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1847 // unconditionally create a stat cache when we parse the file?
1848 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001849 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1850 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001851 if (!ErrorInfo.empty() || Out.has_error())
1852 return true;
1853
1854 std::vector<unsigned char> Buffer;
1855 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001856 ASTWriter Writer(Stream);
1857 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001858
1859 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001860 if (!Buffer.empty())
1861 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001862 Out.close();
1863 return Out.has_error();
1864}